ddcutil-2.2.0/0000775000175000001440000000000014754576333006723 5ddcutil-2.2.0/config/0000775000175000001440000000000014754576330010165 5ddcutil-2.2.0/config/ar-lib0000755000175000001440000001336314671527764011212 #! /bin/sh # Wrapper for Microsoft lib.exe me=ar-lib scriptversion=2019-07-04.01; # UTC # Copyright (C) 2010-2021 Free Software Foundation, Inc. # Written by Peter Rosin . # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . # func_error message func_error () { echo "$me: $1" 1>&2 exit 1 } file_conv= # func_file_conv build_file # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN* | MSYS*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv in mingw) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin | msys) file=`cygpath -m "$file" || echo "$file"` ;; wine) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_at_file at_file operation archive # Iterate over all members in AT_FILE performing OPERATION on ARCHIVE # for each of them. # When interpreting the content of the @FILE, do NOT use func_file_conv, # since the user would need to supply preconverted file names to # binutils ar, at least for MinGW. func_at_file () { operation=$2 archive=$3 at_file_contents=`cat "$1"` eval set x "$at_file_contents" shift for member do $AR -NOLOGO $operation:"$member" "$archive" || exit $? done } case $1 in '') func_error "no command. Try '$0 --help' for more information." ;; -h | --h*) cat <. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . nl=' ' # We need space, tab and new line, in precisely that order. Quoting is # there to prevent tools from complaining about whitespace usage. IFS=" "" $nl" file_conv= # func_file_conv build_file lazy # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. If the determined conversion # type is listed in (the comma separated) LAZY, no conversion will # take place. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN* | MSYS*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv/,$2, in *,$file_conv,*) ;; mingw/*) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin/* | msys/*) file=`cygpath -m "$file" || echo "$file"` ;; wine/*) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_cl_dashL linkdir # Make cl look for libraries in LINKDIR func_cl_dashL () { func_file_conv "$1" if test -z "$lib_path"; then lib_path=$file else lib_path="$lib_path;$file" fi linker_opts="$linker_opts -LIBPATH:$file" } # func_cl_dashl library # Do a library search-path lookup for cl func_cl_dashl () { lib=$1 found=no save_IFS=$IFS IFS=';' for dir in $lib_path $LIB do IFS=$save_IFS if $shared && test -f "$dir/$lib.dll.lib"; then found=yes lib=$dir/$lib.dll.lib break fi if test -f "$dir/$lib.lib"; then found=yes lib=$dir/$lib.lib break fi if test -f "$dir/lib$lib.a"; then found=yes lib=$dir/lib$lib.a break fi done IFS=$save_IFS if test "$found" != yes; then lib=$lib.lib fi } # func_cl_wrapper cl arg... # Adjust compile command to suit cl func_cl_wrapper () { # Assume a capable shell lib_path= shared=: linker_opts= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. eat=1 case $2 in *.o | *.[oO][bB][jJ]) func_file_conv "$2" set x "$@" -Fo"$file" shift ;; *) func_file_conv "$2" set x "$@" -Fe"$file" shift ;; esac ;; -I) eat=1 func_file_conv "$2" mingw set x "$@" -I"$file" shift ;; -I*) func_file_conv "${1#-I}" mingw set x "$@" -I"$file" shift ;; -l) eat=1 func_cl_dashl "$2" set x "$@" "$lib" shift ;; -l*) func_cl_dashl "${1#-l}" set x "$@" "$lib" shift ;; -L) eat=1 func_cl_dashL "$2" ;; -L*) func_cl_dashL "${1#-L}" ;; -static) shared=false ;; -Wl,*) arg=${1#-Wl,} save_ifs="$IFS"; IFS=',' for flag in $arg; do IFS="$save_ifs" linker_opts="$linker_opts $flag" done IFS="$save_ifs" ;; -Xlinker) eat=1 linker_opts="$linker_opts $2" ;; -*) set x "$@" "$1" shift ;; *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) func_file_conv "$1" set x "$@" -Tp"$file" shift ;; *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) func_file_conv "$1" mingw set x "$@" "$file" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -n "$linker_opts"; then linker_opts="-link$linker_opts" fi exec "$@" $linker_opts exit 1 } eat= case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: compile [--help] [--version] PROGRAM [ARGS] Wrapper for compilers which do not understand '-c -o'. Remove '-o dest.o' from ARGS, run PROGRAM with the remaining arguments, and rename the output as expected. If you are trying to build a whole package this is not the right script to run: please start by reading the file 'INSTALL'. Report bugs to . EOF exit $? ;; -v | --v*) echo "compile $scriptversion" exit $? ;; cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \ icl | *[/\\]icl | icl.exe | *[/\\]icl.exe ) func_cl_wrapper "$@" # Doesn't return... ;; esac ofile= cfile= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. # So we strip '-o arg' only if arg is an object. eat=1 case $2 in *.o | *.obj) ofile=$2 ;; *) set x "$@" -o "$2" shift ;; esac ;; *.c) cfile=$1 set x "$@" "$1" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -z "$ofile" || test -z "$cfile"; then # If no '-o' option was seen then we might have been invoked from a # pattern rule where we don't need one. That is ok -- this is a # normal compilation that the losing compiler can handle. If no # '.c' file was seen then we are probably linking. That is also # ok. exec "$@" fi # Name of file we expect compiler to create. cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` # Create the lock directory. # Note: use '[/\\:.-]' here to ensure that we don't use the same name # that we are using for the .o file. Also, base the name on the expected # object file name, since that is what matters with a parallel build. lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d while true; do if mkdir "$lockdir" >/dev/null 2>&1; then break fi sleep 1 done # FIXME: race condition here if user kills between mkdir and trap. trap "rmdir '$lockdir'; exit 1" 1 2 15 # Run the compile. "$@" ret=$? if test -f "$cofile"; then test "$cofile" = "$ofile" || mv "$cofile" "$ofile" elif test -f "${cofile}bj"; then test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" fi rmdir "$lockdir" exit $ret # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: ddcutil-2.2.0/config/config.guess0000755000175000001440000014142314671527764012435 #!/usr/bin/sh # Attempt to guess a canonical system name. # Copyright 1992-2023 Free Software Foundation, Inc. # shellcheck disable=SC2006,SC2268 # see below for rationale timestamp='2023-06-23' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner; maintained since 2000 by Ben Elliston. # # You can get the latest version of this script from: # https://git.savannah.gnu.org/cgit/config.git/plain/config.guess # # Please send patches to . # The "shellcheck disable" line above the timestamp inhibits complaints # about features and limitations of the classic Bourne shell that were # superseded or lifted in POSIX. However, this script identifies a wide # variety of pre-POSIX systems that do not have POSIX shells at all, and # even some reasonably current systems (Solaris 10 as case-in-point) still # have a pre-POSIX /bin/sh. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system '$me' is run on. Options: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright 1992-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi # Just in case it came from the environment. GUESS= # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, 'CC_FOR_BUILD' used to be named 'HOST_CC'. We still # use 'HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. tmp= # shellcheck disable=SC2172 trap 'test -z "$tmp" || rm -fr "$tmp"' 0 1 2 13 15 set_cc_for_build() { # prevent multiple calls if $tmp is already set test "$tmp" && return 0 : "${TMPDIR=/tmp}" # shellcheck disable=SC2039,SC3028 { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir "$tmp" 2>/dev/null) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir "$tmp" 2>/dev/null) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } dummy=$tmp/dummy case ${CC_FOR_BUILD-},${HOST_CC-},${CC-} in ,,) echo "int x;" > "$dummy.c" for driver in cc gcc c89 c99 ; do if ($driver -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then CC_FOR_BUILD=$driver break fi done if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac } # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if test -f /.attbin/uname ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case $UNAME_SYSTEM in Linux|GNU|GNU/*) LIBC=unknown set_cc_for_build cat <<-EOF > "$dummy.c" #include #if defined(__UCLIBC__) LIBC=uclibc #elif defined(__dietlibc__) LIBC=dietlibc #elif defined(__GLIBC__) LIBC=gnu #else #include /* First heuristic to detect musl libc. */ #ifdef __DEFINED_va_list LIBC=musl #endif #endif EOF cc_set_libc=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` eval "$cc_set_libc" # Second heuristic to detect musl libc. if [ "$LIBC" = unknown ] && command -v ldd >/dev/null && ldd --version 2>&1 | grep -q ^musl; then LIBC=musl fi # If the system lacks a compiler, then just pick glibc. # We could probably try harder. if [ "$LIBC" = unknown ]; then LIBC=gnu fi ;; esac # Note: order is significant - the case branches are not exclusive. case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ /sbin/sysctl -n hw.machine_arch 2>/dev/null || \ /usr/sbin/sysctl -n hw.machine_arch 2>/dev/null || \ echo unknown)` case $UNAME_MACHINE_ARCH in aarch64eb) machine=aarch64_be-unknown ;; armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; earmv*) arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'` endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'` machine=${arch}${endian}-unknown ;; *) machine=$UNAME_MACHINE_ARCH-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently (or will in the future) and ABI. case $UNAME_MACHINE_ARCH in earm*) os=netbsdelf ;; arm*|i386|m68k|ns32k|sh3*|sparc|vax) set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # Determine ABI tags. case $UNAME_MACHINE_ARCH in earm*) expr='s/^earmv[0-9]/-eabi/;s/eb$//' abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"` ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case $UNAME_VERSION in Debian*) release='-gnu' ;; *) release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. GUESS=$machine-${os}${release}${abi-} ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-bitrig$UNAME_RELEASE ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-openbsd$UNAME_RELEASE ;; *:SecBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/SecBSD.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-secbsd$UNAME_RELEASE ;; *:LibertyBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` GUESS=$UNAME_MACHINE_ARCH-unknown-libertybsd$UNAME_RELEASE ;; *:MidnightBSD:*:*) GUESS=$UNAME_MACHINE-unknown-midnightbsd$UNAME_RELEASE ;; *:ekkoBSD:*:*) GUESS=$UNAME_MACHINE-unknown-ekkobsd$UNAME_RELEASE ;; *:SolidBSD:*:*) GUESS=$UNAME_MACHINE-unknown-solidbsd$UNAME_RELEASE ;; *:OS108:*:*) GUESS=$UNAME_MACHINE-unknown-os108_$UNAME_RELEASE ;; macppc:MirBSD:*:*) GUESS=powerpc-unknown-mirbsd$UNAME_RELEASE ;; *:MirBSD:*:*) GUESS=$UNAME_MACHINE-unknown-mirbsd$UNAME_RELEASE ;; *:Sortix:*:*) GUESS=$UNAME_MACHINE-unknown-sortix ;; *:Twizzler:*:*) GUESS=$UNAME_MACHINE-unknown-twizzler ;; *:Redox:*:*) GUESS=$UNAME_MACHINE-unknown-redox ;; mips:OSF1:*.*) GUESS=mips-dec-osf1 ;; alpha:OSF1:*:*) # Reset EXIT trap before exiting to avoid spurious non-zero exit code. trap '' 0 case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case $ALPHA_CPU_TYPE in "EV4 (21064)") UNAME_MACHINE=alpha ;; "EV4.5 (21064)") UNAME_MACHINE=alpha ;; "LCA4 (21066/21068)") UNAME_MACHINE=alpha ;; "EV5 (21164)") UNAME_MACHINE=alphaev5 ;; "EV5.6 (21164A)") UNAME_MACHINE=alphaev56 ;; "EV5.6 (21164PC)") UNAME_MACHINE=alphapca56 ;; "EV5.7 (21164PC)") UNAME_MACHINE=alphapca57 ;; "EV6 (21264)") UNAME_MACHINE=alphaev6 ;; "EV6.7 (21264A)") UNAME_MACHINE=alphaev67 ;; "EV6.8CB (21264C)") UNAME_MACHINE=alphaev68 ;; "EV6.8AL (21264B)") UNAME_MACHINE=alphaev68 ;; "EV6.8CX (21264D)") UNAME_MACHINE=alphaev68 ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE=alphaev69 ;; "EV7 (21364)") UNAME_MACHINE=alphaev7 ;; "EV7.9 (21364A)") UNAME_MACHINE=alphaev79 ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. OSF_REL=`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` GUESS=$UNAME_MACHINE-dec-osf$OSF_REL ;; Amiga*:UNIX_System_V:4.0:*) GUESS=m68k-unknown-sysv4 ;; *:[Aa]miga[Oo][Ss]:*:*) GUESS=$UNAME_MACHINE-unknown-amigaos ;; *:[Mm]orph[Oo][Ss]:*:*) GUESS=$UNAME_MACHINE-unknown-morphos ;; *:OS/390:*:*) GUESS=i370-ibm-openedition ;; *:z/VM:*:*) GUESS=s390-ibm-zvmoe ;; *:OS400:*:*) GUESS=powerpc-ibm-os400 ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) GUESS=arm-acorn-riscix$UNAME_RELEASE ;; arm*:riscos:*:*|arm*:RISCOS:*:*) GUESS=arm-unknown-riscos ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) GUESS=hppa1.1-hitachi-hiuxmpp ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. case `(/bin/universe) 2>/dev/null` in att) GUESS=pyramid-pyramid-sysv3 ;; *) GUESS=pyramid-pyramid-bsd ;; esac ;; NILE*:*:*:dcosx) GUESS=pyramid-pyramid-svr4 ;; DRS?6000:unix:4.0:6*) GUESS=sparc-icl-nx6 ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) GUESS=sparc-icl-nx7 ;; esac ;; s390x:SunOS:*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=$UNAME_MACHINE-ibm-solaris2$SUN_REL ;; sun4H:SunOS:5.*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=sparc-hal-solaris2$SUN_REL ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=sparc-sun-solaris2$SUN_REL ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) GUESS=i386-pc-auroraux$UNAME_RELEASE ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) set_cc_for_build SUN_ARCH=i386 # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if test "$CC_FOR_BUILD" != no_compiler_found; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -m64 -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH=x86_64 fi fi SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=$SUN_ARCH-pc-solaris2$SUN_REL ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=sparc-sun-solaris3$SUN_REL ;; sun4*:SunOS:*:*) case `/usr/bin/arch -k` in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like '4.1.3-JL'. SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/'` GUESS=sparc-sun-sunos$SUN_REL ;; sun3*:SunOS:*:*) GUESS=m68k-sun-sunos$UNAME_RELEASE ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3 case `/bin/arch` in sun3) GUESS=m68k-sun-sunos$UNAME_RELEASE ;; sun4) GUESS=sparc-sun-sunos$UNAME_RELEASE ;; esac ;; aushp:SunOS:*:*) GUESS=sparc-auspex-sunos$UNAME_RELEASE ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) GUESS=m68k-atari-mint$UNAME_RELEASE ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) GUESS=m68k-atari-mint$UNAME_RELEASE ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) GUESS=m68k-atari-mint$UNAME_RELEASE ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) GUESS=m68k-milan-mint$UNAME_RELEASE ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) GUESS=m68k-hades-mint$UNAME_RELEASE ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) GUESS=m68k-unknown-mint$UNAME_RELEASE ;; m68k:machten:*:*) GUESS=m68k-apple-machten$UNAME_RELEASE ;; powerpc:machten:*:*) GUESS=powerpc-apple-machten$UNAME_RELEASE ;; RISC*:Mach:*:*) GUESS=mips-dec-mach_bsd4.3 ;; RISC*:ULTRIX:*:*) GUESS=mips-dec-ultrix$UNAME_RELEASE ;; VAX*:ULTRIX*:*:*) GUESS=vax-dec-ultrix$UNAME_RELEASE ;; 2020:CLIX:*:* | 2430:CLIX:*:*) GUESS=clipper-intergraph-clix$UNAME_RELEASE ;; mips:*:*:UMIPS | mips:*:*:RISCos) set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" && dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`"$dummy" "$dummyarg"` && { echo "$SYSTEM_NAME"; exit; } GUESS=mips-mips-riscos$UNAME_RELEASE ;; Motorola:PowerMAX_OS:*:*) GUESS=powerpc-motorola-powermax ;; Motorola:*:4.3:PL8-*) GUESS=powerpc-harris-powermax ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) GUESS=powerpc-harris-powermax ;; Night_Hawk:Power_UNIX:*:*) GUESS=powerpc-harris-powerunix ;; m88k:CX/UX:7*:*) GUESS=m88k-harris-cxux7 ;; m88k:*:4*:R4*) GUESS=m88k-motorola-sysv4 ;; m88k:*:3*:R3*) GUESS=m88k-motorola-sysv3 ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if test "$UNAME_PROCESSOR" = mc88100 || test "$UNAME_PROCESSOR" = mc88110 then if test "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx || \ test "$TARGET_BINARY_INTERFACE"x = x then GUESS=m88k-dg-dgux$UNAME_RELEASE else GUESS=m88k-dg-dguxbcs$UNAME_RELEASE fi else GUESS=i586-dg-dgux$UNAME_RELEASE fi ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) GUESS=m88k-dolphin-sysv3 ;; M88*:*:R3*:*) # Delta 88k system running SVR3 GUESS=m88k-motorola-sysv3 ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) GUESS=m88k-tektronix-sysv3 ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) GUESS=m68k-tektronix-bsd ;; *:IRIX*:*:*) IRIX_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/g'` GUESS=mips-sgi-irix$IRIX_REL ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. GUESS=romp-ibm-aix # uname -m gives an 8 hex-code CPU id ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) GUESS=i386-ibm-aix ;; ia64:AIX:*:*) if test -x /usr/bin/oslevel ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=$UNAME_VERSION.$UNAME_RELEASE fi GUESS=$UNAME_MACHINE-ibm-aix$IBM_REV ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` then GUESS=$SYSTEM_NAME else GUESS=rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then GUESS=rs6000-ibm-aix3.2.4 else GUESS=rs6000-ibm-aix3.2 fi ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if test -x /usr/bin/lslpp ; then IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | \ awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else IBM_REV=$UNAME_VERSION.$UNAME_RELEASE fi GUESS=$IBM_ARCH-ibm-aix$IBM_REV ;; *:AIX:*:*) GUESS=rs6000-ibm-aix ;; ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*) GUESS=romp-ibm-bsd4.4 ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and GUESS=romp-ibm-bsd$UNAME_RELEASE # 4.3 with uname added to ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) GUESS=rs6000-bull-bosx ;; DPX/2?00:B.O.S.:*:*) GUESS=m68k-bull-sysv3 ;; 9000/[34]??:4.3bsd:1.*:*) GUESS=m68k-hp-bsd ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) GUESS=m68k-hp-bsd4.4 ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` case $UNAME_MACHINE in 9000/31?) HP_ARCH=m68000 ;; 9000/[34]??) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if test -x /usr/bin/getconf; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case $sc_cpu_version in 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case $sc_kernel_bits in 32) HP_ARCH=hppa2.0n ;; 64) HP_ARCH=hppa2.0w ;; '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 esac ;; esac fi if test "$HP_ARCH" = ""; then set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if test "$HP_ARCH" = hppa2.0w then set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH=hppa2.0w else HP_ARCH=hppa64 fi fi GUESS=$HP_ARCH-hp-hpux$HPUX_REV ;; ia64:HP-UX:*:*) HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` GUESS=ia64-hp-hpux$HPUX_REV ;; 3050*:HI-UX:*:*) set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } GUESS=unknown-hitachi-hiuxwe2 ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*) GUESS=hppa1.1-hp-bsd ;; 9000/8??:4.3bsd:*:*) GUESS=hppa1.0-hp-bsd ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) GUESS=hppa1.0-hp-mpeix ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*) GUESS=hppa1.1-hp-osf ;; hp8??:OSF1:*:*) GUESS=hppa1.0-hp-osf ;; i*86:OSF1:*:*) if test -x /usr/sbin/sysversion ; then GUESS=$UNAME_MACHINE-unknown-osf1mk else GUESS=$UNAME_MACHINE-unknown-osf1 fi ;; parisc*:Lites*:*:*) GUESS=hppa1.1-hp-lites ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) GUESS=c1-convex-bsd ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) GUESS=c34-convex-bsd ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) GUESS=c38-convex-bsd ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) GUESS=c4-convex-bsd ;; CRAY*Y-MP:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=ymp-cray-unicos$CRAY_REL ;; CRAY*[A-Z]90:*:*:*) echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=t90-cray-unicos$CRAY_REL ;; CRAY*T3E:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=alphaev5-cray-unicosmk$CRAY_REL ;; CRAY*SV1:*:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=sv1-cray-unicos$CRAY_REL ;; *:UNICOS/mp:*:*) CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` GUESS=craynv-cray-unicosmp$CRAY_REL ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'` GUESS=${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` GUESS=sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) GUESS=$UNAME_MACHINE-pc-bsdi$UNAME_RELEASE ;; sparc*:BSD/OS:*:*) GUESS=sparc-unknown-bsdi$UNAME_RELEASE ;; *:BSD/OS:*:*) GUESS=$UNAME_MACHINE-unknown-bsdi$UNAME_RELEASE ;; arm:FreeBSD:*:*) UNAME_PROCESSOR=`uname -p` set_cc_for_build if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabi else FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabihf fi ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case $UNAME_PROCESSOR in amd64) UNAME_PROCESSOR=x86_64 ;; i386) UNAME_PROCESSOR=i586 ;; esac FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL ;; i*:CYGWIN*:*) GUESS=$UNAME_MACHINE-pc-cygwin ;; *:MINGW64*:*) GUESS=$UNAME_MACHINE-pc-mingw64 ;; *:MINGW*:*) GUESS=$UNAME_MACHINE-pc-mingw32 ;; *:MSYS*:*) GUESS=$UNAME_MACHINE-pc-msys ;; i*:PW*:*) GUESS=$UNAME_MACHINE-pc-pw32 ;; *:SerenityOS:*:*) GUESS=$UNAME_MACHINE-pc-serenity ;; *:Interix*:*) case $UNAME_MACHINE in x86) GUESS=i586-pc-interix$UNAME_RELEASE ;; authenticamd | genuineintel | EM64T) GUESS=x86_64-unknown-interix$UNAME_RELEASE ;; IA64) GUESS=ia64-unknown-interix$UNAME_RELEASE ;; esac ;; i*:UWIN*:*) GUESS=$UNAME_MACHINE-pc-uwin ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) GUESS=x86_64-pc-cygwin ;; prep*:SunOS:5.*:*) SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` GUESS=powerpcle-unknown-solaris2$SUN_REL ;; *:GNU:*:*) # the GNU system GNU_ARCH=`echo "$UNAME_MACHINE" | sed -e 's,[-/].*$,,'` GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's,/.*$,,'` GUESS=$GNU_ARCH-unknown-$LIBC$GNU_REL ;; *:GNU/*:*:*) # other systems with GNU libc and userland GNU_SYS=`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"` GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_MACHINE-unknown-$GNU_SYS$GNU_REL-$LIBC ;; x86_64:[Mm]anagarm:*:*|i?86:[Mm]anagarm:*:*) GUESS="$UNAME_MACHINE-pc-managarm-mlibc" ;; *:[Mm]anagarm:*:*) GUESS="$UNAME_MACHINE-unknown-managarm-mlibc" ;; *:Minix:*:*) GUESS=$UNAME_MACHINE-unknown-minix ;; aarch64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' /proc/cpuinfo 2>/dev/null` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC=gnulibc1 ; fi GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; arc:Linux:*:* | arceb:Linux:*:* | arc32:Linux:*:* | arc64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; arm*:Linux:*:*) set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then GUESS=$UNAME_MACHINE-unknown-linux-$LIBC else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabi else GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabihf fi fi ;; avr32*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; cris:Linux:*:*) GUESS=$UNAME_MACHINE-axis-linux-$LIBC ;; crisv32:Linux:*:*) GUESS=$UNAME_MACHINE-axis-linux-$LIBC ;; e2k:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; frv:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; hexagon:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; i*86:Linux:*:*) GUESS=$UNAME_MACHINE-pc-linux-$LIBC ;; ia64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; k1om:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; loongarch32:Linux:*:* | loongarch64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; m32r*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; m68*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; mips:Linux:*:* | mips64:Linux:*:*) set_cc_for_build IS_GLIBC=0 test x"${LIBC}" = xgnu && IS_GLIBC=1 sed 's/^ //' << EOF > "$dummy.c" #undef CPU #undef mips #undef mipsel #undef mips64 #undef mips64el #if ${IS_GLIBC} && defined(_ABI64) LIBCABI=gnuabi64 #else #if ${IS_GLIBC} && defined(_ABIN32) LIBCABI=gnuabin32 #else LIBCABI=${LIBC} #endif #endif #if ${IS_GLIBC} && defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 CPU=mipsisa64r6 #else #if ${IS_GLIBC} && !defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 CPU=mipsisa32r6 #else #if defined(__mips64) CPU=mips64 #else CPU=mips #endif #endif #endif #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) MIPS_ENDIAN=el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) MIPS_ENDIAN= #else MIPS_ENDIAN= #endif #endif EOF cc_set_vars=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU\|^MIPS_ENDIAN\|^LIBCABI'` eval "$cc_set_vars" test "x$CPU" != x && { echo "$CPU${MIPS_ENDIAN}-unknown-linux-$LIBCABI"; exit; } ;; mips64el:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; openrisc*:Linux:*:*) GUESS=or1k-unknown-linux-$LIBC ;; or32:Linux:*:* | or1k*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; padre:Linux:*:*) GUESS=sparc-unknown-linux-$LIBC ;; parisc64:Linux:*:* | hppa64:Linux:*:*) GUESS=hppa64-unknown-linux-$LIBC ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) GUESS=hppa1.1-unknown-linux-$LIBC ;; PA8*) GUESS=hppa2.0-unknown-linux-$LIBC ;; *) GUESS=hppa-unknown-linux-$LIBC ;; esac ;; ppc64:Linux:*:*) GUESS=powerpc64-unknown-linux-$LIBC ;; ppc:Linux:*:*) GUESS=powerpc-unknown-linux-$LIBC ;; ppc64le:Linux:*:*) GUESS=powerpc64le-unknown-linux-$LIBC ;; ppcle:Linux:*:*) GUESS=powerpcle-unknown-linux-$LIBC ;; riscv32:Linux:*:* | riscv32be:Linux:*:* | riscv64:Linux:*:* | riscv64be:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; s390:Linux:*:* | s390x:Linux:*:*) GUESS=$UNAME_MACHINE-ibm-linux-$LIBC ;; sh64*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; sh*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; sparc:Linux:*:* | sparc64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; tile*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; vax:Linux:*:*) GUESS=$UNAME_MACHINE-dec-linux-$LIBC ;; x86_64:Linux:*:*) set_cc_for_build CPU=$UNAME_MACHINE LIBCABI=$LIBC if test "$CC_FOR_BUILD" != no_compiler_found; then ABI=64 sed 's/^ //' << EOF > "$dummy.c" #ifdef __i386__ ABI=x86 #else #ifdef __ILP32__ ABI=x32 #endif #endif EOF cc_set_abi=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^ABI' | sed 's, ,,g'` eval "$cc_set_abi" case $ABI in x86) CPU=i686 ;; x32) LIBCABI=${LIBC}x32 ;; esac fi GUESS=$CPU-pc-linux-$LIBCABI ;; xtensa*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. GUESS=i386-sequent-sysv4 ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. GUESS=$UNAME_MACHINE-pc-sysv4.2uw$UNAME_VERSION ;; i*86:OS/2:*:*) # If we were able to find 'uname', then EMX Unix compatibility # is probably installed. GUESS=$UNAME_MACHINE-pc-os2-emx ;; i*86:XTS-300:*:STOP) GUESS=$UNAME_MACHINE-unknown-stop ;; i*86:atheos:*:*) GUESS=$UNAME_MACHINE-unknown-atheos ;; i*86:syllable:*:*) GUESS=$UNAME_MACHINE-pc-syllable ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) GUESS=i386-unknown-lynxos$UNAME_RELEASE ;; i*86:*DOS:*:*) GUESS=$UNAME_MACHINE-pc-msdosdjgpp ;; i*86:*:4.*:*) UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then GUESS=$UNAME_MACHINE-univel-sysv$UNAME_REL else GUESS=$UNAME_MACHINE-pc-sysv$UNAME_REL fi ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac GUESS=$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 GUESS=$UNAME_MACHINE-pc-sco$UNAME_REL else GUESS=$UNAME_MACHINE-pc-sysv32 fi ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configure will decide that # this is a cross-build. GUESS=i586-pc-msdosdjgpp ;; Intel:Mach:3*:*) GUESS=i386-pc-mach3 ;; paragon:*:*:*) GUESS=i860-intel-osf1 ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then GUESS=i860-stardent-sysv$UNAME_RELEASE # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. GUESS=i860-unknown-sysv$UNAME_RELEASE # Unknown i860-SVR4 fi ;; mini*:CTIX:SYS*5:*) # "miniframe" GUESS=m68010-convergent-sysv ;; mc68k:UNIX:SYSTEM5:3.51m) GUESS=m68k-convergent-sysv ;; M680?0:D-NIX:5.3:*) GUESS=m68k-diab-dnix ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) GUESS=m68k-unknown-lynxos$UNAME_RELEASE ;; mc68030:UNIX_System_V:4.*:*) GUESS=m68k-atari-sysv4 ;; TSUNAMI:LynxOS:2.*:*) GUESS=sparc-unknown-lynxos$UNAME_RELEASE ;; rs6000:LynxOS:2.*:*) GUESS=rs6000-unknown-lynxos$UNAME_RELEASE ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) GUESS=powerpc-unknown-lynxos$UNAME_RELEASE ;; SM[BE]S:UNIX_SV:*:*) GUESS=mips-dde-sysv$UNAME_RELEASE ;; RM*:ReliantUNIX-*:*:*) GUESS=mips-sni-sysv4 ;; RM*:SINIX-*:*:*) GUESS=mips-sni-sysv4 ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` GUESS=$UNAME_MACHINE-sni-sysv4 else GUESS=ns32k-sni-sysv fi ;; PENTIUM:*:4.0*:*) # Unisys 'ClearPath HMP IX 4000' SVR4/MP effort # says GUESS=i586-unisys-sysv4 ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm GUESS=hppa1.1-stratus-sysv4 ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. GUESS=i860-stratus-sysv4 ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. GUESS=$UNAME_MACHINE-stratus-vos ;; *:VOS:*:*) # From Paul.Green@stratus.com. GUESS=hppa1.1-stratus-vos ;; mc68*:A/UX:*:*) GUESS=m68k-apple-aux$UNAME_RELEASE ;; news*:NEWS-OS:6*:*) GUESS=mips-sony-newsos6 ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if test -d /usr/nec; then GUESS=mips-nec-sysv$UNAME_RELEASE else GUESS=mips-unknown-sysv$UNAME_RELEASE fi ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. GUESS=powerpc-be-beos ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. GUESS=powerpc-apple-beos ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. GUESS=i586-pc-beos ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. GUESS=i586-pc-haiku ;; ppc:Haiku:*:*) # Haiku running on Apple PowerPC GUESS=powerpc-apple-haiku ;; *:Haiku:*:*) # Haiku modern gcc (not bound by BeOS compat) GUESS=$UNAME_MACHINE-unknown-haiku ;; SX-4:SUPER-UX:*:*) GUESS=sx4-nec-superux$UNAME_RELEASE ;; SX-5:SUPER-UX:*:*) GUESS=sx5-nec-superux$UNAME_RELEASE ;; SX-6:SUPER-UX:*:*) GUESS=sx6-nec-superux$UNAME_RELEASE ;; SX-7:SUPER-UX:*:*) GUESS=sx7-nec-superux$UNAME_RELEASE ;; SX-8:SUPER-UX:*:*) GUESS=sx8-nec-superux$UNAME_RELEASE ;; SX-8R:SUPER-UX:*:*) GUESS=sx8r-nec-superux$UNAME_RELEASE ;; SX-ACE:SUPER-UX:*:*) GUESS=sxace-nec-superux$UNAME_RELEASE ;; Power*:Rhapsody:*:*) GUESS=powerpc-apple-rhapsody$UNAME_RELEASE ;; *:Rhapsody:*:*) GUESS=$UNAME_MACHINE-apple-rhapsody$UNAME_RELEASE ;; arm64:Darwin:*:*) GUESS=aarch64-apple-darwin$UNAME_RELEASE ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` case $UNAME_PROCESSOR in unknown) UNAME_PROCESSOR=powerpc ;; esac if command -v xcode-select > /dev/null 2> /dev/null && \ ! xcode-select --print-path > /dev/null 2> /dev/null ; then # Avoid executing cc if there is no toolchain installed as # cc will be a stub that puts up a graphical alert # prompting the user to install developer tools. CC_FOR_BUILD=no_compiler_found else set_cc_for_build fi if test "$CC_FOR_BUILD" != no_compiler_found; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_PPC >/dev/null then UNAME_PROCESSOR=powerpc fi elif test "$UNAME_PROCESSOR" = i386 ; then # uname -m returns i386 or x86_64 UNAME_PROCESSOR=$UNAME_MACHINE fi GUESS=$UNAME_PROCESSOR-apple-darwin$UNAME_RELEASE ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = x86; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi GUESS=$UNAME_PROCESSOR-$UNAME_MACHINE-nto-qnx$UNAME_RELEASE ;; *:QNX:*:4*) GUESS=i386-pc-qnx ;; NEO-*:NONSTOP_KERNEL:*:*) GUESS=neo-tandem-nsk$UNAME_RELEASE ;; NSE-*:NONSTOP_KERNEL:*:*) GUESS=nse-tandem-nsk$UNAME_RELEASE ;; NSR-*:NONSTOP_KERNEL:*:*) GUESS=nsr-tandem-nsk$UNAME_RELEASE ;; NSV-*:NONSTOP_KERNEL:*:*) GUESS=nsv-tandem-nsk$UNAME_RELEASE ;; NSX-*:NONSTOP_KERNEL:*:*) GUESS=nsx-tandem-nsk$UNAME_RELEASE ;; *:NonStop-UX:*:*) GUESS=mips-compaq-nonstopux ;; BS2000:POSIX*:*:*) GUESS=bs2000-siemens-sysv ;; DS/*:UNIX_System_V:*:*) GUESS=$UNAME_MACHINE-$UNAME_SYSTEM-$UNAME_RELEASE ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "${cputype-}" = 386; then UNAME_MACHINE=i386 elif test "x${cputype-}" != x; then UNAME_MACHINE=$cputype fi GUESS=$UNAME_MACHINE-unknown-plan9 ;; *:TOPS-10:*:*) GUESS=pdp10-unknown-tops10 ;; *:TENEX:*:*) GUESS=pdp10-unknown-tenex ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) GUESS=pdp10-dec-tops20 ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) GUESS=pdp10-xkl-tops20 ;; *:TOPS-20:*:*) GUESS=pdp10-unknown-tops20 ;; *:ITS:*:*) GUESS=pdp10-unknown-its ;; SEI:*:*:SEIUX) GUESS=mips-sei-seiux$UNAME_RELEASE ;; *:DragonFly:*:*) DRAGONFLY_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_MACHINE-unknown-dragonfly$DRAGONFLY_REL ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case $UNAME_MACHINE in A*) GUESS=alpha-dec-vms ;; I*) GUESS=ia64-dec-vms ;; V*) GUESS=vax-dec-vms ;; esac ;; *:XENIX:*:SysV) GUESS=i386-pc-xenix ;; i*86:skyos:*:*) SKYOS_REL=`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'` GUESS=$UNAME_MACHINE-pc-skyos$SKYOS_REL ;; i*86:rdos:*:*) GUESS=$UNAME_MACHINE-pc-rdos ;; i*86:Fiwix:*:*) GUESS=$UNAME_MACHINE-pc-fiwix ;; *:AROS:*:*) GUESS=$UNAME_MACHINE-unknown-aros ;; x86_64:VMkernel:*:*) GUESS=$UNAME_MACHINE-unknown-esx ;; amd64:Isilon\ OneFS:*:*) GUESS=x86_64-unknown-onefs ;; *:Unleashed:*:*) GUESS=$UNAME_MACHINE-unknown-unleashed$UNAME_RELEASE ;; esac # Do we have a guess based on uname results? if test "x$GUESS" != x; then echo "$GUESS" exit fi # No uname command or uname output not recognized. set_cc_for_build cat > "$dummy.c" < #include #endif #if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) #if defined (vax) || defined (__vax) || defined (__vax__) || defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) #include #if defined(_SIZE_T_) || defined(SIGLOST) #include #endif #endif #endif main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) #if !defined (ultrix) #include #if defined (BSD) #if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); #else #if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); #else printf ("vax-dec-bsd\n"); exit (0); #endif #endif #else printf ("vax-dec-bsd\n"); exit (0); #endif #else #if defined(_SIZE_T_) || defined(SIGLOST) struct utsname un; uname (&un); printf ("vax-dec-ultrix%s\n", un.release); exit (0); #else printf ("vax-dec-ultrix\n"); exit (0); #endif #endif #endif #if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) #if defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) #if defined(_SIZE_T_) || defined(SIGLOST) struct utsname *un; uname (&un); printf ("mips-dec-ultrix%s\n", un.release); exit (0); #else printf ("mips-dec-ultrix\n"); exit (0); #endif #endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. test -d /usr/apollo && { echo "$ISP-apollo-$SYSTYPE"; exit; } echo "$0: unable to guess system type" >&2 case $UNAME_MACHINE:$UNAME_SYSTEM in mips:Linux | mips64:Linux) # If we got here on MIPS GNU/Linux, output extra information. cat >&2 <&2 <&2 </dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = "$UNAME_MACHINE" UNAME_RELEASE = "$UNAME_RELEASE" UNAME_SYSTEM = "$UNAME_SYSTEM" UNAME_VERSION = "$UNAME_VERSION" EOF fi exit 1 # Local variables: # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: ddcutil-2.2.0/config/config.sub0000755000175000001440000010572414671527764012104 #!/usr/bin/sh # Configuration validation subroutine script. # Copyright 1992-2023 Free Software Foundation, Inc. # shellcheck disable=SC2006,SC2268 # see below for rationale timestamp='2023-06-23' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # Please send patches to . # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # https://git.savannah.gnu.org/cgit/config.git/plain/config.sub # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. # The "shellcheck disable" line above the timestamp inhibits complaints # about features and limitations of the classic Bourne shell that were # superseded or lifted in POSIX. However, this script identifies a wide # variety of pre-POSIX systems that do not have POSIX shells at all, and # even some reasonably current systems (Solaris 10 as case-in-point) still # have a pre-POSIX /bin/sh. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS Canonicalize a configuration name. Options: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright 1992-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; *local*) # First pass through any local machine types. echo "$1" exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Split fields of configuration type # shellcheck disable=SC2162 saved_IFS=$IFS IFS="-" read field1 field2 field3 field4 <&2 exit 1 ;; *-*-*-*) basic_machine=$field1-$field2 basic_os=$field3-$field4 ;; *-*-*) # Ambiguous whether COMPANY is present, or skipped and KERNEL-OS is two # parts maybe_os=$field2-$field3 case $maybe_os in nto-qnx* | linux-* | uclinux-uclibc* \ | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* \ | netbsd*-eabi* | kopensolaris*-gnu* | cloudabi*-eabi* \ | storm-chaos* | os2-emx* | rtmk-nova* | managarm-*) basic_machine=$field1 basic_os=$maybe_os ;; android-linux) basic_machine=$field1-unknown basic_os=linux-android ;; *) basic_machine=$field1-$field2 basic_os=$field3 ;; esac ;; *-*) # A lone config we happen to match not fitting any pattern case $field1-$field2 in decstation-3100) basic_machine=mips-dec basic_os= ;; *-*) # Second component is usually, but not always the OS case $field2 in # Prevent following clause from handling this valid os sun*os*) basic_machine=$field1 basic_os=$field2 ;; zephyr*) basic_machine=$field1-unknown basic_os=$field2 ;; # Manufacturers dec* | mips* | sequent* | encore* | pc533* | sgi* | sony* \ | att* | 7300* | 3300* | delta* | motorola* | sun[234]* \ | unicom* | ibm* | next | hp | isi* | apollo | altos* \ | convergent* | ncr* | news | 32* | 3600* | 3100* \ | hitachi* | c[123]* | convex* | sun | crds | omron* | dg \ | ultra | tti* | harris | dolphin | highlevel | gould \ | cbm | ns | masscomp | apple | axis | knuth | cray \ | microblaze* | sim | cisco \ | oki | wec | wrs | winbond) basic_machine=$field1-$field2 basic_os= ;; *) basic_machine=$field1 basic_os=$field2 ;; esac ;; esac ;; *) # Convert single-component short-hands not valid as part of # multi-component configurations. case $field1 in 386bsd) basic_machine=i386-pc basic_os=bsd ;; a29khif) basic_machine=a29k-amd basic_os=udi ;; adobe68k) basic_machine=m68010-adobe basic_os=scout ;; alliant) basic_machine=fx80-alliant basic_os= ;; altos | altos3068) basic_machine=m68k-altos basic_os= ;; am29k) basic_machine=a29k-none basic_os=bsd ;; amdahl) basic_machine=580-amdahl basic_os=sysv ;; amiga) basic_machine=m68k-unknown basic_os= ;; amigaos | amigados) basic_machine=m68k-unknown basic_os=amigaos ;; amigaunix | amix) basic_machine=m68k-unknown basic_os=sysv4 ;; apollo68) basic_machine=m68k-apollo basic_os=sysv ;; apollo68bsd) basic_machine=m68k-apollo basic_os=bsd ;; aros) basic_machine=i386-pc basic_os=aros ;; aux) basic_machine=m68k-apple basic_os=aux ;; balance) basic_machine=ns32k-sequent basic_os=dynix ;; blackfin) basic_machine=bfin-unknown basic_os=linux ;; cegcc) basic_machine=arm-unknown basic_os=cegcc ;; convex-c1) basic_machine=c1-convex basic_os=bsd ;; convex-c2) basic_machine=c2-convex basic_os=bsd ;; convex-c32) basic_machine=c32-convex basic_os=bsd ;; convex-c34) basic_machine=c34-convex basic_os=bsd ;; convex-c38) basic_machine=c38-convex basic_os=bsd ;; cray) basic_machine=j90-cray basic_os=unicos ;; crds | unos) basic_machine=m68k-crds basic_os= ;; da30) basic_machine=m68k-da30 basic_os= ;; decstation | pmax | pmin | dec3100 | decstatn) basic_machine=mips-dec basic_os= ;; delta88) basic_machine=m88k-motorola basic_os=sysv3 ;; dicos) basic_machine=i686-pc basic_os=dicos ;; djgpp) basic_machine=i586-pc basic_os=msdosdjgpp ;; ebmon29k) basic_machine=a29k-amd basic_os=ebmon ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson basic_os=ose ;; gmicro) basic_machine=tron-gmicro basic_os=sysv ;; go32) basic_machine=i386-pc basic_os=go32 ;; h8300hms) basic_machine=h8300-hitachi basic_os=hms ;; h8300xray) basic_machine=h8300-hitachi basic_os=xray ;; h8500hms) basic_machine=h8500-hitachi basic_os=hms ;; harris) basic_machine=m88k-harris basic_os=sysv3 ;; hp300 | hp300hpux) basic_machine=m68k-hp basic_os=hpux ;; hp300bsd) basic_machine=m68k-hp basic_os=bsd ;; hppaosf) basic_machine=hppa1.1-hp basic_os=osf ;; hppro) basic_machine=hppa1.1-hp basic_os=proelf ;; i386mach) basic_machine=i386-mach basic_os=mach ;; isi68 | isi) basic_machine=m68k-isi basic_os=sysv ;; m68knommu) basic_machine=m68k-unknown basic_os=linux ;; magnum | m3230) basic_machine=mips-mips basic_os=sysv ;; merlin) basic_machine=ns32k-utek basic_os=sysv ;; mingw64) basic_machine=x86_64-pc basic_os=mingw64 ;; mingw32) basic_machine=i686-pc basic_os=mingw32 ;; mingw32ce) basic_machine=arm-unknown basic_os=mingw32ce ;; monitor) basic_machine=m68k-rom68k basic_os=coff ;; morphos) basic_machine=powerpc-unknown basic_os=morphos ;; moxiebox) basic_machine=moxie-unknown basic_os=moxiebox ;; msdos) basic_machine=i386-pc basic_os=msdos ;; msys) basic_machine=i686-pc basic_os=msys ;; mvs) basic_machine=i370-ibm basic_os=mvs ;; nacl) basic_machine=le32-unknown basic_os=nacl ;; ncr3000) basic_machine=i486-ncr basic_os=sysv4 ;; netbsd386) basic_machine=i386-pc basic_os=netbsd ;; netwinder) basic_machine=armv4l-rebel basic_os=linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony basic_os=newsos ;; news1000) basic_machine=m68030-sony basic_os=newsos ;; necv70) basic_machine=v70-nec basic_os=sysv ;; nh3000) basic_machine=m68k-harris basic_os=cxux ;; nh[45]000) basic_machine=m88k-harris basic_os=cxux ;; nindy960) basic_machine=i960-intel basic_os=nindy ;; mon960) basic_machine=i960-intel basic_os=mon960 ;; nonstopux) basic_machine=mips-compaq basic_os=nonstopux ;; os400) basic_machine=powerpc-ibm basic_os=os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson basic_os=ose ;; os68k) basic_machine=m68k-none basic_os=os68k ;; paragon) basic_machine=i860-intel basic_os=osf ;; parisc) basic_machine=hppa-unknown basic_os=linux ;; psp) basic_machine=mipsallegrexel-sony basic_os=psp ;; pw32) basic_machine=i586-unknown basic_os=pw32 ;; rdos | rdos64) basic_machine=x86_64-pc basic_os=rdos ;; rdos32) basic_machine=i386-pc basic_os=rdos ;; rom68k) basic_machine=m68k-rom68k basic_os=coff ;; sa29200) basic_machine=a29k-amd basic_os=udi ;; sei) basic_machine=mips-sei basic_os=seiux ;; sequent) basic_machine=i386-sequent basic_os= ;; sps7) basic_machine=m68k-bull basic_os=sysv2 ;; st2000) basic_machine=m68k-tandem basic_os= ;; stratus) basic_machine=i860-stratus basic_os=sysv4 ;; sun2) basic_machine=m68000-sun basic_os= ;; sun2os3) basic_machine=m68000-sun basic_os=sunos3 ;; sun2os4) basic_machine=m68000-sun basic_os=sunos4 ;; sun3) basic_machine=m68k-sun basic_os= ;; sun3os3) basic_machine=m68k-sun basic_os=sunos3 ;; sun3os4) basic_machine=m68k-sun basic_os=sunos4 ;; sun4) basic_machine=sparc-sun basic_os= ;; sun4os3) basic_machine=sparc-sun basic_os=sunos3 ;; sun4os4) basic_machine=sparc-sun basic_os=sunos4 ;; sun4sol2) basic_machine=sparc-sun basic_os=solaris2 ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun basic_os= ;; sv1) basic_machine=sv1-cray basic_os=unicos ;; symmetry) basic_machine=i386-sequent basic_os=dynix ;; t3e) basic_machine=alphaev5-cray basic_os=unicos ;; t90) basic_machine=t90-cray basic_os=unicos ;; toad1) basic_machine=pdp10-xkl basic_os=tops20 ;; tpf) basic_machine=s390x-ibm basic_os=tpf ;; udi29k) basic_machine=a29k-amd basic_os=udi ;; ultra3) basic_machine=a29k-nyu basic_os=sym1 ;; v810 | necv810) basic_machine=v810-nec basic_os=none ;; vaxv) basic_machine=vax-dec basic_os=sysv ;; vms) basic_machine=vax-dec basic_os=vms ;; vsta) basic_machine=i386-pc basic_os=vsta ;; vxworks960) basic_machine=i960-wrs basic_os=vxworks ;; vxworks68) basic_machine=m68k-wrs basic_os=vxworks ;; vxworks29k) basic_machine=a29k-wrs basic_os=vxworks ;; xbox) basic_machine=i686-pc basic_os=mingw32 ;; ymp) basic_machine=ymp-cray basic_os=unicos ;; *) basic_machine=$1 basic_os= ;; esac ;; esac # Decode 1-component or ad-hoc basic machines case $basic_machine in # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) cpu=hppa1.1 vendor=winbond ;; op50n) cpu=hppa1.1 vendor=oki ;; op60c) cpu=hppa1.1 vendor=oki ;; ibm*) cpu=i370 vendor=ibm ;; orion105) cpu=clipper vendor=highlevel ;; mac | mpw | mac-mpw) cpu=m68k vendor=apple ;; pmac | pmac-mpw) cpu=powerpc vendor=apple ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) cpu=m68000 vendor=att ;; 3b*) cpu=we32k vendor=att ;; bluegene*) cpu=powerpc vendor=ibm basic_os=cnk ;; decsystem10* | dec10*) cpu=pdp10 vendor=dec basic_os=tops10 ;; decsystem20* | dec20*) cpu=pdp10 vendor=dec basic_os=tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) cpu=m68k vendor=motorola ;; dpx2*) cpu=m68k vendor=bull basic_os=sysv3 ;; encore | umax | mmax) cpu=ns32k vendor=encore ;; elxsi) cpu=elxsi vendor=elxsi basic_os=${basic_os:-bsd} ;; fx2800) cpu=i860 vendor=alliant ;; genix) cpu=ns32k vendor=ns ;; h3050r* | hiux*) cpu=hppa1.1 vendor=hitachi basic_os=hiuxwe2 ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) cpu=hppa1.0 vendor=hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) cpu=m68000 vendor=hp ;; hp9k3[2-9][0-9]) cpu=m68k vendor=hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) cpu=hppa1.0 vendor=hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) cpu=hppa1.1 vendor=hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp cpu=hppa1.1 vendor=hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp cpu=hppa1.1 vendor=hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) cpu=hppa1.1 vendor=hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) cpu=hppa1.0 vendor=hp ;; i*86v32) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv32 ;; i*86v4*) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv4 ;; i*86v) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv ;; i*86sol2) cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=solaris2 ;; j90 | j90-cray) cpu=j90 vendor=cray basic_os=${basic_os:-unicos} ;; iris | iris4d) cpu=mips vendor=sgi case $basic_os in irix*) ;; *) basic_os=irix4 ;; esac ;; miniframe) cpu=m68000 vendor=convergent ;; *mint | mint[0-9]* | *MiNT | *MiNT[0-9]*) cpu=m68k vendor=atari basic_os=mint ;; news-3600 | risc-news) cpu=mips vendor=sony basic_os=newsos ;; next | m*-next) cpu=m68k vendor=next case $basic_os in openstep*) ;; nextstep*) ;; ns2*) basic_os=nextstep2 ;; *) basic_os=nextstep3 ;; esac ;; np1) cpu=np1 vendor=gould ;; op50n-* | op60c-*) cpu=hppa1.1 vendor=oki basic_os=proelf ;; pa-hitachi) cpu=hppa1.1 vendor=hitachi basic_os=hiuxwe2 ;; pbd) cpu=sparc vendor=tti ;; pbb) cpu=m68k vendor=tti ;; pc532) cpu=ns32k vendor=pc532 ;; pn) cpu=pn vendor=gould ;; power) cpu=power vendor=ibm ;; ps2) cpu=i386 vendor=ibm ;; rm[46]00) cpu=mips vendor=siemens ;; rtpc | rtpc-*) cpu=romp vendor=ibm ;; sde) cpu=mipsisa32 vendor=sde basic_os=${basic_os:-elf} ;; simso-wrs) cpu=sparclite vendor=wrs basic_os=vxworks ;; tower | tower-32) cpu=m68k vendor=ncr ;; vpp*|vx|vx-*) cpu=f301 vendor=fujitsu ;; w65) cpu=w65 vendor=wdc ;; w89k-*) cpu=hppa1.1 vendor=winbond basic_os=proelf ;; none) cpu=none vendor=none ;; leon|leon[3-9]) cpu=sparc vendor=$basic_machine ;; leon-*|leon[3-9]-*) cpu=sparc vendor=`echo "$basic_machine" | sed 's/-.*//'` ;; *-*) # shellcheck disable=SC2162 saved_IFS=$IFS IFS="-" read cpu vendor <&2 exit 1 ;; esac ;; esac # Here we canonicalize certain aliases for manufacturers. case $vendor in digital*) vendor=dec ;; commodore*) vendor=cbm ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if test x$basic_os != x then # First recognize some ad-hoc cases, or perhaps split kernel-os, or else just # set os. case $basic_os in gnu/linux*) kernel=linux os=`echo "$basic_os" | sed -e 's|gnu/linux|gnu|'` ;; os2-emx) kernel=os2 os=`echo "$basic_os" | sed -e 's|os2-emx|emx|'` ;; nto-qnx*) kernel=nto os=`echo "$basic_os" | sed -e 's|nto-qnx|qnx|'` ;; *-*) # shellcheck disable=SC2162 saved_IFS=$IFS IFS="-" read kernel os <&2 exit 1 ;; esac # As a final step for OS-related things, validate the OS-kernel combination # (given a valid OS), if there is a kernel. case $kernel-$os in linux-gnu* | linux-dietlibc* | linux-android* | linux-newlib* \ | linux-musl* | linux-relibc* | linux-uclibc* | linux-mlibc* ) ;; uclinux-uclibc* ) ;; managarm-mlibc* | managarm-kernel* ) ;; -dietlibc* | -newlib* | -musl* | -relibc* | -uclibc* | -mlibc* ) # These are just libc implementations, not actual OSes, and thus # require a kernel. echo "Invalid configuration '$1': libc '$os' needs explicit kernel." 1>&2 exit 1 ;; -kernel* ) echo "Invalid configuration '$1': '$os' needs explicit kernel." 1>&2 exit 1 ;; *-kernel* ) echo "Invalid configuration '$1': '$kernel' does not support '$os'." 1>&2 exit 1 ;; kfreebsd*-gnu* | kopensolaris*-gnu*) ;; vxworks-simlinux | vxworks-simwindows | vxworks-spe) ;; nto-qnx*) ;; os2-emx) ;; *-eabi* | *-gnueabi*) ;; -*) # Blank kernel with real OS is always fine. ;; *-*) echo "Invalid configuration '$1': Kernel '$kernel' not known to work with OS '$os'." 1>&2 exit 1 ;; esac # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. case $vendor in unknown) case $cpu-$os in *-riscix*) vendor=acorn ;; *-sunos*) vendor=sun ;; *-cnk* | *-aix*) vendor=ibm ;; *-beos*) vendor=be ;; *-hpux*) vendor=hp ;; *-mpeix*) vendor=hp ;; *-hiux*) vendor=hitachi ;; *-unos*) vendor=crds ;; *-dgux*) vendor=dg ;; *-luna*) vendor=omron ;; *-genix*) vendor=ns ;; *-clix*) vendor=intergraph ;; *-mvs* | *-opened*) vendor=ibm ;; *-os400*) vendor=ibm ;; s390-* | s390x-*) vendor=ibm ;; *-ptx*) vendor=sequent ;; *-tpf*) vendor=ibm ;; *-vxsim* | *-vxworks* | *-windiss*) vendor=wrs ;; *-aux*) vendor=apple ;; *-hms*) vendor=hitachi ;; *-mpw* | *-macos*) vendor=apple ;; *-*mint | *-mint[0-9]* | *-*MiNT | *-MiNT[0-9]*) vendor=atari ;; *-vos*) vendor=stratus ;; esac ;; esac echo "$cpu-$vendor-${kernel:+$kernel-}$os" exit # Local variables: # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: ddcutil-2.2.0/config/install-sh0000755000175000001440000003577614671527764012136 #!/bin/sh # install - install a program, script, or datafile scriptversion=2020-11-14.01; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # 'make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. tab=' ' nl=' ' IFS=" $tab$nl" # Set DOITPROG to "echo" to test this script. doit=${DOITPROG-} doit_exec=${doit:-exec} # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_mkdir= # Desired mode of installed file. mode=0755 # Create dirs (including intermediate dirs) using mode 755. # This is like GNU 'install' as of coreutils 8.32 (2020). mkdir_umask=22 backupsuffix= chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false is_target_a_directory=possibly usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -p pass -p to $cpprog. -s $stripprog installed files. -S SUFFIX attempt to back up existing files, with suffix SUFFIX. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG By default, rm is invoked with -f; when overridden with RMPROG, it's up to you to specify -f if you want it. If -S is not specified, no backups are attempted. Email bug reports to bug-automake@gnu.org. Automake home page: https://www.gnu.org/software/automake/ " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -p) cpprog="$cpprog -p";; -s) stripcmd=$stripprog;; -S) backupsuffix="$2" shift;; -t) is_target_a_directory=always dst_arg=$2 # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) is_target_a_directory=never;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done # We allow the use of options -d and -T together, by making -d # take the precedence; this is for compatibility with GNU install. if test -n "$dir_arg"; then if test -n "$dst_arg"; then echo "$0: target directory not allowed when installing a directory." >&2 exit 1 fi fi if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call 'install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then if test $# -gt 1 || test "$is_target_a_directory" = always; then if test ! -d "$dst_arg"; then echo "$0: $dst_arg: Is not a directory." >&2 exit 1 fi fi fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for 'test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? # Don't chown directories that already exist. if test $dstdir_status = 0; then chowncmd="" fi else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename. if test -d "$dst"; then if test "$is_target_a_directory" = never; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dstbase=`basename "$src"` case $dst in */) dst=$dst$dstbase;; *) dst=$dst/$dstbase;; esac dstdir_status=0 else dstdir=`dirname "$dst"` test -d "$dstdir" dstdir_status=$? fi fi case $dstdir in */) dstdirslash=$dstdir;; *) dstdirslash=$dstdir/;; esac obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false # The $RANDOM variable is not portable (e.g., dash). Use it # here however when possible just to lower collision chance. tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap ' ret=$? rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null exit $ret ' 0 # Because "mkdir -p" follows existing symlinks and we likely work # directly in world-writeable /tmp, make sure that the '$tmpdir' # directory is successfully created first before we actually test # 'mkdir -p'. if (umask $mkdir_umask && $mkdirprog $mkdir_mode "$tmpdir" && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. test_tmpdir="$tmpdir/a" ls_ld_tmpdir=`ls -ld "$test_tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$test_tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null fi trap '' 0;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac oIFS=$IFS IFS=/ set -f set fnord $dstdir shift set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=${dstdirslash}_inst.$$_ rmtmp=${dstdirslash}_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && { test -z "$stripcmd" || { # Create $dsttmp read-write so that cp doesn't create it read-only, # which would cause strip to fail. if test -z "$doit"; then : >"$dsttmp" # No need to fork-exec 'touch'. else $doit touch "$dsttmp" fi } } && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # If $backupsuffix is set, and the file being installed # already exists, attempt a backup. Don't worry if it fails, # e.g., if mv doesn't support -f. if test -n "$backupsuffix" && test -f "$dst"; then $doit $mvcmd -f "$dst" "$dst$backupsuffix" 2>/dev/null fi # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: ddcutil-2.2.0/config/ltmain.sh0000644000175000001440000121201014671527761011722 #! /usr/bin/env sh ## DO NOT EDIT - This file generated from ./build-aux/ltmain.in ## by inline-source v2019-02-19.15 # libtool (GNU libtool) 2.4.7 # Provide generalized library-building support services. # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996-2019, 2021-2022 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . PROGRAM=libtool PACKAGE=libtool VERSION=2.4.7 package_revision=2.4.7 ## ------ ## ## Usage. ## ## ------ ## # Run './libtool --help' for help with using this script from the # command line. ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # After configure completes, it has a better idea of some of the # shell tools we need than the defaults used by the functions shared # with bootstrap, so set those here where they can still be over- # ridden by the user, but otherwise take precedence. : ${AUTOCONF="autoconf"} : ${AUTOMAKE="automake"} ## -------------------------- ## ## Source external libraries. ## ## -------------------------- ## # Much of our low-level functionality needs to be sourced from external # libraries, which are installed to $pkgauxdir. # Set a version string for this script. scriptversion=2019-02-19.15; # UTC # General shell script boiler plate, and helper functions. # Written by Gary V. Vaughan, 2004 # This is free software. There is NO warranty; not even for # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # Copyright (C) 2004-2019, 2021 Bootstrap Authors # # This file is dual licensed under the terms of the MIT license # , and GPL version 2 or later # . You must apply one of # these licenses when using or redistributing this software or any of # the files within it. See the URLs above, or the file `LICENSE` # included in the Bootstrap distribution for the full license texts. # Please report bugs or propose patches to: # ## ------ ## ## Usage. ## ## ------ ## # Evaluate this file near the top of your script to gain access to # the functions and variables defined here: # # . `echo "$0" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh # # If you need to override any of the default environment variable # settings, do that before evaluating this file. ## -------------------- ## ## Shell normalisation. ## ## -------------------- ## # Some shells need a little help to be as Bourne compatible as possible. # Before doing anything else, make sure all that help has been provided! DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi # NLS nuisances: We save the old values in case they are required later. _G_user_locale= _G_safe_locale= for _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test set = \"\${$_G_var+set}\"; then save_$_G_var=\$$_G_var $_G_var=C export $_G_var _G_user_locale=\"$_G_var=\\\$save_\$_G_var; \$_G_user_locale\" _G_safe_locale=\"$_G_var=C; \$_G_safe_locale\" fi" done # These NLS vars are set unconditionally (bootstrap issue #24). Unset those # in case the environment reset is needed later and the $save_* variant is not # defined (see the code above). LC_ALL=C LANGUAGE=C export LANGUAGE LC_ALL # Make sure IFS has a sensible default sp=' ' nl=' ' IFS="$sp $nl" # There are apparently some retarded systems that use ';' as a PATH separator! if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # func_unset VAR # -------------- # Portably unset VAR. # In some shells, an 'unset VAR' statement leaves a non-zero return # status if VAR is already unset, which might be problematic if the # statement is used at the end of a function (thus poisoning its return # value) or when 'set -e' is active (causing even a spurious abort of # the script in this case). func_unset () { { eval $1=; (eval unset $1) >/dev/null 2>&1 && eval unset $1 || : ; } } # Make sure CDPATH doesn't cause `cd` commands to output the target dir. func_unset CDPATH # Make sure ${,E,F}GREP behave sanely. func_unset GREP_OPTIONS ## ------------------------- ## ## Locate command utilities. ## ## ------------------------- ## # func_executable_p FILE # ---------------------- # Check that FILE is an executable regular file. func_executable_p () { test -f "$1" && test -x "$1" } # func_path_progs PROGS_LIST CHECK_FUNC [PATH] # -------------------------------------------- # Search for either a program that responds to --version with output # containing "GNU", or else returned by CHECK_FUNC otherwise, by # trying all the directories in PATH with each of the elements of # PROGS_LIST. # # CHECK_FUNC should accept the path to a candidate program, and # set $func_check_prog_result if it truncates its output less than # $_G_path_prog_max characters. func_path_progs () { _G_progs_list=$1 _G_check_func=$2 _G_PATH=${3-"$PATH"} _G_path_prog_max=0 _G_path_prog_found=false _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:} for _G_dir in $_G_PATH; do IFS=$_G_save_IFS test -z "$_G_dir" && _G_dir=. for _G_prog_name in $_G_progs_list; do for _exeext in '' .EXE; do _G_path_prog=$_G_dir/$_G_prog_name$_exeext func_executable_p "$_G_path_prog" || continue case `"$_G_path_prog" --version 2>&1` in *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;; *) $_G_check_func $_G_path_prog func_path_progs_result=$func_check_prog_result ;; esac $_G_path_prog_found && break 3 done done done IFS=$_G_save_IFS test -z "$func_path_progs_result" && { echo "no acceptable sed could be found in \$PATH" >&2 exit 1 } } # We want to be able to use the functions in this file before configure # has figured out where the best binaries are kept, which means we have # to search for them ourselves - except when the results are already set # where we skip the searches. # Unless the user overrides by setting SED, search the path for either GNU # sed, or the sed that truncates its output the least. test -z "$SED" && { _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for _G_i in 1 2 3 4 5 6 7; do _G_sed_script=$_G_sed_script$nl$_G_sed_script done echo "$_G_sed_script" 2>/dev/null | sed 99q >conftest.sed _G_sed_script= func_check_prog_sed () { _G_path_prog=$1 _G_count=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo '' >> conftest.nl "$_G_path_prog" -f conftest.sed conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "sed gsed" func_check_prog_sed "$PATH:/usr/xpg4/bin" rm -f conftest.sed SED=$func_path_progs_result } # Unless the user overrides by setting GREP, search the path for either GNU # grep, or the grep that truncates its output the least. test -z "$GREP" && { func_check_prog_grep () { _G_path_prog=$1 _G_count=0 _G_path_prog_max=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo 'GREP' >> conftest.nl "$_G_path_prog" -e 'GREP$' -e '-(cannot match)-' conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "grep ggrep" func_check_prog_grep "$PATH:/usr/xpg4/bin" GREP=$func_path_progs_result } ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # All uppercase variable names are used for environment variables. These # variables can be overridden by the user before calling a script that # uses them if a suitable command of that name is not already available # in the command search PATH. : ${CP="cp -f"} : ${ECHO="printf %s\n"} : ${EGREP="$GREP -E"} : ${FGREP="$GREP -F"} : ${LN_S="ln -s"} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} ## -------------------- ## ## Useful sed snippets. ## ## -------------------- ## sed_dirname='s|/[^/]*$||' sed_basename='s|^.*/||' # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='s|\([`"$\\]\)|\\\1|g' # Same as above, but do not quote variable references. sed_double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s|[].[^$\\*\/]|\\&|g' # Sed substitution that converts a w32 file name or path # that contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-'\' parameter expansions in output of sed_double_quote_subst that # were '\'-ed in input to the same. If an odd number of '\' preceded a # '$' in input to sed_double_quote_subst, that '$' was protected from # expansion. Since each input '\' is now two '\'s, look for any number # of runs of four '\'s followed by two '\'s and then a '$'. '\' that '$'. _G_bs='\\' _G_bs2='\\\\' _G_bs4='\\\\\\\\' _G_dollar='\$' sed_double_backslash="\ s/$_G_bs4/&\\ /g s/^$_G_bs2$_G_dollar/$_G_bs&/ s/\\([^$_G_bs]\\)$_G_bs2$_G_dollar/\\1$_G_bs2$_G_bs$_G_dollar/g s/\n//g" # require_check_ifs_backslash # --------------------------- # Check if we can use backslash as IFS='\' separator, and set # $check_ifs_backshlash_broken to ':' or 'false'. require_check_ifs_backslash=func_require_check_ifs_backslash func_require_check_ifs_backslash () { _G_save_IFS=$IFS IFS='\' _G_check_ifs_backshlash='a\\b' for _G_i in $_G_check_ifs_backshlash do case $_G_i in a) check_ifs_backshlash_broken=false ;; '') break ;; *) check_ifs_backshlash_broken=: break ;; esac done IFS=$_G_save_IFS require_check_ifs_backslash=: } ## ----------------- ## ## Global variables. ## ## ----------------- ## # Except for the global variables explicitly listed below, the following # functions in the '^func_' namespace, and the '^require_' namespace # variables initialised in the 'Resource management' section, sourcing # this file will not pollute your global namespace with anything # else. There's no portable way to scope variables in Bourne shell # though, so actually running these functions will sometimes place # results into a variable named after the function, and often use # temporary variables in the '^_G_' namespace. If you are careful to # avoid using those namespaces casually in your sourcing script, things # should continue to work as you expect. And, of course, you can freely # overwrite any of the functions or variables defined here before # calling anything to customize them. EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. # Allow overriding, eg assuming that you follow the convention of # putting '$debug_cmd' at the start of all your functions, you can get # bash to show function call trace with: # # debug_cmd='eval echo "${FUNCNAME[0]} $*" >&2' bash your-script-name debug_cmd=${debug_cmd-":"} exit_cmd=: # By convention, finish your script with: # # exit $exit_status # # so that you can set exit_status to non-zero if you want to indicate # something went wrong during execution without actually bailing out at # the point of failure. exit_status=$EXIT_SUCCESS # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath=$0 # The name of this program. progname=`$ECHO "$progpath" |$SED "$sed_basename"` # Make sure we have an absolute progpath for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=`$ECHO "$progpath" |$SED "$sed_dirname"` progdir=`cd "$progdir" && pwd` progpath=$progdir/$progname ;; *) _G_IFS=$IFS IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS=$_G_IFS test -x "$progdir/$progname" && break done IFS=$_G_IFS test -n "$progdir" || progdir=`pwd` progpath=$progdir/$progname ;; esac ## ----------------- ## ## Standard options. ## ## ----------------- ## # The following options affect the operation of the functions defined # below, and should be set appropriately depending on run-time para- # meters passed on the command line. opt_dry_run=false opt_quiet=false opt_verbose=false # Categories 'all' and 'none' are always available. Append any others # you will pass as the first argument to func_warning from your own # code. warning_categories= # By default, display warnings according to 'opt_warning_types'. Set # 'warning_func' to ':' to elide all warnings, or func_fatal_error to # treat the next displayed warning as a fatal error. warning_func=func_warn_and_continue # Set to 'all' to display all warnings, 'none' to suppress all # warnings, or a space delimited list of some subset of # 'warning_categories' to display only the listed warnings. opt_warning_types=all ## -------------------- ## ## Resource management. ## ## -------------------- ## # This section contains definitions for functions that each ensure a # particular resource (a file, or a non-empty configuration variable for # example) is available, and if appropriate to extract default values # from pertinent package files. Call them using their associated # 'require_*' variable to ensure that they are executed, at most, once. # # It's entirely deliberate that calling these functions can set # variables that don't obey the namespace limitations obeyed by the rest # of this file, in order that that they be as useful as possible to # callers. # require_term_colors # ------------------- # Allow display of bold text on terminals that support it. require_term_colors=func_require_term_colors func_require_term_colors () { $debug_cmd test -t 1 && { # COLORTERM and USE_ANSI_COLORS environment variables take # precedence, because most terminfo databases neglect to describe # whether color sequences are supported. test -n "${COLORTERM+set}" && : ${USE_ANSI_COLORS="1"} if test 1 = "$USE_ANSI_COLORS"; then # Standard ANSI escape sequences tc_reset='' tc_bold=''; tc_standout='' tc_red=''; tc_green='' tc_blue=''; tc_cyan='' else # Otherwise trust the terminfo database after all. test -n "`tput sgr0 2>/dev/null`" && { tc_reset=`tput sgr0` test -n "`tput bold 2>/dev/null`" && tc_bold=`tput bold` tc_standout=$tc_bold test -n "`tput smso 2>/dev/null`" && tc_standout=`tput smso` test -n "`tput setaf 1 2>/dev/null`" && tc_red=`tput setaf 1` test -n "`tput setaf 2 2>/dev/null`" && tc_green=`tput setaf 2` test -n "`tput setaf 4 2>/dev/null`" && tc_blue=`tput setaf 4` test -n "`tput setaf 5 2>/dev/null`" && tc_cyan=`tput setaf 5` } fi } require_term_colors=: } ## ----------------- ## ## Function library. ## ## ----------------- ## # This section contains a variety of useful functions to call in your # scripts. Take note of the portable wrappers for features provided by # some modern shells, which will fall back to slower equivalents on # less featureful shells. # func_append VAR VALUE # --------------------- # Append VALUE onto the existing contents of VAR. # We should try to minimise forks, especially on Windows where they are # unreasonably slow, so skip the feature probes when bash or zsh are # being used: if test set = "${BASH_VERSION+set}${ZSH_VERSION+set}"; then : ${_G_HAVE_ARITH_OP="yes"} : ${_G_HAVE_XSI_OPS="yes"} # The += operator was introduced in bash 3.1 case $BASH_VERSION in [12].* | 3.0 | 3.0*) ;; *) : ${_G_HAVE_PLUSEQ_OP="yes"} ;; esac fi # _G_HAVE_PLUSEQ_OP # Can be empty, in which case the shell is probed, "yes" if += is # useable or anything else if it does not work. test -z "$_G_HAVE_PLUSEQ_OP" \ && (eval 'x=a; x+=" b"; test "a b" = "$x"') 2>/dev/null \ && _G_HAVE_PLUSEQ_OP=yes if test yes = "$_G_HAVE_PLUSEQ_OP" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_append () { $debug_cmd eval "$1+=\$2" }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_append () { $debug_cmd eval "$1=\$$1\$2" } fi # func_append_quoted VAR VALUE # ---------------------------- # Quote VALUE and append to the end of shell variable VAR, separated # by a space. if test yes = "$_G_HAVE_PLUSEQ_OP"; then eval 'func_append_quoted () { $debug_cmd func_quote_arg pretty "$2" eval "$1+=\\ \$func_quote_arg_result" }' else func_append_quoted () { $debug_cmd func_quote_arg pretty "$2" eval "$1=\$$1\\ \$func_quote_arg_result" } fi # func_append_uniq VAR VALUE # -------------------------- # Append unique VALUE onto the existing contents of VAR, assuming # entries are delimited by the first character of VALUE. For example: # # func_append_uniq options " --another-option option-argument" # # will only append to $options if " --another-option option-argument " # is not already present somewhere in $options already (note spaces at # each end implied by leading space in second argument). func_append_uniq () { $debug_cmd eval _G_current_value='`$ECHO $'$1'`' _G_delim=`expr "$2" : '\(.\)'` case $_G_delim$_G_current_value$_G_delim in *"$2$_G_delim"*) ;; *) func_append "$@" ;; esac } # func_arith TERM... # ------------------ # Set func_arith_result to the result of evaluating TERMs. test -z "$_G_HAVE_ARITH_OP" \ && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \ && _G_HAVE_ARITH_OP=yes if test yes = "$_G_HAVE_ARITH_OP"; then eval 'func_arith () { $debug_cmd func_arith_result=$(( $* )) }' else func_arith () { $debug_cmd func_arith_result=`expr "$@"` } fi # func_basename FILE # ------------------ # Set func_basename_result to FILE with everything up to and including # the last / stripped. if test yes = "$_G_HAVE_XSI_OPS"; then # If this shell supports suffix pattern removal, then use it to avoid # forking. Hide the definitions single quotes in case the shell chokes # on unsupported syntax... _b='func_basename_result=${1##*/}' _d='case $1 in */*) func_dirname_result=${1%/*}$2 ;; * ) func_dirname_result=$3 ;; esac' else # ...otherwise fall back to using sed. _b='func_basename_result=`$ECHO "$1" |$SED "$sed_basename"`' _d='func_dirname_result=`$ECHO "$1" |$SED "$sed_dirname"` if test "X$func_dirname_result" = "X$1"; then func_dirname_result=$3 else func_append func_dirname_result "$2" fi' fi eval 'func_basename () { $debug_cmd '"$_b"' }' # func_dirname FILE APPEND NONDIR_REPLACEMENT # ------------------------------------------- # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. eval 'func_dirname () { $debug_cmd '"$_d"' }' # func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT # -------------------------------------------------------- # Perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # For efficiency, we do not delegate to the functions above but instead # duplicate the functionality here. eval 'func_dirname_and_basename () { $debug_cmd '"$_b"' '"$_d"' }' # func_echo ARG... # ---------------- # Echo program name prefixed message. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname: $_G_line" done IFS=$func_echo_IFS } # func_echo_all ARG... # -------------------- # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_echo_infix_1 INFIX ARG... # ------------------------------ # Echo program name, followed by INFIX on the first line, with any # additional lines not showing INFIX. func_echo_infix_1 () { $debug_cmd $require_term_colors _G_infix=$1; shift _G_indent=$_G_infix _G_prefix="$progname: $_G_infix: " _G_message=$* # Strip color escape sequences before counting printable length for _G_tc in "$tc_reset" "$tc_bold" "$tc_standout" "$tc_red" "$tc_green" "$tc_blue" "$tc_cyan" do test -n "$_G_tc" && { _G_esc_tc=`$ECHO "$_G_tc" | $SED "$sed_make_literal_regex"` _G_indent=`$ECHO "$_G_indent" | $SED "s|$_G_esc_tc||g"` } done _G_indent="$progname: "`echo "$_G_indent" | $SED 's|.| |g'`" " ## exclude from sc_prohibit_nested_quotes func_echo_infix_1_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_infix_1_IFS $ECHO "$_G_prefix$tc_bold$_G_line$tc_reset" >&2 _G_prefix=$_G_indent done IFS=$func_echo_infix_1_IFS } # func_error ARG... # ----------------- # Echo program name prefixed message to standard error. func_error () { $debug_cmd $require_term_colors func_echo_infix_1 " $tc_standout${tc_red}error$tc_reset" "$*" >&2 } # func_fatal_error ARG... # ----------------------- # Echo program name prefixed message to standard error, and exit. func_fatal_error () { $debug_cmd func_error "$*" exit $EXIT_FAILURE } # func_grep EXPRESSION FILENAME # ----------------------------- # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $debug_cmd $GREP "$1" "$2" >/dev/null 2>&1 } # func_len STRING # --------------- # Set func_len_result to the length of STRING. STRING may not # start with a hyphen. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_len () { $debug_cmd func_len_result=${#1} }' else func_len () { $debug_cmd func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` } fi # func_mkdir_p DIRECTORY-PATH # --------------------------- # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { $debug_cmd _G_directory_path=$1 _G_dir_list= if test -n "$_G_directory_path" && test : != "$opt_dry_run"; then # Protect directory names starting with '-' case $_G_directory_path in -*) _G_directory_path=./$_G_directory_path ;; esac # While some portion of DIR does not yet exist... while test ! -d "$_G_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. _G_dir_list=$_G_directory_path:$_G_dir_list # If the last portion added has no slash in it, the list is done case $_G_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop _G_directory_path=`$ECHO "$_G_directory_path" | $SED -e "$sed_dirname"` done _G_dir_list=`$ECHO "$_G_dir_list" | $SED 's|:*$||'` func_mkdir_p_IFS=$IFS; IFS=: for _G_dir in $_G_dir_list; do IFS=$func_mkdir_p_IFS # mkdir can fail with a 'File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$_G_dir" 2>/dev/null || : done IFS=$func_mkdir_p_IFS # Bail out if we (or some other process) failed to create a directory. test -d "$_G_directory_path" || \ func_fatal_error "Failed to create '$1'" fi } # func_mktempdir [BASENAME] # ------------------------- # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, BASENAME is the basename for that directory. func_mktempdir () { $debug_cmd _G_template=${TMPDIR-/tmp}/${1-$progname} if test : = "$opt_dry_run"; then # Return a directory name, but don't create it in dry-run mode _G_tmpdir=$_G_template-$$ else # If mktemp works, use that first and foremost _G_tmpdir=`mktemp -d "$_G_template-XXXXXXXX" 2>/dev/null` if test ! -d "$_G_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race _G_tmpdir=$_G_template-${RANDOM-0}$$ func_mktempdir_umask=`umask` umask 0077 $MKDIR "$_G_tmpdir" umask $func_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$_G_tmpdir" || \ func_fatal_error "cannot create temporary directory '$_G_tmpdir'" fi $ECHO "$_G_tmpdir" } # func_normal_abspath PATH # ------------------------ # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. func_normal_abspath () { $debug_cmd # These SED scripts presuppose an absolute path with a trailing slash. _G_pathcar='s|^/\([^/]*\).*$|\1|' _G_pathcdr='s|^/[^/]*||' _G_removedotparts=':dotsl s|/\./|/|g t dotsl s|/\.$|/|' _G_collapseslashes='s|/\{1,\}|/|g' _G_finalslash='s|/*$|/|' # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_removedotparts" -e "$_G_collapseslashes" -e "$_G_finalslash"` while :; do # Processed it all yet? if test / = "$func_normal_abspath_tpath"; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result"; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_append func_normal_abspath_result "/$func_normal_abspath_tcomponent" ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_notquiet ARG... # -------------------- # Echo program name prefixed message only when not in quiet mode. func_notquiet () { $debug_cmd $opt_quiet || func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_relative_path SRCDIR DSTDIR # -------------------------------- # Set func_relative_path_result to the relative path from SRCDIR to DSTDIR. func_relative_path () { $debug_cmd func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=$func_dirname_result if test -z "$func_relative_path_tlibdir"; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test -n "$func_stripname_result"; then func_append func_relative_path_result "/$func_stripname_result" fi # Normalisation. If bindir is libdir, return '.' else relative path. if test -n "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result" func_relative_path_result=$func_stripname_result fi test -n "$func_relative_path_result" || func_relative_path_result=. : } # func_quote_portable EVAL ARG # ---------------------------- # Internal function to portably implement func_quote_arg. Note that we still # keep attention to performance here so we as much as possible try to avoid # calling sed binary (so far O(N) complexity as long as func_append is O(1)). func_quote_portable () { $debug_cmd $require_check_ifs_backslash func_quote_portable_result=$2 # one-time-loop (easy break) while true do if $1; then func_quote_portable_result=`$ECHO "$2" | $SED \ -e "$sed_double_quote_subst" -e "$sed_double_backslash"` break fi # Quote for eval. case $func_quote_portable_result in *[\\\`\"\$]*) # Fallback to sed for $func_check_bs_ifs_broken=:, or when the string # contains the shell wildcard characters. case $check_ifs_backshlash_broken$func_quote_portable_result in :*|*[\[\*\?]*) func_quote_portable_result=`$ECHO "$func_quote_portable_result" \ | $SED "$sed_quote_subst"` break ;; esac func_quote_portable_old_IFS=$IFS for _G_char in '\' '`' '"' '$' do # STATE($1) PREV($2) SEPARATOR($3) set start "" "" func_quote_portable_result=dummy"$_G_char$func_quote_portable_result$_G_char"dummy IFS=$_G_char for _G_part in $func_quote_portable_result do case $1 in quote) func_append func_quote_portable_result "$3$2" set quote "$_G_part" "\\$_G_char" ;; start) set first "" "" func_quote_portable_result= ;; first) set quote "$_G_part" "" ;; esac done done IFS=$func_quote_portable_old_IFS ;; *) ;; esac break done func_quote_portable_unquoted_result=$func_quote_portable_result case $func_quote_portable_result in # double-quote args containing shell metacharacters to delay # word splitting, command substitution and variable expansion # for a subsequent eval. # many bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_portable_result=\"$func_quote_portable_result\" ;; esac } # func_quotefast_eval ARG # ----------------------- # Quote one ARG (internal). This is equivalent to 'func_quote_arg eval ARG', # but optimized for speed. Result is stored in $func_quotefast_eval. if test xyes = `(x=; printf -v x %q yes; echo x"$x") 2>/dev/null`; then printf -v _GL_test_printf_tilde %q '~' if test '\~' = "$_GL_test_printf_tilde"; then func_quotefast_eval () { printf -v func_quotefast_eval_result %q "$1" } else # Broken older Bash implementations. Make those faster too if possible. func_quotefast_eval () { case $1 in '~'*) func_quote_portable false "$1" func_quotefast_eval_result=$func_quote_portable_result ;; *) printf -v func_quotefast_eval_result %q "$1" ;; esac } fi else func_quotefast_eval () { func_quote_portable false "$1" func_quotefast_eval_result=$func_quote_portable_result } fi # func_quote_arg MODEs ARG # ------------------------ # Quote one ARG to be evaled later. MODEs argument may contain zero or more # specifiers listed below separated by ',' character. This function returns two # values: # i) func_quote_arg_result # double-quoted (when needed), suitable for a subsequent eval # ii) func_quote_arg_unquoted_result # has all characters that are still active within double # quotes backslashified. Available only if 'unquoted' is specified. # # Available modes: # ---------------- # 'eval' (default) # - escape shell special characters # 'expand' # - the same as 'eval'; but do not quote variable references # 'pretty' # - request aesthetic output, i.e. '"a b"' instead of 'a\ b'. This might # be used later in func_quote to get output like: 'echo "a b"' instead # of 'echo a\ b'. This is slower than default on some shells. # 'unquoted' # - produce also $func_quote_arg_unquoted_result which does not contain # wrapping double-quotes. # # Examples for 'func_quote_arg pretty,unquoted string': # # string | *_result | *_unquoted_result # ------------+-----------------------+------------------- # " | \" | \" # a b | "a b" | a b # "a b" | "\"a b\"" | \"a b\" # * | "*" | * # z="${x-$y}" | "z=\"\${x-\$y}\"" | z=\"\${x-\$y}\" # # Examples for 'func_quote_arg pretty,unquoted,expand string': # # string | *_result | *_unquoted_result # --------------+---------------------+-------------------- # z="${x-$y}" | "z=\"${x-$y}\"" | z=\"${x-$y}\" func_quote_arg () { _G_quote_expand=false case ,$1, in *,expand,*) _G_quote_expand=: ;; esac case ,$1, in *,pretty,*|*,expand,*|*,unquoted,*) func_quote_portable $_G_quote_expand "$2" func_quote_arg_result=$func_quote_portable_result func_quote_arg_unquoted_result=$func_quote_portable_unquoted_result ;; *) # Faster quote-for-eval for some shells. func_quotefast_eval "$2" func_quote_arg_result=$func_quotefast_eval_result ;; esac } # func_quote MODEs ARGs... # ------------------------ # Quote all ARGs to be evaled later and join them into single command. See # func_quote_arg's description for more info. func_quote () { $debug_cmd _G_func_quote_mode=$1 ; shift func_quote_result= while test 0 -lt $#; do func_quote_arg "$_G_func_quote_mode" "$1" if test -n "$func_quote_result"; then func_append func_quote_result " $func_quote_arg_result" else func_append func_quote_result "$func_quote_arg_result" fi shift done } # func_stripname PREFIX SUFFIX NAME # --------------------------------- # strip PREFIX and SUFFIX from NAME, and store in func_stripname_result. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_stripname () { $debug_cmd # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary variable first. func_stripname_result=$3 func_stripname_result=${func_stripname_result#"$1"} func_stripname_result=${func_stripname_result%"$2"} }' else func_stripname () { $debug_cmd case $2 in .*) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%\\\\$2\$%%"`;; *) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%$2\$%%"`;; esac } fi # func_show_eval CMD [FAIL_EXP] # ----------------------------- # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} func_quote_arg pretty,expand "$_G_cmd" eval "func_notquiet $func_quote_arg_result" $opt_dry_run || { eval "$_G_cmd" _G_status=$? if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_show_eval_locale CMD [FAIL_EXP] # ------------------------------------ # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} $opt_quiet || { func_quote_arg expand,pretty "$_G_cmd" eval "func_echo $func_quote_arg_result" } $opt_dry_run || { eval "$_G_user_locale $_G_cmd" _G_status=$? eval "$_G_safe_locale" if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_tr_sh # ---------- # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { $debug_cmd case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED -e 's/^\([0-9]\)/_\1/' -e 's/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_verbose ARG... # ------------------- # Echo program name prefixed message in verbose mode only. func_verbose () { $debug_cmd $opt_verbose && func_echo "$*" : } # func_warn_and_continue ARG... # ----------------------------- # Echo program name prefixed warning message to standard error. func_warn_and_continue () { $debug_cmd $require_term_colors func_echo_infix_1 "${tc_red}warning$tc_reset" "$*" >&2 } # func_warning CATEGORY ARG... # ---------------------------- # Echo program name prefixed warning message to standard error. Warning # messages can be filtered according to CATEGORY, where this function # elides messages where CATEGORY is not listed in the global variable # 'opt_warning_types'. func_warning () { $debug_cmd # CATEGORY must be in the warning_categories list! case " $warning_categories " in *" $1 "*) ;; *) func_internal_error "invalid warning category '$1'" ;; esac _G_category=$1 shift case " $opt_warning_types " in *" $_G_category "*) $warning_func ${1+"$@"} ;; esac } # func_sort_ver VER1 VER2 # ----------------------- # 'sort -V' is not generally available. # Note this deviates from the version comparison in automake # in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a # but this should suffice as we won't be specifying old # version formats or redundant trailing .0 in bootstrap.conf. # If we did want full compatibility then we should probably # use m4_version_compare from autoconf. func_sort_ver () { $debug_cmd printf '%s\n%s\n' "$1" "$2" \ | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n } # func_lt_ver PREV CURR # --------------------- # Return true if PREV and CURR are in the correct order according to # func_sort_ver, otherwise false. Use it like this: # # func_lt_ver "$prev_ver" "$proposed_ver" || func_fatal_error "..." func_lt_ver () { $debug_cmd test "x$1" = x`func_sort_ver "$1" "$2" | $SED 1q` } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: #! /bin/sh # A portable, pluggable option parser for Bourne shell. # Written by Gary V. Vaughan, 2010 # This is free software. There is NO warranty; not even for # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # Copyright (C) 2010-2019, 2021 Bootstrap Authors # # This file is dual licensed under the terms of the MIT license # , and GPL version 2 or later # . You must apply one of # these licenses when using or redistributing this software or any of # the files within it. See the URLs above, or the file `LICENSE` # included in the Bootstrap distribution for the full license texts. # Please report bugs or propose patches to: # # Set a version string for this script. scriptversion=2019-02-19.15; # UTC ## ------ ## ## Usage. ## ## ------ ## # This file is a library for parsing options in your shell scripts along # with assorted other useful supporting features that you can make use # of too. # # For the simplest scripts you might need only: # # #!/bin/sh # . relative/path/to/funclib.sh # . relative/path/to/options-parser # scriptversion=1.0 # func_options ${1+"$@"} # eval set dummy "$func_options_result"; shift # ...rest of your script... # # In order for the '--version' option to work, you will need to have a # suitably formatted comment like the one at the top of this file # starting with '# Written by ' and ending with '# Copyright'. # # For '-h' and '--help' to work, you will also need a one line # description of your script's purpose in a comment directly above the # '# Written by ' line, like the one at the top of this file. # # The default options also support '--debug', which will turn on shell # execution tracing (see the comment above debug_cmd below for another # use), and '--verbose' and the func_verbose function to allow your script # to display verbose messages only when your user has specified # '--verbose'. # # After sourcing this file, you can plug in processing for additional # options by amending the variables from the 'Configuration' section # below, and following the instructions in the 'Option parsing' # section further down. ## -------------- ## ## Configuration. ## ## -------------- ## # You should override these variables in your script after sourcing this # file so that they reflect the customisations you have added to the # option parser. # The usage line for option parsing errors and the start of '-h' and # '--help' output messages. You can embed shell variables for delayed # expansion at the time the message is displayed, but you will need to # quote other shell meta-characters carefully to prevent them being # expanded when the contents are evaled. usage='$progpath [OPTION]...' # Short help message in response to '-h' and '--help'. Add to this or # override it after sourcing this library to reflect the full set of # options your script accepts. usage_message="\ --debug enable verbose shell tracing -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -v, --verbose verbosely report processing --version print version information and exit -h, --help print short or long help message and exit " # Additional text appended to 'usage_message' in response to '--help'. long_help_message=" Warning categories include: 'all' show all warnings 'none' turn off all the warnings 'error' warnings are treated as fatal errors" # Help message printed before fatal option parsing errors. fatal_help="Try '\$progname --help' for more information." ## ------------------------- ## ## Hook function management. ## ## ------------------------- ## # This section contains functions for adding, removing, and running hooks # in the main code. A hook is just a list of function names that can be # run in order later on. # func_hookable FUNC_NAME # ----------------------- # Declare that FUNC_NAME will run hooks added with # 'func_add_hook FUNC_NAME ...'. func_hookable () { $debug_cmd func_append hookable_fns " $1" } # func_add_hook FUNC_NAME HOOK_FUNC # --------------------------------- # Request that FUNC_NAME call HOOK_FUNC before it returns. FUNC_NAME must # first have been declared "hookable" by a call to 'func_hookable'. func_add_hook () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not accept hook functions." ;; esac eval func_append ${1}_hooks '" $2"' } # func_remove_hook FUNC_NAME HOOK_FUNC # ------------------------------------ # Remove HOOK_FUNC from the list of hook functions to be called by # FUNC_NAME. func_remove_hook () { $debug_cmd eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`' } # func_propagate_result FUNC_NAME_A FUNC_NAME_B # --------------------------------------------- # If the *_result variable of FUNC_NAME_A _is set_, assign its value to # *_result variable of FUNC_NAME_B. func_propagate_result () { $debug_cmd func_propagate_result_result=: if eval "test \"\${${1}_result+set}\" = set" then eval "${2}_result=\$${1}_result" else func_propagate_result_result=false fi } # func_run_hooks FUNC_NAME [ARG]... # --------------------------------- # Run all hook functions registered to FUNC_NAME. # It's assumed that the list of hook functions contains nothing more # than a whitespace-delimited list of legal shell function names, and # no effort is wasted trying to catch shell meta-characters or preserve # whitespace. func_run_hooks () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not support hook functions." ;; esac eval _G_hook_fns=\$$1_hooks; shift for _G_hook in $_G_hook_fns; do func_unset "${_G_hook}_result" eval $_G_hook '${1+"$@"}' func_propagate_result $_G_hook func_run_hooks if $func_propagate_result_result; then eval set dummy "$func_run_hooks_result"; shift fi done } ## --------------- ## ## Option parsing. ## ## --------------- ## # In order to add your own option parsing hooks, you must accept the # full positional parameter list from your hook function. You may remove # or edit any options that you action, and then pass back the remaining # unprocessed options in '_result', escaped # suitably for 'eval'. # # The '_result' variable is automatically unset # before your hook gets called; for best performance, only set the # *_result variable when necessary (i.e. don't call the 'func_quote' # function unnecessarily because it can be an expensive operation on some # machines). # # Like this: # # my_options_prep () # { # $debug_cmd # # # Extend the existing usage message. # usage_message=$usage_message' # -s, --silent don'\''t print informational messages # ' # # No change in '$@' (ignored completely by this hook). Leave # # my_options_prep_result variable intact. # } # func_add_hook func_options_prep my_options_prep # # # my_silent_option () # { # $debug_cmd # # args_changed=false # # # Note that, for efficiency, we parse as many options as we can # # recognise in a loop before passing the remainder back to the # # caller on the first unrecognised argument we encounter. # while test $# -gt 0; do # opt=$1; shift # case $opt in # --silent|-s) opt_silent=: # args_changed=: # ;; # # Separate non-argument short options: # -s*) func_split_short_opt "$_G_opt" # set dummy "$func_split_short_opt_name" \ # "-$func_split_short_opt_arg" ${1+"$@"} # shift # args_changed=: # ;; # *) # Make sure the first unrecognised option "$_G_opt" # # is added back to "$@" in case we need it later, # # if $args_changed was set to 'true'. # set dummy "$_G_opt" ${1+"$@"}; shift; break ;; # esac # done # # # Only call 'func_quote' here if we processed at least one argument. # if $args_changed; then # func_quote eval ${1+"$@"} # my_silent_option_result=$func_quote_result # fi # } # func_add_hook func_parse_options my_silent_option # # # my_option_validation () # { # $debug_cmd # # $opt_silent && $opt_verbose && func_fatal_help "\ # '--silent' and '--verbose' options are mutually exclusive." # } # func_add_hook func_validate_options my_option_validation # # You'll also need to manually amend $usage_message to reflect the extra # options you parse. It's preferable to append if you can, so that # multiple option parsing hooks can be added safely. # func_options_finish [ARG]... # ---------------------------- # Finishing the option parse loop (call 'func_options' hooks ATM). func_options_finish () { $debug_cmd func_run_hooks func_options ${1+"$@"} func_propagate_result func_run_hooks func_options_finish } # func_options [ARG]... # --------------------- # All the functions called inside func_options are hookable. See the # individual implementations for details. func_hookable func_options func_options () { $debug_cmd _G_options_quoted=false for my_func in options_prep parse_options validate_options options_finish do func_unset func_${my_func}_result func_unset func_run_hooks_result eval func_$my_func '${1+"$@"}' func_propagate_result func_$my_func func_options if $func_propagate_result_result; then eval set dummy "$func_options_result"; shift _G_options_quoted=: fi done $_G_options_quoted || { # As we (func_options) are top-level options-parser function and # nobody quoted "$@" for us yet, we need to do it explicitly for # caller. func_quote eval ${1+"$@"} func_options_result=$func_quote_result } } # func_options_prep [ARG]... # -------------------------- # All initialisations required before starting the option parse loop. # Note that when calling hook functions, we pass through the list of # positional parameters. If a hook function modifies that list, and # needs to propagate that back to rest of this script, then the complete # modified list must be put in 'func_run_hooks_result' before returning. func_hookable func_options_prep func_options_prep () { $debug_cmd # Option defaults: opt_verbose=false opt_warning_types= func_run_hooks func_options_prep ${1+"$@"} func_propagate_result func_run_hooks func_options_prep } # func_parse_options [ARG]... # --------------------------- # The main option parsing loop. func_hookable func_parse_options func_parse_options () { $debug_cmd _G_parse_options_requote=false # this just eases exit handling while test $# -gt 0; do # Defer to hook functions for initial option parsing, so they # get priority in the event of reusing an option name. func_run_hooks func_parse_options ${1+"$@"} func_propagate_result func_run_hooks func_parse_options if $func_propagate_result_result; then eval set dummy "$func_parse_options_result"; shift # Even though we may have changed "$@", we passed the "$@" array # down into the hook and it quoted it for us (because we are in # this if-branch). No need to quote it again. _G_parse_options_requote=false fi # Break out of the loop if we already parsed every option. test $# -gt 0 || break # We expect that one of the options parsed in this function matches # and thus we remove _G_opt from "$@" and need to re-quote. _G_match_parse_options=: _G_opt=$1 shift case $_G_opt in --debug|-x) debug_cmd='set -x' func_echo "enabling shell trace mode" >&2 $debug_cmd ;; --no-warnings|--no-warning|--no-warn) set dummy --warnings none ${1+"$@"} shift ;; --warnings|--warning|-W) if test $# = 0 && func_missing_arg $_G_opt; then _G_parse_options_requote=: break fi case " $warning_categories $1" in *" $1 "*) # trailing space prevents matching last $1 above func_append_uniq opt_warning_types " $1" ;; *all) opt_warning_types=$warning_categories ;; *none) opt_warning_types=none warning_func=: ;; *error) opt_warning_types=$warning_categories warning_func=func_fatal_error ;; *) func_fatal_error \ "unsupported warning category: '$1'" ;; esac shift ;; --verbose|-v) opt_verbose=: ;; --version) func_version ;; -\?|-h) func_usage ;; --help) func_help ;; # Separate optargs to long options (plugins may need this): --*=*) func_split_equals "$_G_opt" set dummy "$func_split_equals_lhs" \ "$func_split_equals_rhs" ${1+"$@"} shift ;; # Separate optargs to short options: -W*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "$func_split_short_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-v*|-x*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) _G_parse_options_requote=: ; break ;; -*) func_fatal_help "unrecognised option: '$_G_opt'" ;; *) set dummy "$_G_opt" ${1+"$@"}; shift _G_match_parse_options=false break ;; esac if $_G_match_parse_options; then _G_parse_options_requote=: fi done if $_G_parse_options_requote; then # save modified positional parameters for caller func_quote eval ${1+"$@"} func_parse_options_result=$func_quote_result fi } # func_validate_options [ARG]... # ------------------------------ # Perform any sanity checks on option settings and/or unconsumed # arguments. func_hookable func_validate_options func_validate_options () { $debug_cmd # Display all warnings if -W was not given. test -n "$opt_warning_types" || opt_warning_types=" $warning_categories" func_run_hooks func_validate_options ${1+"$@"} func_propagate_result func_run_hooks func_validate_options # Bail if the options were screwed! $exit_cmd $EXIT_FAILURE } ## ----------------- ## ## Helper functions. ## ## ----------------- ## # This section contains the helper functions used by the rest of the # hookable option parser framework in ascii-betical order. # func_fatal_help ARG... # ---------------------- # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { $debug_cmd eval \$ECHO \""Usage: $usage"\" eval \$ECHO \""$fatal_help"\" func_error ${1+"$@"} exit $EXIT_FAILURE } # func_help # --------- # Echo long help message to standard output and exit. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message" exit 0 } # func_missing_arg ARGNAME # ------------------------ # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $debug_cmd func_error "Missing argument for '$1'." exit_cmd=exit } # func_split_equals STRING # ------------------------ # Set func_split_equals_lhs and func_split_equals_rhs shell variables # after splitting STRING at the '=' sign. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_equals () { $debug_cmd func_split_equals_lhs=${1%%=*} func_split_equals_rhs=${1#*=} if test "x$func_split_equals_lhs" = "x$1"; then func_split_equals_rhs= fi }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_equals () { $debug_cmd func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'` func_split_equals_rhs= test "x$func_split_equals_lhs=" = "x$1" \ || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'` } fi #func_split_equals # func_split_short_opt SHORTOPT # ----------------------------- # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_short_opt () { $debug_cmd func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"} }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_short_opt () { $debug_cmd func_split_short_opt_name=`expr "x$1" : 'x\(-.\)'` func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'` } fi #func_split_short_opt # func_usage # ---------- # Echo short help message to standard output and exit. func_usage () { $debug_cmd func_usage_message $ECHO "Run '$progname --help |${PAGER-more}' for full usage" exit 0 } # func_usage_message # ------------------ # Echo short help message to standard output. func_usage_message () { $debug_cmd eval \$ECHO \""Usage: $usage"\" echo $SED -n 's|^# || /^Written by/{ x;p;x } h /^Written by/q' < "$progpath" echo eval \$ECHO \""$usage_message"\" } # func_version # ------------ # Echo version message to standard output and exit. # The version message is extracted from the calling file's header # comments, with leading '# ' stripped: # 1. First display the progname and version # 2. Followed by the header comment line matching /^# Written by / # 3. Then a blank line followed by the first following line matching # /^# Copyright / # 4. Immediately followed by any lines between the previous matches, # except lines preceding the intervening completely blank line. # For example, see the header comments of this file. func_version () { $debug_cmd printf '%s\n' "$progname $scriptversion" $SED -n ' /^# Written by /!b s|^# ||; p; n :fwd2blnk /./ { n b fwd2blnk } p; n :holdwrnt s|^# || s|^# *$|| /^Copyright /!{ /./H n b holdwrnt } s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2| G s|\(\n\)\n*|\1|g p; q' < "$progpath" exit $? } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "30/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: # Set a version string. scriptversion='(GNU libtool) 2.4.7' # func_echo ARG... # ---------------- # Libtool also displays the current mode in messages, so override # funclib.sh func_echo with this custom definition. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line" done IFS=$func_echo_IFS } # func_warning ARG... # ------------------- # Libtool warnings are not categorized, so override funclib.sh # func_warning with this simpler definition. func_warning () { $debug_cmd $warning_func ${1+"$@"} } ## ---------------- ## ## Options parsing. ## ## ---------------- ## # Hook in the functions to make sure our own options are parsed during # the option parsing loop. usage='$progpath [OPTION]... [MODE-ARG]...' # Short help message in response to '-h'. usage_message="Options: --config show all configuration variables --debug enable verbose shell tracing -n, --dry-run display commands without modifying any files --features display basic configuration information and exit --mode=MODE use operation mode MODE --no-warnings equivalent to '-Wnone' --preserve-dup-deps don't remove duplicate dependency libraries --quiet, --silent don't print informational messages --tag=TAG use configuration variables from tag TAG -v, --verbose print more informational messages than default --version print version information -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -h, --help, --help-all print short, long, or detailed help message " # Additional text appended to 'usage_message' in response to '--help'. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message MODE must be one of the following: clean remove files from the build directory compile compile a source file into a libtool object execute automatically set library path, then run a program finish complete the installation of libtool libraries install install libraries or executables link create a library or an executable uninstall remove libraries from an installed directory MODE-ARGS vary depending on the MODE. When passed as first option, '--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that. Try '$progname --help --mode=MODE' for a more detailed description of MODE. When reporting a bug, please describe a test case to reproduce it and include the following information: host-triplet: $host shell: $SHELL compiler: $LTCC compiler flags: $LTCFLAGS linker: $LD (gnu? $with_gnu_ld) version: $progname (GNU libtool) 2.4.7 automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` Report bugs to . GNU libtool home page: . General help using GNU software: ." exit 0 } # func_lo2o OBJECT-NAME # --------------------- # Transform OBJECT-NAME from a '.lo' suffix to the platform specific # object suffix. lo2o=s/\\.lo\$/.$objext/ o2lo=s/\\.$objext\$/.lo/ if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_lo2o () { case $1 in *.lo) func_lo2o_result=${1%.lo}.$objext ;; * ) func_lo2o_result=$1 ;; esac }' # func_xform LIBOBJ-OR-SOURCE # --------------------------- # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise) # suffix to a '.lo' libtool-object suffix. eval 'func_xform () { func_xform_result=${1%.*}.lo }' else # ...otherwise fall back to using sed. func_lo2o () { func_lo2o_result=`$ECHO "$1" | $SED "$lo2o"` } func_xform () { func_xform_result=`$ECHO "$1" | $SED 's|\.[^.]*$|.lo|'` } fi # func_fatal_configuration ARG... # ------------------------------- # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_fatal_error ${1+"$@"} \ "See the $PACKAGE documentation for more information." \ "Fatal configuration error." } # func_config # ----------- # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # ------------- # Display the features supported by this script. func_features () { echo "host: $host" if test yes = "$build_libtool_libs"; then echo "enable shared libraries" else echo "disable shared libraries" fi if test yes = "$build_old_libs"; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag TAGNAME # ----------------------- # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname=$1 re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf=/$re_begincf/,/$re_endcf/p # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # ------------------------ # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # libtool_options_prep [ARG]... # ----------------------------- # Preparation for options parsed by libtool. libtool_options_prep () { $debug_mode # Option defaults: opt_config=false opt_dlopen= opt_dry_run=false opt_help=false opt_mode= opt_preserve_dup_deps=false opt_quiet=false nonopt= preserve_args= _G_rc_lt_options_prep=: # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; *) _G_rc_lt_options_prep=false ;; esac if $_G_rc_lt_options_prep; then # Pass back the list of options. func_quote eval ${1+"$@"} libtool_options_prep_result=$func_quote_result fi } func_add_hook func_options_prep libtool_options_prep # libtool_parse_options [ARG]... # --------------------------------- # Provide handling for libtool specific options. libtool_parse_options () { $debug_cmd _G_rc_lt_parse_options=false # Perform our own loop to consume as many options as possible in # each iteration. while test $# -gt 0; do _G_match_lt_parse_options=: _G_opt=$1 shift case $_G_opt in --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) func_config ;; --dlopen|-dlopen) opt_dlopen="${opt_dlopen+$opt_dlopen }$1" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) func_features ;; --finish) set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $_G_opt && break opt_mode=$1 case $1 in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $_G_opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_quiet=false func_append preserve_args " $_G_opt" ;; --no-warnings|--no-warning|--no-warn) opt_warning=false func_append preserve_args " $_G_opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $_G_opt" ;; --silent|--quiet) opt_quiet=: opt_verbose=false func_append preserve_args " $_G_opt" ;; --tag) test $# = 0 && func_missing_arg $_G_opt && break opt_tag=$1 func_append preserve_args " $_G_opt $1" func_enable_tag "$1" shift ;; --verbose|-v) opt_quiet=false opt_verbose=: func_append preserve_args " $_G_opt" ;; # An option not handled by this hook function: *) set dummy "$_G_opt" ${1+"$@"} ; shift _G_match_lt_parse_options=false break ;; esac $_G_match_lt_parse_options && _G_rc_lt_parse_options=: done if $_G_rc_lt_parse_options; then # save modified positional parameters for caller func_quote eval ${1+"$@"} libtool_parse_options_result=$func_quote_result fi } func_add_hook func_parse_options libtool_parse_options # libtool_validate_options [ARG]... # --------------------------------- # Perform any sanity checks on option settings and/or unconsumed # arguments. libtool_validate_options () { # save first non-option argument if test 0 -lt $#; then nonopt=$1 shift fi # preserve --debug test : = "$debug_cmd" || func_append preserve_args " --debug" # Keeping compiler generated duplicates in $postdeps and $predeps is not # harmful, and is necessary in a majority of systems that use it to satisfy # symbol dependencies. opt_duplicate_compiler_generated_deps=: $opt_help || { # Sanity checks first: func_check_version_match test yes != "$build_libtool_libs" \ && test yes != "$build_old_libs" \ && func_fatal_configuration "not configured to build any kind of library" # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test execute != "$opt_mode"; then func_error "unrecognized option '-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help=$help help="Try '$progname --help --mode=$opt_mode' for more information." } # Pass back the unparsed argument list func_quote eval ${1+"$@"} libtool_validate_options_result=$func_quote_result } func_add_hook func_validate_options libtool_validate_options # Process options as early as possible so that --help and --version # can return quickly. func_options ${1+"$@"} eval set dummy "$func_options_result"; shift ## ----------- ## ## Main. ## ## ----------- ## magic='%%%MAGIC variable%%%' magic_exe='%%%MAGIC EXE variable%%%' # Global variables. extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # func_generated_by_libtool # True iff stdin has been generated by Libtool. This function is only # a basic sanity check; it will hardly flush out determined imposters. func_generated_by_libtool_p () { $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null | func_generated_by_libtool_p } # func_lalib_unsafe_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if 'file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case $lalib_p_line in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test yes = "$lalib_p" } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { test -f "$1" && $lt_truncate_bin < "$1" 2>/dev/null | func_generated_by_libtool_p } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $debug_cmd save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # 'FILE.' does not work on cygwin managed mounts. func_source () { $debug_cmd case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case $lt_sysroot:$1 in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result='='$func_stripname_result ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $debug_cmd if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with '--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=$1 if test yes = "$build_libtool_libs"; then write_lobj=\'$2\' else write_lobj=none fi if test yes = "$build_old_libs"; then write_oldobj=\'$3\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "$func_convert_core_file_wine_to_w32_tmp"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $debug_cmd # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result= if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result"; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $debug_cmd if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $debug_cmd # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $debug_cmd if test -z "$2" && test -n "$1"; then func_error "Could not determine host file name corresponding to" func_error " '$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result=$1 fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $debug_cmd if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " '$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result=$3 fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $debug_cmd case $4 in $1 ) func_to_host_path_result=$3$func_to_host_path_result ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via '$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $debug_cmd $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $debug_cmd case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result=$1 } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result=$func_convert_core_msys_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result=$func_convert_core_file_wine_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via '$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $debug_cmd if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd=func_convert_path_$func_stripname_result fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $debug_cmd func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result=$1 } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_msys_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_path_wine_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_dll_def_p FILE # True iff FILE is a Windows DLL '.def' file. # Keep in sync with _LT_DLL_DEF_P in libtool.m4 func_dll_def_p () { $debug_cmd func_dll_def_p_tmp=`$SED -n \ -e 's/^[ ]*//' \ -e '/^\(;.*\)*$/d' \ -e 's/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p' \ -e q \ "$1"` test DEF = "$func_dll_def_p_tmp" } # func_mode_compile arg... func_mode_compile () { $debug_cmd # Get the compilation command and the source file. base_compile= srcfile=$nonopt # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg=$arg arg_mode=normal ;; target ) libobj=$arg arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify '-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs=$IFS; IFS=, for arg in $args; do IFS=$save_ifs func_append_quoted lastarg "$arg" done IFS=$save_ifs func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg=$srcfile srcfile=$arg ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with '-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj=$func_basename_result } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from '$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test yes = "$build_libtool_libs" \ || func_fatal_configuration "cannot build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_arg pretty "$libobj" test "X$libobj" != "X$func_quote_arg_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name '$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname=$func_basename_result xdir=$func_dirname_result lobj=$xdir$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test yes = "$build_old_libs"; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test no = "$pic_mode" && test pass_all != "$deplibs_check_method"; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test no = "$compiler_c_o"; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.$objext lockfile=$output_obj.lock else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test yes = "$need_locks"; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test warn = "$need_locks"; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_arg pretty "$srcfile" qsrcfile=$func_quote_arg_result # Only build a PIC object if we are building libtool libraries. if test yes = "$build_libtool_libs"; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test no != "$pic_mode"; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test yes = "$suppress_opt"; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test yes = "$build_old_libs"; then if test yes != "$pic_mode"; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test yes = "$compiler_c_o"; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test no != "$need_locks"; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test compile = "$opt_mode" && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a '.o' file suitable for static linking -static only build a '.o' file suitable for static linking -Wc,FLAG -Xcompiler FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a 'standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix '.c' with the library object suffix, '.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to '-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the '--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the 'install' or 'cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE '-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE use a list of object files found in FILE to specify objects -os2dllname NAME force a short DLL name on OS/2 (no effect on other OSes) -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wa,FLAG -Xassembler FLAG pass linker-specific FLAG directly to the assembler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with '-') are ignored. Every other argument is treated as a filename. Files ending in '.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in '.la', then a libtool library is created, only library objects ('.lo' files) may be specified, and '-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created using 'ar' and 'ranlib', or on Windows using 'lib'. If OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode '$opt_mode'" ;; esac echo $ECHO "Try '$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test : = "$opt_help"; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | $SED -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | $SED '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $debug_cmd # The first argument is the command name. cmd=$nonopt test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "'$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "'$file' was not linked with '-export-dynamic'" continue fi func_dirname "$file" "" "." dir=$func_dirname_result if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find '$dlname' in '$dir' or '$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir=$func_dirname_result ;; *) func_warning "'-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir=$absdir # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic=$magic # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file=$progdir/$program elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file=$progdir/$program fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if $opt_dry_run; then # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS else if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd=\$cmd$args fi } test execute = "$opt_mode" && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $debug_cmd libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "'$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument '$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and '=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do $SED -e "$sysroot_cmd s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_quiet && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the '-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the '$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the '$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the '$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to '/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test finish = "$opt_mode" && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $debug_cmd # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$SHELL" = "$nonopt" || test /bin/sh = "$nonopt" || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac then # Aesthetically quote it. func_quote_arg pretty "$nonopt" install_prog="$func_quote_arg_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_arg pretty "$arg" func_append install_prog "$func_quote_arg_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=false stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=: ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test X-m = "X$prev" && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_arg pretty "$arg" func_append install_prog " $func_quote_arg_result" if test -n "$arg2"; then func_quote_arg pretty "$arg2" fi func_append install_shared_prog " $func_quote_arg_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the '$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_arg pretty "$install_override_mode" func_append install_shared_prog " -m $func_quote_arg_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=: if $isdir; then destdir=$dest destname= else func_dirname_and_basename "$dest" "" "." destdir=$func_dirname_result destname=$func_basename_result # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "'$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "'$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir=$func_dirname_result func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install '$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking '$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname=$1 shift srcname=$realname test -n "$relink_command" && srcname=${realname}T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme=$stripme case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme= ;; esac ;; os2*) case $realname in *_dll.a) tstripme= ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try 'ln -sf' first, because the 'ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib=$destdir/$realname func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name=$func_basename_result instname=$dir/${name}i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest=$destfile destfile= ;; *) func_fatal_help "cannot copy a libtool object to '$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test yes = "$build_old_libs"; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext= case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=.exe fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script '$wrapper'" finalize=: for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile=$libdir/`$ECHO "$lib" | $SED 's%^.*/%%g'` if test -n "$libdir" && test ! -f "$libfile"; then func_warning "'$lib' has not been installed in '$libdir'" finalize=false fi done relink_command= func_source "$wrapper" outputname= if test no = "$fast_install" && test -n "$relink_command"; then $opt_dry_run || { if $finalize; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file=$func_basename_result outputname=$tmpdir/$file # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_quiet || { func_quote_arg expand,pretty "$relink_command" eval "func_echo $func_quote_arg_result" } if eval "$relink_command"; then : else func_error "error: relink '$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file=$outputname else func_warning "cannot relink '$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name=$func_basename_result # Set up the ranlib parameters. oldlib=$destdir/$name func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run '$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL "$progpath" $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test install = "$opt_mode" && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $debug_cmd my_outputname=$1 my_originator=$2 my_pic_p=${3-false} my_prefix=`$ECHO "$my_originator" | $SED 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms=${my_outputname}S.c else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist=$output_objdir/$my_outputname.nm func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* External symbol declarations for the compiler. */\ " if test yes = "$dlself"; then func_verbose "generating symbol list for '$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from '$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols=$output_objdir/$outputname.exp $opt_dry_run || { $RM $export_symbols eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "$SED -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from '$dlprefile'" func_basename "$dlprefile" name=$func_basename_result case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename= if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname"; then func_basename "$dlprefile_dlname" dlprefile_dlbasename=$func_basename_result else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename"; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi func_show_eval '$RM "${nlist}I"' if test -n "$global_symbol_to_import"; then eval "$global_symbol_to_import"' < "$nlist"S > "$nlist"I' fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[];\ " if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ static void lt_syminit(void) { LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols; for (; symbol->name; ++symbol) {" $SED 's/.*/ if (STREQ (symbol->name, \"&\")) symbol->address = (void *) \&&;/' < "$nlist"I >> "$output_objdir/$my_dlsyms" echo >> "$output_objdir/$my_dlsyms" "\ } }" fi echo >> "$output_objdir/$my_dlsyms" "\ LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = { {\"$my_originator\", (void *) 0}," if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ {\"@INIT@\", (void *) <_syminit}," fi case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) $my_pic_p && pic_flag_for_symtable=" $pic_flag" ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T" "${nlist}I"' # Transform the symbol file into the correct name. symfileobj=$output_objdir/${my_outputname}S.$objext case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for '$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $debug_cmd win32_libid_type=unknown win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then case $nm_interface in "MS dumpbin") if func_cygming_ms_implib_p "$1" || func_cygming_gnu_implib_p "$1" then win32_nmres=import else win32_nmres= fi ;; *) func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s|.*|import| p q } }'` ;; esac case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $debug_cmd sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $debug_cmd match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive that possess that section. Heuristic: eliminate # all those that have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $debug_cmd if func_cygming_gnu_implib_p "$1"; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1"; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result= fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $debug_cmd f_ex_an_ar_dir=$1; shift f_ex_an_ar_oldlib=$1 if test yes = "$lock_old_archive_extraction"; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test yes = "$lock_old_archive_extraction"; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $debug_cmd my_gentop=$1; shift my_oldlibs=${1+"$@"} my_oldobjs= my_xlib= my_xabs= my_xdir= for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs=$my_xlib ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib=$func_basename_result my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir=$my_gentop/$my_xlib_u func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` func_basename "$darwin_archive" darwin_base_archive=$func_basename_result darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches; do func_mkdir_p "unfat-$$/$darwin_base_archive-$darwin_arch" $LIPO -thin $darwin_arch -output "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" "$darwin_archive" cd "unfat-$$/$darwin_base_archive-$darwin_arch" func_extract_an_archive "`pwd`" "$darwin_base_archive" cd "$darwin_curdir" $RM "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$sed_basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result=$my_oldobjs } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory where it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" func_quote_arg pretty "$ECHO" qECHO=$func_quote_arg_result $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=$qECHO fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ that is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options that match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"$outputname:$output:\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"$outputname:$output:\$LINENO: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test yes = "$fast_install"; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | $SED 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else \$ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: '\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* declarations of non-ANSI functions */ #if defined __MINGW32__ # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined __CYGWIN__ # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined other_platform || defined ... */ #endif /* portability defines, excluding path handling macros */ #if defined _MSC_VER # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC #elif defined __MINGW32__ # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined __CYGWIN__ # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined other platforms ... */ #endif #if defined PATH_MAX # define LT_PATHMAX PATH_MAX #elif defined MAXPATHLEN # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \ defined __OS2__ # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free (stale); stale = 0; } \ } while (0) #if defined LT_DEBUGWRAPPER static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; size_t tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined HAVE_DOS_BASED_FILE_SYSTEM if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined HAVE_DOS_BASED_FILE_SYSTEM } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = (size_t) (q - p); p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (STREQ (str, pat)) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else size_t len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { size_t orig_value_len = strlen (orig_value); size_t add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ size_t len = strlen (new_value); while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[--len] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \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" #define SHELL_SPACE_CHARS " \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" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $debug_cmd case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_suncc_cstd_abi # !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!! # Several compiler flags select an ABI that is incompatible with the # Cstd library. Avoid specifying it if any are in CXXFLAGS. func_suncc_cstd_abi () { $debug_cmd case " $compile_command " in *" -compat=g "*|*\ -std=c++[0-9][0-9]\ *|*" -library=stdcxx4 "*|*" -library=stlport4 "*) suncc_use_cstd_abi=no ;; *) suncc_use_cstd_abi=yes ;; esac } # func_mode_link arg... func_mode_link () { $debug_cmd case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # what system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll that has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= os2dllname= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=false prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module=$wl-single_module func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test yes != "$build_libtool_libs" \ && func_fatal_configuration "cannot build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test yes = "$build_libtool_libs" && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg=$1 shift func_quote_arg pretty,unquoted "$arg" qarg=$func_quote_arg_unquoted_result func_append libtool_args " $func_quote_arg_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir=$arg prev= continue ;; dlfiles|dlprefiles) $preload || { # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=: } case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test no = "$dlself"; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test dlprefiles = "$prev"; then dlself=yes elif test dlfiles = "$prev" && test yes != "$dlopen_self"; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test dlfiles = "$prev"; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols=$arg test -f "$arg" \ || func_fatal_error "symbol file '$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex=$arg prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir=$arg prev= continue ;; mllvm) # Clang does not use LLVM to link, so we can simply discard any # '-mllvm $arg' options when doing the link step. prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result if test none != "$pic_object"; then # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object fi # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file '$arg' does not exist" fi arg=$save_arg prev= continue ;; os2dllname) os2dllname=$arg prev= continue ;; precious_regex) precious_files_regex=$arg prev= continue ;; release) release=-$arg prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test rpath = "$prev"; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds=$arg prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xassembler) func_append compiler_flags " -Xassembler $qarg" prev= func_append compile_command " -Xassembler $qarg" func_append finalize_command " -Xassembler $qarg" continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg=$arg case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "'-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test X-export-symbols = "X$arg"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between '-L' and '$1'" else func_fatal_error "need path for '-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of '$dir'" dir=$absdir ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test X-lc = "X$arg" || test X-lm = "X$arg"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test X-lc = "X$arg" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) # Do not include libc due to us having libc/libc_r. test X-lc = "X$arg" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test X-lc = "X$arg" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test X-lc = "X$arg" && continue ;; esac elif test X-lc_r = "X$arg"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -mllvm) prev=mllvm continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; # Solaris ld rejects as of 11.4. Refer to Oracle bug 22985199. -pthread) case $host in *solaris2*) ;; *) case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac ;; esac continue ;; -mt|-mthreads|-kthread|-Kthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module=$wl-multi_module continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "'-no-install' is ignored for $host" func_warning "assuming '-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -os2dllname) prev=os2dllname continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_arg pretty "$flag" func_append arg " $func_quote_arg_result" func_append compiler_flags " $func_quote_arg_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_arg pretty "$flag" func_append arg " $wl$func_quote_arg_result" func_append compiler_flags " $wl$func_quote_arg_result" func_append linker_flags " $func_quote_arg_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xassembler) prev=xassembler continue ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_arg pretty "$arg" arg=$func_quote_arg_result ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # -fstack-protector* stack protector flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization # -specs=* GCC specs files # -stdlib=* select c++ std lib with clang # -fsanitize=* Clang/GCC memory and address sanitizer # -fuse-ld=* Linker select flags for GCC # -Wa,* Pass flags directly to the assembler -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \ -specs=*|-fsanitize=*|-fuse-ld=*|-Wa,*) func_quote_arg pretty "$arg" arg=$func_quote_arg_result func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; -Z*) if test os2 = "`expr $host : '.*\(os2\)'`"; then # OS/2 uses -Zxxx to specify OS/2-specific options compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case $arg in -Zlinker | -Zstack) prev=xcompiler ;; esac continue else # Otherwise treat like 'Some other compiler flag' below func_quote_arg pretty "$arg" arg=$func_quote_arg_result fi ;; # Some other compiler flag. -* | +*) func_quote_arg pretty "$arg" arg=$func_quote_arg_result ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result test none = "$pic_object" || { # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object } # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test dlfiles = "$prev"; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test dlprefiles = "$prev"; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_arg pretty "$arg" arg=$func_quote_arg_result ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the '$prevarg' option requires an argument" if test yes = "$export_dynamic" && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname=$func_basename_result libobjs_save=$libobjs if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\$$shlibpath_var\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" # Definition is injected by LT_CONFIG during libtool generation. func_munge_path_list sys_lib_dlsearch_path "$LT_SYS_LIBRARY_PATH" func_dirname "$output" "/" "" output_objdir=$func_dirname_result$objdir func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test lib = "$linkmode"; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can '-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=false newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test lib,link = "$linkmode,$pass"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs=$tmp_deplibs fi if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass"; then libs=$deplibs deplibs= fi if test prog = "$linkmode"; then case $pass in dlopen) libs=$dlfiles ;; dlpreopen) libs=$dlprefiles ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test lib,dlpreopen = "$linkmode,$pass"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs=$dlprefiles fi if test dlopen = "$pass"; then # Collect dlpreopened libraries save_deplibs=$deplibs deplibs= fi for deplib in $libs; do lib= found=false case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test lib != "$linkmode" && test prog != "$linkmode"; then func_warning "'-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test lib = "$linkmode"; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib=$searchdir/lib$name$search_ext if test -f "$lib"; then if test .la = "$search_ext"; then found=: else found=false fi break 2 fi done done if $found; then # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll=$l done if test "X$ll" = "X$old_library"; then # only static version available found=false func_dirname "$lib" "" "." ladir=$func_dirname_result lib=$ladir/$old_library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi else # deplib doesn't seem to be a libtool library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi ;; # -l *.ltframework) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test conv = "$pass" && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi if test scan = "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "'-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test link = "$pass"; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=false case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=: fi ;; pass_all) valid_a_lib=: ;; esac if $valid_a_lib; then echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" else echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." fi ;; esac continue ;; prog) if test link != "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test conv = "$pass"; then deplibs="$deplib $deplibs" elif test prog = "$linkmode"; then if test dlpreopen = "$pass" || test yes != "$dlopen_support" || test no = "$build_libtool_libs"; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=: continue ;; esac # case $deplib $found || test -f "$lib" \ || func_fatal_error "cannot find the library '$lib' or unhandled argument '$deplib'" # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "'$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir=$func_dirname_result dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass" || { test prog != "$linkmode" && test lib != "$linkmode"; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test conv = "$pass"; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for '$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" elif test prog != "$linkmode" && test lib != "$linkmode"; then func_fatal_error "'$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test yes = "$prefer_static_libs" || test built,no = "$prefer_static_libs,$installed"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib=$l done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for '$lib'" fi # This library was specified with -dlopen. if test dlopen = "$pass"; then test -z "$libdir" \ && func_fatal_error "cannot -dlopen a convenience library: '$lib'" if test -z "$dlname" || test yes != "$dlopen_support" || test no = "$build_libtool_libs" then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir=$ladir ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of '$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir=$ladir fi ;; esac func_basename "$lib" laname=$func_basename_result # Find the relevant object directory and library name. if test yes = "$installed"; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library '$lib' was moved." dir=$ladir absdir=$abs_ladir libdir=$abs_ladir else dir=$lt_sysroot$libdir absdir=$lt_sysroot$libdir fi test yes = "$hardcode_automatic" && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir=$ladir absdir=$abs_ladir # Remove this search path later func_append notinst_path " $abs_ladir" else dir=$ladir/$objdir absdir=$abs_ladir/$objdir # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test dlpreopen = "$pass"; then if test -z "$libdir" && test prog = "$linkmode"; then func_fatal_error "only libraries may -dlpreopen a convenience library: '$lib'" fi case $host in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test lib = "$linkmode"; then deplibs="$dir/$old_library $deplibs" elif test prog,link = "$linkmode,$pass"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test prog = "$linkmode" && test link != "$pass"; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=false if test no != "$link_all_deplibs" || test -z "$library_names" || test no = "$build_libtool_libs"; then linkalldeplibs=: fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if $linkalldeplibs; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test prog,link = "$linkmode,$pass"; then if test -n "$library_names" && { { test no = "$prefer_static_libs" || test built,yes = "$prefer_static_libs,$installed"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath"; then # Make sure the rpath contains only unique directories. case $temp_rpath: in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if $alldeplibs && { test pass_all = "$deplibs_check_method" || { test yes = "$build_libtool_libs" && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test built = "$use_static_libs" && test yes = "$installed"; then use_static_libs=no fi if test -n "$library_names" && { test no = "$use_static_libs" || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc* | *os2*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test no = "$installed"; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule= for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule=$dlpremoduletest break fi done if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then echo if test prog = "$linkmode"; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test lib = "$linkmode" && test yes = "$hardcode_into_libs"; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname=$1 shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname=$dlname elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc* | *os2*) func_arith $current - $age major=$func_arith_result versuffix=-$major ;; esac eval soname=\"$soname_spec\" else soname=$realname fi # Make a new name for the extract_expsyms_cmds to use soroot=$soname func_basename "$soroot" soname=$func_basename_result func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from '$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for '$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test prog = "$linkmode" || test relink != "$opt_mode"; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test no = "$hardcode_direct"; then add=$dir/$linklib case $host in *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;; *-*-sysv4*uw2*) add_dir=-L$dir ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir=-L$dir ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we cannot # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library"; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add=$dir/$old_library fi elif test -n "$old_library"; then add=$dir/$old_library fi fi esac elif test no = "$hardcode_minus_L"; then case $host in *-*-sunos*) add_shlibpath=$dir ;; esac add_dir=-L$dir add=-l$name elif test no = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; relink) if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$dir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$absdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name elif test yes = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; *) lib_linked=no ;; esac if test yes != "$lib_linked"; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test prog = "$linkmode"; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test yes != "$hardcode_direct" && test yes != "$hardcode_minus_L" && test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test prog = "$linkmode" || test relink = "$opt_mode"; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$libdir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$libdir add=-l$name elif test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add=-l$name elif test yes = "$hardcode_automatic"; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib"; then add=$inst_prefix_dir$libdir/$linklib else add=$libdir/$linklib fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir=-L$libdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name fi if test prog = "$linkmode"; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test prog = "$linkmode"; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test unsupported != "$hardcode_direct"; then test -n "$old_library" && linklib=$old_library compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test yes = "$build_libtool_libs"; then # Not a shared library if test pass_all != "$deplibs_check_method"; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system cannot link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test yes = "$module"; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test lib = "$linkmode"; then if test -n "$dependency_libs" && { test yes != "$hardcode_into_libs" || test yes = "$build_old_libs" || test yes = "$link_static"; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs=$temp_deplibs fi func_append newlib_search_path " $absdir" # Link against this library test no = "$link_static" && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test no != "$link_all_deplibs"; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path=$deplib ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir=$dir ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of '$dir'" absdir=$dir fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`$SED -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names"; then for tmp in $deplibrary_names; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl"; then depdepl=$absdir/$objdir/$depdepl darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`$OTOOL64 -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " $wl-dylib_file $wl$darwin_install_name:$depdepl" func_append linker_flags " -dylib_file $darwin_install_name:$depdepl" path= fi fi ;; *) path=-L$absdir/$objdir ;; esac else eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "'$deplib' seems to be moved" path=-L$absdir fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test link = "$pass"; then if test prog = "$linkmode"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs=$newdependency_libs if test dlpreopen = "$pass"; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test dlopen != "$pass"; then test conv = "$pass" || { # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= } if test prog,link = "$linkmode,$pass"; then vars="compile_deplibs finalize_deplibs" else vars=deplibs fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Add Sun CC postdeps if required: test CXX = "$tagname" && { case $host_os in linux*) case `$CC -V 2>&1 | $SED 5q` in *Sun\ C*) # Sun C++ 5.9 func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; solaris*) func_cc_basename "$CC" case $func_cc_basename_result in CC* | sunCC*) func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; esac } # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i= ;; esac if test -n "$i"; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test prog = "$linkmode"; then dlfiles=$newdlfiles fi if test prog = "$linkmode" || test lib = "$linkmode"; then dlprefiles=$newdlprefiles fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "'-R' is ignored for archives" test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "'-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "'-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs=$output func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form 'libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test no = "$module" \ && func_fatal_help "libtool library '$output' must begin with 'lib'" if test no != "$need_lib_prefix"; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test pass_all != "$deplibs_check_method"; then func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test no = "$dlself" \ || func_warning "'-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test 1 -lt "$#" \ && func_warning "ignoring multiple '-rpath's for a libtool library" install_libdir=$1 oldlibs= if test -z "$rpath"; then if test yes = "$build_libtool_libs"; then # Building a libtool convenience library. # Some compilers have problems with a '.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "'-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs=$IFS; IFS=: set dummy $vinfo 0 0 0 shift IFS=$save_ifs test -n "$7" && \ func_fatal_help "too many parameters to '-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major=$1 number_minor=$2 number_revision=$3 # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # that has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|freebsd-elf|linux|midnightbsd-elf|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_revision ;; freebsd-aout|qnx|sunos) current=$number_major revision=$number_minor age=0 ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_minor lt_irix_increment=no ;; esac ;; no) current=$1 revision=$2 age=$3 ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT '$current' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION '$revision' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE '$age' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE '$age' is greater than the current interface number '$current'" func_fatal_error "'$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" # On Darwin other compilers case $CC in nagfor*) verstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" ;; *) verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; esac ;; freebsd-aout) major=.$current versuffix=.$current.$revision ;; freebsd-elf | midnightbsd-elf) func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; irix | nonstopux) if test no = "$lt_irix_increment"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring=$verstring_prefix$major.$revision # Add in all the interfaces that we are compatible with. loop=$revision while test 0 -ne "$loop"; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring_prefix$major.$iface:$verstring done # Before this point, $major must not contain '.'. major=.$major versuffix=$major.$revision ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=.$current.$age.$revision verstring=$current.$age.$revision # Add in all the interfaces that we are compatible with. loop=$age while test 0 -ne "$loop"; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring:$iface.0 done # Make executables depend on our current version. func_append verstring ":$current.0" ;; qnx) major=.$current versuffix=.$current ;; sco) major=.$current versuffix=.$current ;; sunos) major=.$current versuffix=.$current.$revision ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 file systems. func_arith $current - $age major=$func_arith_result versuffix=-$major ;; *) func_fatal_configuration "unknown library version type '$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring=0.0 ;; esac if test no = "$need_version"; then versuffix= else versuffix=.0.0 fi fi # Remove version info from name if versioning should be avoided if test yes,no = "$avoid_version,$need_version"; then major= versuffix= verstring= fi # Check to see if the archive will have undefined symbols. if test yes = "$allow_undefined"; then if test unsupported = "$allow_undefined_flag"; then if test yes = "$build_old_libs"; then func_warning "undefined symbols not allowed in $host shared libraries; building static only" build_libtool_libs=no else func_fatal_error "can't build $host shared library unless -no-undefined is specified" fi fi else # Don't allow undefined symbols. allow_undefined_flag=$no_undefined_flag fi fi func_generate_dlsyms "$libname" "$libname" : func_append libobjs " $symfileobj" test " " = "$libobjs" && libobjs= if test relink != "$opt_mode"; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*) if test -n "$precious_files_regex"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test yes = "$build_old_libs" && test convenience != "$build_libtool_libs"; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test yes != "$hardcode_into_libs" || test yes = "$build_old_libs"; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles=$dlfiles dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles=$dlprefiles dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test yes = "$build_libtool_libs"; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test yes = "$build_libtool_need_lc"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release= versuffix= major= newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib=$potent_lib while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | $SED 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib=$potliblink;; *) potlib=`$ECHO "$potlib" | $SED 's|[^/]*$||'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib= ;; esac fi if test -n "$a_deplib"; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib=$potent_lib # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs= tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test yes = "$allow_libtool_libs_with_static_runtimes"; then for i in $predeps $postdeps; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s|$i||"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test none = "$deplibs_check_method"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test yes = "$droppeddeps"; then if test yes = "$module"; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test no = "$allow_undefined"; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs=$new_libs # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test yes = "$build_libtool_libs"; then # Remove $wl instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test yes = "$hardcode_into_libs"; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath=$finalize_rpath test relink = "$opt_mode" || rpath=$compile_rpath$rpath for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath=$finalize_shlibpath test relink = "$opt_mode" || shlibpath=$compile_shlibpath$shlibpath if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname=$1 shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname=$realname fi if test -z "$dlname"; then dlname=$soname fi lib=$output_objdir/$realname linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols=$output_objdir/$libname.uexp func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile func_dll_def_p "$export_symbols" || { # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols=$export_symbols export_symbols= always_export_symbols=yes } fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test yes = "$always_export_symbols" || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs=$IFS; IFS='~' for cmd1 in $cmds; do IFS=$save_ifs # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test yes = "$try_normal_branch" \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=$output_objdir/$output_la.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS=$save_ifs if test -n "$export_symbols_regex" && test : != "$skipped_export"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test : != "$skipped_export" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs=$tmp_deplibs if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test yes = "$compiler_needs_object" && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test yes = "$thread_safe" && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test : != "$skipped_export" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then output=$output_objdir/$output_la.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then output=$output_objdir/$output_la.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test yes = "$compiler_needs_object"; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-$k.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test -z "$objlist" || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test 1 -eq "$k"; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-$k.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-$k.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi ${skipped_export-false} && { func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi } test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs=$IFS; IFS='~' for cmd in $concat_cmds; do IFS=$save_ifs $opt_quiet || { func_quote_arg expand,pretty "$cmd" eval "func_echo $func_quote_arg_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi ${skipped_export-false} && { if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi } libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs=$IFS; IFS='~' for cmd in $cmds; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs $opt_quiet || { func_quote_arg expand,pretty "$cmd" eval "func_echo $func_quote_arg_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs # Restore the uninstalled library and exit if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test yes = "$module" || test yes = "$export_dynamic"; then # On all known operating systems, these are identical. dlname=$soname fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "'-R' is ignored for objects" test -n "$vinfo" && \ func_warning "'-version-info' is ignored for objects" test -n "$release" && \ func_warning "'-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object '$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj=$output ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # if reload_cmds runs $LD directly, get rid of -Wl from # whole_archive_flag_spec and hope we can get by with turning comma # into space. case $reload_cmds in *\$LD[\ \$]*) wl= ;; esac if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" test -n "$wl" || tmp_whole_archive_flags=`$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` reload_conv_objs=$reload_objs\ $tmp_whole_archive_flags else gentop=$output_objdir/${obj}x func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test yes = "$build_libtool_libs" || libobjs=$non_pic_objects # Create the old-style object. reload_objs=$objs$old_deplibs' '`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; /\.lib$/d; $lo2o" | $NL2SP`' '$reload_conv_objs output=$obj func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi test yes = "$build_libtool_libs" || { if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS } if test -n "$pic_flag" || test default != "$pic_mode"; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output=$libobj func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "'-version-info' is ignored for programs" test -n "$release" && \ func_warning "'-release' is ignored for programs" $preload \ && test unknown,unknown,unknown = "$dlopen_support,$dlopen_self,$dlopen_self_static" \ && func_warning "'LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test CXX = "$tagname"; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " $wl-bind_at_load" func_append finalize_command " $wl-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs=$new_libs func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath=$rpath rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath=$rpath if test -n "$libobjs" && test yes = "$build_old_libs"; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" false # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=: case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=false ;; *cygwin* | *mingw* ) test yes = "$build_libtool_libs" || wrappers_required=false ;; *) if test no = "$need_relink" || test yes != "$build_libtool_libs"; then wrappers_required=false fi ;; esac $wrappers_required || { # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command=$compile_command$compile_rpath # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.$objext"; then func_show_eval '$RM "$output_objdir/${outputname}S.$objext"' fi exit $exit_status } if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test yes = "$no_install"; then # We don't need to create a wrapper script. link_command=$compile_var$compile_command$compile_rpath # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi case $hardcode_action,$fast_install in relink,*) # Fast installation is not supported link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath func_warning "this platform does not like uninstalled shared libraries" func_warning "'$output' will be relinked during installation" ;; *,yes) link_command=$finalize_var$compile_command$finalize_rpath relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` ;; *,no) link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath ;; *,needless) link_command=$finalize_var$compile_command$finalize_rpath relink_command= ;; esac # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_arg pretty "$var_value" relink_command="$var=$func_quote_arg_result; export $var; $relink_command" fi done func_quote eval cd "`pwd`" func_quote_arg pretty,unquoted "($func_quote_result; $relink_command)" relink_command=$func_quote_arg_unquoted_result fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource=$output_path/$objdir/lt-$output_name.c cwrapper=$output_path/$output_name.exe $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host"; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do case $build_libtool_libs in convenience) oldobjs="$libobjs_save $symfileobj" addlibs=$convenience build_libtool_libs=no ;; module) oldobjs=$libobjs_save addlibs=$old_convenience build_libtool_libs=no ;; *) oldobjs="$old_deplibs $non_pic_objects" $preload && test -f "$symfileobj" \ && func_append oldobjs " $symfileobj" addlibs=$old_convenience ;; esac if test -n "$addlibs"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test yes = "$build_libtool_libs"; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase=$func_basename_result case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj"; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test -z "$oldobjs"; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test yes = "$build_old_libs" && old_library=$libname.$libext func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_arg pretty,unquoted "$var_value" relink_command="$var=$func_quote_arg_unquoted_result; export $var; $relink_command" fi done # Quote the link command for shipping. func_quote eval cd "`pwd`" relink_command="($func_quote_result; $SHELL \"$progpath\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" func_quote_arg pretty,unquoted "$relink_command" relink_command=$func_quote_arg_unquoted_result if test yes = "$hardcode_automatic"; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test yes = "$installed"; then if test -z "$install_libdir"; then break fi output=$output_objdir/${outputname}i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name=$func_basename_result func_resolve_sysroot "$deplib" eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs=$newdependency_libs newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles=$newdlprefiles else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles=$newdlprefiles fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test -n "$bindir"; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result/$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that cannot go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test no,yes = "$installed,$need_relink"; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } if test link = "$opt_mode" || test relink = "$opt_mode"; then func_mode_link ${1+"$@"} fi # func_mode_uninstall arg... func_mode_uninstall () { $debug_cmd RM=$nonopt files= rmforce=false exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic for arg do case $arg in -f) func_append RM " $arg"; rmforce=: ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir=$func_dirname_result if test . = "$dir"; then odir=$objdir else odir=$dir/$objdir fi func_basename "$file" name=$func_basename_result test uninstall = "$opt_mode" && odir=$dir # Remember odir for removal later, being careful to avoid duplicates if test clean = "$opt_mode"; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif $rmforce; then continue fi rmfiles=$file case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case $opt_mode in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" '$rmforce || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" '$rmforce || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test none != "$pic_object"; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test none != "$non_pic_object"; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test clean = "$opt_mode"; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.$objext" if test yes = "$fast_install" && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name"; then func_append rmfiles " $odir/lt-$noexename.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the $objdir's in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } if test uninstall = "$opt_mode" || test clean = "$opt_mode"; then func_mode_uninstall ${1+"$@"} fi test -z "$opt_mode" && { help=$generic_help func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode '$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # where we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: ddcutil-2.2.0/config/missing0000755000175000001440000001533614671527764011517 #! /bin/sh # Common wrapper for a few potentially missing GNU programs. scriptversion=2018-03-07.03; # UTC # Copyright (C) 1996-2021 Free Software Foundation, Inc. # Originally written by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try '$0 --help' for more information" exit 1 fi case $1 in --is-lightweight) # Used by our autoconf macros to check whether the available missing # script is modern enough. exit 0 ;; --run) # Back-compat with the calling convention used by older automake. shift ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due to PROGRAM being missing or too old. Options: -h, --help display this help and exit -v, --version output version information and exit Supported PROGRAM values: aclocal autoconf autoheader autom4te automake makeinfo bison yacc flex lex help2man Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and 'g' are ignored when checking the name. Send bug reports to ." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: unknown '$1' option" echo 1>&2 "Try '$0 --help' for more information" exit 1 ;; esac # Run the given program, remember its exit status. "$@"; st=$? # If it succeeded, we are done. test $st -eq 0 && exit 0 # Also exit now if we it failed (or wasn't found), and '--version' was # passed; such an option is passed most likely to detect whether the # program is present and works. case $2 in --version|--help) exit $st;; esac # Exit code 63 means version mismatch. This often happens when the user # tries to use an ancient version of a tool on a file that requires a # minimum version. if test $st -eq 63; then msg="probably too old" elif test $st -eq 127; then # Program was missing. msg="missing on your system" else # Program was found and executed, but failed. Give up. exit $st fi perl_URL=https://www.perl.org/ flex_URL=https://github.com/westes/flex gnu_software_URL=https://www.gnu.org/software program_details () { case $1 in aclocal|automake) echo "The '$1' program is part of the GNU Automake package:" echo "<$gnu_software_URL/automake>" echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/autoconf>" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; autoconf|autom4te|autoheader) echo "The '$1' program is part of the GNU Autoconf package:" echo "<$gnu_software_URL/autoconf/>" echo "It also requires GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; esac } give_advice () { # Normalize program name to check for. normalized_program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` printf '%s\n' "'$1' is $msg." configure_deps="'configure.ac' or m4 files included by 'configure.ac'" case $normalized_program in autoconf*) echo "You should only need it if you modified 'configure.ac'," echo "or m4 files included by it." program_details 'autoconf' ;; autoheader*) echo "You should only need it if you modified 'acconfig.h' or" echo "$configure_deps." program_details 'autoheader' ;; automake*) echo "You should only need it if you modified 'Makefile.am' or" echo "$configure_deps." program_details 'automake' ;; aclocal*) echo "You should only need it if you modified 'acinclude.m4' or" echo "$configure_deps." program_details 'aclocal' ;; autom4te*) echo "You might have modified some maintainer files that require" echo "the 'autom4te' program to be rebuilt." program_details 'autom4te' ;; bison*|yacc*) echo "You should only need it if you modified a '.y' file." echo "You may want to install the GNU Bison package:" echo "<$gnu_software_URL/bison/>" ;; lex*|flex*) echo "You should only need it if you modified a '.l' file." echo "You may want to install the Fast Lexical Analyzer package:" echo "<$flex_URL>" ;; help2man*) echo "You should only need it if you modified a dependency" \ "of a man page." echo "You may want to install the GNU Help2man package:" echo "<$gnu_software_URL/help2man/>" ;; makeinfo*) echo "You should only need it if you modified a '.texi' file, or" echo "any other file indirectly affecting the aspect of the manual." echo "You might want to install the Texinfo package:" echo "<$gnu_software_URL/texinfo/>" echo "The spurious makeinfo call might also be the consequence of" echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might" echo "want to install GNU make:" echo "<$gnu_software_URL/make/>" ;; *) echo "You might have modified some files without having the proper" echo "tools for further handling them. Check the 'README' file, it" echo "often tells you about the needed prerequisites for installing" echo "this package. You may also peek at any GNU archive site, in" echo "case some other package contains this missing '$1' program." ;; esac } give_advice "$1" | sed -e '1s/^/WARNING: /' \ -e '2,$s/^/ /' >&2 # Propagate the correct exit status (expected to be 127 for a program # not found, 63 for a program that failed due to version mismatch). exit $st # Local variables: # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: ddcutil-2.2.0/config/depcomp0000755000175000001440000005602014671527764011470 #! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2018-03-07.03; # UTC # Copyright (C) 1999-2021 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva . case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to . EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # Get the directory component of the given path, and save it in the # global variables '$dir'. Note that this directory component will # be either empty or ending with a '/' character. This is deliberate. set_dir_from () { case $1 in */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;; *) dir=;; esac } # Get the suffix-stripped basename of the given path, and save it the # global variable '$base'. set_base_from () { base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'` } # If no dependency file was actually created by the compiler invocation, # we still have to create a dummy depfile, to avoid errors with the # Makefile "include basename.Plo" scheme. make_dummy_depfile () { echo "#dummy" > "$depfile" } # Factor out some common post-processing of the generated depfile. # Requires the auxiliary global variable '$tmpdepfile' to be set. aix_post_process_depfile () { # If the compiler actually managed to produce a dependency file, # post-process it. if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependency.h'. # Do two passes, one to just change these to # $object: dependency.h # and one to simply output # dependency.h: # which is needed to avoid the deleted-header problem. { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile" sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile" } > "$depfile" rm -f "$tmpdepfile" else make_dummy_depfile fi } # A tabulation character. tab=' ' # A newline character. nl=' ' # Character ranges might be problematic outside the C locale. # These definitions help. upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ lower=abcdefghijklmnopqrstuvwxyz digits=0123456789 alpha=${upper}${lower} if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Avoid interferences from the environment. gccflag= dashmflag= # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## Note that this doesn't just cater to obsosete pre-3.x GCC compilers. ## but also to in-use compilers like IMB xlc/xlC and the HP C compiler. ## (see the conditional assignment to $gccflag above). ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). Also, it might not be ## supported by the other compilers which use the 'gcc' depmode. ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The second -e expression handles DOS-style file names with drive # letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \ | tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done aix_post_process_depfile ;; tcc) # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26 # FIXME: That version still under development at the moment of writing. # Make that this statement remains true also for stable, released # versions. # It will wrap lines (doesn't matter whether long or short) with a # trailing '\', as in: # # foo.o : \ # foo.c \ # foo.h \ # # It will put a trailing '\' even on the last line, and will use leading # spaces rather than leading tabs (at least since its commit 0394caf7 # "Emit spaces for -MD"). "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'. # We have to change lines of the first kind to '$object: \'. sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile" # And for each line of the second kind, we have to emit a 'dep.h:' # dummy dependency, to avoid the deleted-header problem. sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; ## The order of this option in the case statement is important, since the ## shell code in configure will try each of these formats in the order ## listed in this file. A plain '-MD' option would be understood by many ## compilers, so we must ensure this comes after the gcc and icc options. pgcc) # Portland's C compiler understands '-MD'. # Will always output deps to 'file.d' where file is the root name of the # source file under compilation, even if file resides in a subdirectory. # The object file name does not affect the name of the '.d' file. # pgcc 10.2 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\' : # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... set_dir_from "$object" # Use the source, not the object, to determine the base name, since # that's sadly what pgcc will do too. set_base_from "$source" tmpdepfile=$base.d # For projects that build the same source file twice into different object # files, the pgcc approach of using the *source* file root name can cause # problems in parallel builds. Use a locking strategy to avoid stomping on # the same $tmpdepfile. lockdir=$base.d-lock trap " echo '$0: caught signal, cleaning up...' >&2 rmdir '$lockdir' exit 1 " 1 2 13 15 numtries=100 i=$numtries while test $i -gt 0; do # mkdir is a portable test-and-set. if mkdir "$lockdir" 2>/dev/null; then # This process acquired the lock. "$@" -MD stat=$? # Release the lock. rmdir "$lockdir" break else # If the lock is being held by a different process, wait # until the winning process is done or we timeout. while test -d "$lockdir" && test $i -gt 0; do sleep 1 i=`expr $i - 1` done fi i=`expr $i - 1` done trap - 1 2 13 15 if test $i -le 0; then echo "$0: failed to acquire lock after $numtries attempts" >&2 echo "$0: check lockdir '$lockdir'" >&2 exit 1 fi if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form `foo.o: dependent.h', # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. # Do two passes, one to just change these to # `$object: dependent.h' and one to simply `dependent.h:'. sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this invocation # correctly. Breaking it into two sed invocations is a workaround. sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then # Libtool generates 2 separate objects for the 2 libraries. These # two compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir$base.o.d # libtool 1.5 tmpdepfile2=$dir.libs/$base.o.d # Likewise. tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d "$@" -MD fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done # Same post-processing that is required for AIX mode. aix_post_process_depfile ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" echo >> "$depfile" # make sure the fragment doesn't end with a backslash rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this sed invocation # correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process the last invocation # correctly. Breaking it into two sed invocations is a workaround. sed '1,2d' "$tmpdepfile" \ | tr ' ' "$nl" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E \ | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: ddcutil-2.2.0/config/py-compile0000755000175000001440000001216414032524263012076 #!/bin/sh # py-compile - Compile a Python program scriptversion=2020-02-19.23; # UTC # Copyright (C) 2000-2020 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . if [ -z "$PYTHON" ]; then PYTHON=python fi me=py-compile usage_error () { echo "$me: $*" >&2 echo "Try '$me --help' for more information." >&2 exit 1 } basedir= destdir= while test $# -ne 0; do case "$1" in --basedir) if test $# -lt 2; then usage_error "option '--basedir' requires an argument" else basedir=$2 fi shift ;; --destdir) if test $# -lt 2; then usage_error "option '--destdir' requires an argument" else destdir=$2 fi shift ;; -h|--help) cat <<\EOF Usage: py-compile [--help] [--version] [--basedir DIR] [--destdir DIR] FILES..." Byte compile some python scripts FILES. Use --destdir to specify any leading directory path to the FILES that you don't want to include in the byte compiled file. Specify --basedir for any additional path information you do want to be shown in the byte compiled file. Example: py-compile --destdir /tmp/pkg-root --basedir /usr/share/test test.py test2.py Report bugs to . EOF exit $? ;; -v|--version) echo "$me $scriptversion" exit $? ;; --) shift break ;; -*) usage_error "unrecognized option '$1'" ;; *) break ;; esac shift done files=$* if test -z "$files"; then usage_error "no files given" fi # if basedir was given, then it should be prepended to filenames before # byte compilation. if [ -z "$basedir" ]; then pathtrans="path = file" else pathtrans="path = os.path.join('$basedir', file)" fi # if destdir was given, then it needs to be prepended to the filename to # byte compile but not go into the compiled file. if [ -z "$destdir" ]; then filetrans="filepath = path" else filetrans="filepath = os.path.normpath('$destdir' + os.sep + path)" fi python_major=$($PYTHON -V 2>&1 | sed -e 's/.* //;s/\..*$//;1q') if test -z "$python_major"; then echo "$me: could not determine $PYTHON major version, guessing 3" >&2 python_major=3 fi # The old way to import libraries was deprecated. if test "$python_major" -le 2; then import_lib=imp import_test="hasattr(imp, 'get_tag')" import_call=imp.cache_from_source import_arg2=', False' # needed in one call and not the other else import_lib=importlib import_test="hasattr(sys.implementation, 'cache_tag')" import_call=importlib.util.cache_from_source import_arg2= fi $PYTHON -c " import sys, os, py_compile, $import_lib files = '''$files''' sys.stdout.write('Byte-compiling python modules...\n') for file in files.split(): $pathtrans $filetrans if not os.path.exists(filepath) or not (len(filepath) >= 3 and filepath[-3:] == '.py'): continue sys.stdout.write(file) sys.stdout.flush() if $import_test: py_compile.compile(filepath, $import_call(filepath), path) else: py_compile.compile(filepath, filepath + 'c', path) sys.stdout.write('\n')" || exit $? # this will fail for python < 1.5, but that doesn't matter ... $PYTHON -O -c " import sys, os, py_compile, $import_lib # pypy does not use .pyo optimization if hasattr(sys, 'pypy_translation_info'): sys.exit(0) files = '''$files''' sys.stdout.write('Byte-compiling python modules (optimized versions) ...\n') for file in files.split(): $pathtrans $filetrans if not os.path.exists(filepath) or not (len(filepath) >= 3 and filepath[-3:] == '.py'): continue sys.stdout.write(file) sys.stdout.flush() if $import_test: py_compile.compile(filepath, $import_call(filepath$import_arg2), path) else: py_compile.compile(filepath, filepath + 'o', path) sys.stdout.write('\n')" 2>/dev/null || : # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: ddcutil-2.2.0/m4/0000775000175000001440000000000014754576330007240 5ddcutil-2.2.0/m4/ax_prog_doxygen.m40000677000175000001440000005004213032550072012602 # =========================================================================== # http://www.gnu.org/software/autoconf-archive/ax_prog_doxygen.html # =========================================================================== # # SYNOPSIS # # DX_INIT_DOXYGEN(PROJECT-NAME, [DOXYFILE-PATH], [OUTPUT-DIR], ...) # DX_DOXYGEN_FEATURE(ON|OFF) # DX_DOT_FEATURE(ON|OFF) # DX_HTML_FEATURE(ON|OFF) # DX_CHM_FEATURE(ON|OFF) # DX_CHI_FEATURE(ON|OFF) # DX_MAN_FEATURE(ON|OFF) # DX_RTF_FEATURE(ON|OFF) # DX_XML_FEATURE(ON|OFF) # DX_PDF_FEATURE(ON|OFF) # DX_PS_FEATURE(ON|OFF) # # DESCRIPTION # # The DX_*_FEATURE macros control the default setting for the given # Doxygen feature. Supported features are 'DOXYGEN' itself, 'DOT' for # generating graphics, 'HTML' for plain HTML, 'CHM' for compressed HTML # help (for MS users), 'CHI' for generating a seperate .chi file by the # .chm file, and 'MAN', 'RTF', 'XML', 'PDF' and 'PS' for the appropriate # output formats. The environment variable DOXYGEN_PAPER_SIZE may be # specified to override the default 'a4wide' paper size. # # By default, HTML, PDF and PS documentation is generated as this seems to # be the most popular and portable combination. MAN pages created by # Doxygen are usually problematic, though by picking an appropriate subset # and doing some massaging they might be better than nothing. CHM and RTF # are specific for MS (note that you can't generate both HTML and CHM at # the same time). The XML is rather useless unless you apply specialized # post-processing to it. # # The macros mainly control the default state of the feature. The use can # override the default by specifying --enable or --disable. The macros # ensure that contradictory flags are not given (e.g., # --enable-doxygen-html and --enable-doxygen-chm, # --enable-doxygen-anything with --disable-doxygen, etc.) Finally, each # feature will be automatically disabled (with a warning) if the required # programs are missing. # # Once all the feature defaults have been specified, call DX_INIT_DOXYGEN # with the following parameters: a one-word name for the project for use # as a filename base etc., an optional configuration file name (the # default is '$(srcdir)/Doxyfile', the same as Doxygen's default), and an # optional output directory name (the default is 'doxygen-doc'). To run # doxygen multiple times for different configuration files and output # directories provide more parameters: the second, forth, sixth, etc # parameter are configuration file names and the third, fifth, seventh, # etc parameter are output directories. No checking is done to catch # duplicates. # # Automake Support # # The DX_RULES substitution can be used to add all needed rules to the # Makefile. Note that this is a substitution without being a variable: # only the @DX_RULES@ syntax will work. # # The provided targets are: # # doxygen-doc: Generate all doxygen documentation. # # doxygen-run: Run doxygen, which will generate some of the # documentation (HTML, CHM, CHI, MAN, RTF, XML) # but will not do the post processing required # for the rest of it (PS, PDF). # # doxygen-ps: Generate doxygen PostScript documentation. # # doxygen-pdf: Generate doxygen PDF documentation. # # Note that by default these are not integrated into the automake targets. # If doxygen is used to generate man pages, you can achieve this # integration by setting man3_MANS to the list of man pages generated and # then adding the dependency: # # $(man3_MANS): doxygen-doc # # This will cause make to run doxygen and generate all the documentation. # # The following variable is intended for use in Makefile.am: # # DX_CLEANFILES = everything to clean. # # Then add this variable to MOSTLYCLEANFILES. # # LICENSE # # Copyright (c) 2009 Oren Ben-Kiki # Copyright (c) 2015 Olaf Mandel # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 20 ## ----------## ## Defaults. ## ## ----------## DX_ENV="" AC_DEFUN([DX_FEATURE_doc], ON) AC_DEFUN([DX_FEATURE_dot], OFF) AC_DEFUN([DX_FEATURE_man], OFF) AC_DEFUN([DX_FEATURE_html], ON) AC_DEFUN([DX_FEATURE_chm], OFF) AC_DEFUN([DX_FEATURE_chi], OFF) AC_DEFUN([DX_FEATURE_rtf], OFF) AC_DEFUN([DX_FEATURE_xml], OFF) AC_DEFUN([DX_FEATURE_pdf], ON) AC_DEFUN([DX_FEATURE_ps], ON) ## --------------- ## ## Private macros. ## ## --------------- ## # DX_ENV_APPEND(VARIABLE, VALUE) # ------------------------------ # Append VARIABLE="VALUE" to DX_ENV for invoking doxygen and add it # as a substitution (but not a Makefile variable). The substitution # is skipped if the variable name is VERSION. AC_DEFUN([DX_ENV_APPEND], [AC_SUBST([DX_ENV], ["$DX_ENV $1='$2'"])dnl m4_if([$1], [VERSION], [], [AC_SUBST([$1], [$2])dnl AM_SUBST_NOTMAKE([$1])])dnl ]) # DX_DIRNAME_EXPR # --------------- # Expand into a shell expression prints the directory part of a path. AC_DEFUN([DX_DIRNAME_EXPR], [[expr ".$1" : '\(\.\)[^/]*$' \| "x$1" : 'x\(.*\)/[^/]*$']]) # DX_IF_FEATURE(FEATURE, IF-ON, IF-OFF) # ------------------------------------- # Expands according to the M4 (static) status of the feature. AC_DEFUN([DX_IF_FEATURE], [ifelse(DX_FEATURE_$1, ON, [$2], [$3])]) # DX_REQUIRE_PROG(VARIABLE, PROGRAM) # ---------------------------------- # Require the specified program to be found for the DX_CURRENT_FEATURE to work. AC_DEFUN([DX_REQUIRE_PROG], [ AC_PATH_TOOL([$1], [$2]) if test "$DX_FLAG_[]DX_CURRENT_FEATURE$$1" = 1; then AC_MSG_WARN([$2 not found - will not DX_CURRENT_DESCRIPTION]) AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0) fi ]) # DX_TEST_FEATURE(FEATURE) # ------------------------ # Expand to a shell expression testing whether the feature is active. AC_DEFUN([DX_TEST_FEATURE], [test "$DX_FLAG_$1" = 1]) # DX_CHECK_DEPEND(REQUIRED_FEATURE, REQUIRED_STATE) # ------------------------------------------------- # Verify that a required features has the right state before trying to turn on # the DX_CURRENT_FEATURE. AC_DEFUN([DX_CHECK_DEPEND], [ test "$DX_FLAG_$1" = "$2" \ || AC_MSG_ERROR([doxygen-DX_CURRENT_FEATURE ifelse([$2], 1, requires, contradicts) doxygen-DX_CURRENT_FEATURE]) ]) # DX_CLEAR_DEPEND(FEATURE, REQUIRED_FEATURE, REQUIRED_STATE) # ---------------------------------------------------------- # Turn off the DX_CURRENT_FEATURE if the required feature is off. AC_DEFUN([DX_CLEAR_DEPEND], [ test "$DX_FLAG_$1" = "$2" || AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0) ]) # DX_FEATURE_ARG(FEATURE, DESCRIPTION, # CHECK_DEPEND, CLEAR_DEPEND, # REQUIRE, DO-IF-ON, DO-IF-OFF) # -------------------------------------------- # Parse the command-line option controlling a feature. CHECK_DEPEND is called # if the user explicitly turns the feature on (and invokes DX_CHECK_DEPEND), # otherwise CLEAR_DEPEND is called to turn off the default state if a required # feature is disabled (using DX_CLEAR_DEPEND). REQUIRE performs additional # requirement tests (DX_REQUIRE_PROG). Finally, an automake flag is set and # DO-IF-ON or DO-IF-OFF are called according to the final state of the feature. AC_DEFUN([DX_ARG_ABLE], [ AC_DEFUN([DX_CURRENT_FEATURE], [$1]) AC_DEFUN([DX_CURRENT_DESCRIPTION], [$2]) AC_ARG_ENABLE(doxygen-$1, [AS_HELP_STRING(DX_IF_FEATURE([$1], [--disable-doxygen-$1], [--enable-doxygen-$1]), DX_IF_FEATURE([$1], [don't $2], [$2]))], [ case "$enableval" in #( y|Y|yes|Yes|YES) AC_SUBST([DX_FLAG_$1], 1) $3 ;; #( n|N|no|No|NO) AC_SUBST([DX_FLAG_$1], 0) ;; #( *) AC_MSG_ERROR([invalid value '$enableval' given to doxygen-$1]) ;; esac ], [ AC_SUBST([DX_FLAG_$1], [DX_IF_FEATURE([$1], 1, 0)]) $4 ]) if DX_TEST_FEATURE([$1]); then $5 : fi if DX_TEST_FEATURE([$1]); then $6 : else $7 : fi ]) ## -------------- ## ## Public macros. ## ## -------------- ## # DX_XXX_FEATURE(DEFAULT_STATE) # ----------------------------- AC_DEFUN([DX_DOXYGEN_FEATURE], [AC_DEFUN([DX_FEATURE_doc], [$1])]) AC_DEFUN([DX_DOT_FEATURE], [AC_DEFUN([DX_FEATURE_dot], [$1])]) AC_DEFUN([DX_MAN_FEATURE], [AC_DEFUN([DX_FEATURE_man], [$1])]) AC_DEFUN([DX_HTML_FEATURE], [AC_DEFUN([DX_FEATURE_html], [$1])]) AC_DEFUN([DX_CHM_FEATURE], [AC_DEFUN([DX_FEATURE_chm], [$1])]) AC_DEFUN([DX_CHI_FEATURE], [AC_DEFUN([DX_FEATURE_chi], [$1])]) AC_DEFUN([DX_RTF_FEATURE], [AC_DEFUN([DX_FEATURE_rtf], [$1])]) AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])]) AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])]) AC_DEFUN([DX_PDF_FEATURE], [AC_DEFUN([DX_FEATURE_pdf], [$1])]) AC_DEFUN([DX_PS_FEATURE], [AC_DEFUN([DX_FEATURE_ps], [$1])]) # DX_INIT_DOXYGEN(PROJECT, [CONFIG-FILE], [OUTPUT-DOC-DIR], ...) # -------------------------------------------------------------- # PROJECT also serves as the base name for the documentation files. # The default CONFIG-FILE is "$(srcdir)/Doxyfile" and OUTPUT-DOC-DIR is # "doxygen-doc". # More arguments are interpreted as interleaved CONFIG-FILE and # OUTPUT-DOC-DIR values. AC_DEFUN([DX_INIT_DOXYGEN], [ # Files: AC_SUBST([DX_PROJECT], [$1]) AC_SUBST([DX_CONFIG], ['ifelse([$2], [], [$(srcdir)/Doxyfile], [$2])']) AC_SUBST([DX_DOCDIR], ['ifelse([$3], [], [doxygen-doc], [$3])']) m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 4, m4_count($@), 2, [AC_SUBST([DX_CONFIG]m4_eval(DX_i[/2]), 'm4_default_nblank_quoted(m4_argn(DX_i, $@), [$(srcdir)/Doxyfile])')])])dnl m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 5, m4_count($@,), 2, [AC_SUBST([DX_DOCDIR]m4_eval([(]DX_i[-1)/2]), 'm4_default_nblank_quoted(m4_argn(DX_i, $@), [doxygen-doc])')])])dnl m4_define([DX_loop], m4_dquote(m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 4, m4_count($@), 2, [, m4_eval(DX_i[/2])])], [])))dnl # Environment variables used inside doxygen.cfg: DX_ENV_APPEND(SRCDIR, $srcdir) DX_ENV_APPEND(PROJECT, $DX_PROJECT) DX_ENV_APPEND(VERSION, $PACKAGE_VERSION) # Doxygen itself: DX_ARG_ABLE(doc, [generate any doxygen documentation], [], [], [DX_REQUIRE_PROG([DX_DOXYGEN], doxygen) DX_REQUIRE_PROG([DX_PERL], perl)], [DX_ENV_APPEND(PERL_PATH, $DX_PERL)]) # Dot for graphics: DX_ARG_ABLE(dot, [generate graphics for doxygen documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_DOT], dot)], [DX_ENV_APPEND(HAVE_DOT, YES) DX_ENV_APPEND(DOT_PATH, [`DX_DIRNAME_EXPR($DX_DOT)`])], [DX_ENV_APPEND(HAVE_DOT, NO)]) # Man pages generation: DX_ARG_ABLE(man, [generate doxygen manual pages], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_MAN, YES)], [DX_ENV_APPEND(GENERATE_MAN, NO)]) # RTF file generation: DX_ARG_ABLE(rtf, [generate doxygen RTF documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_RTF, YES)], [DX_ENV_APPEND(GENERATE_RTF, NO)]) # XML file generation: DX_ARG_ABLE(xml, [generate doxygen XML documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_XML, YES)], [DX_ENV_APPEND(GENERATE_XML, NO)]) # (Compressed) HTML help generation: DX_ARG_ABLE(chm, [generate doxygen compressed HTML help documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_HHC], hhc)], [DX_ENV_APPEND(HHC_PATH, $DX_HHC) DX_ENV_APPEND(GENERATE_HTML, YES) DX_ENV_APPEND(GENERATE_HTMLHELP, YES)], [DX_ENV_APPEND(GENERATE_HTMLHELP, NO)]) # Seperate CHI file generation. DX_ARG_ABLE(chi, [generate doxygen seperate compressed HTML help index file], [DX_CHECK_DEPEND(chm, 1)], [DX_CLEAR_DEPEND(chm, 1)], [], [DX_ENV_APPEND(GENERATE_CHI, YES)], [DX_ENV_APPEND(GENERATE_CHI, NO)]) # Plain HTML pages generation: DX_ARG_ABLE(html, [generate doxygen plain HTML documentation], [DX_CHECK_DEPEND(doc, 1) DX_CHECK_DEPEND(chm, 0)], [DX_CLEAR_DEPEND(doc, 1) DX_CLEAR_DEPEND(chm, 0)], [], [DX_ENV_APPEND(GENERATE_HTML, YES)], [DX_TEST_FEATURE(chm) || DX_ENV_APPEND(GENERATE_HTML, NO)]) # PostScript file generation: DX_ARG_ABLE(ps, [generate doxygen PostScript documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_LATEX], latex) DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex) DX_REQUIRE_PROG([DX_DVIPS], dvips) DX_REQUIRE_PROG([DX_EGREP], egrep)]) # PDF file generation: DX_ARG_ABLE(pdf, [generate doxygen PDF documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_PDFLATEX], pdflatex) DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex) DX_REQUIRE_PROG([DX_EGREP], egrep)]) # LaTeX generation for PS and/or PDF: if DX_TEST_FEATURE(ps) || DX_TEST_FEATURE(pdf); then DX_ENV_APPEND(GENERATE_LATEX, YES) else DX_ENV_APPEND(GENERATE_LATEX, NO) fi # Paper size for PS and/or PDF: AC_ARG_VAR(DOXYGEN_PAPER_SIZE, [a4wide (default), a4, letter, legal or executive]) case "$DOXYGEN_PAPER_SIZE" in #( "") AC_SUBST(DOXYGEN_PAPER_SIZE, "") ;; #( a4wide|a4|letter|legal|executive) DX_ENV_APPEND(PAPER_SIZE, $DOXYGEN_PAPER_SIZE) ;; #( *) AC_MSG_ERROR([unknown DOXYGEN_PAPER_SIZE='$DOXYGEN_PAPER_SIZE']) ;; esac # Rules: AS_IF([[test $DX_FLAG_html -eq 1]], [[DX_SNIPPET_html="## ------------------------------- ## ## Rules specific for HTML output. ## ## ------------------------------- ## DX_CLEAN_HTML = \$(DX_DOCDIR)/html]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/html]])[ "]], [[DX_SNIPPET_html=""]]) AS_IF([[test $DX_FLAG_chi -eq 1]], [[DX_SNIPPET_chi=" DX_CLEAN_CHI = \$(DX_DOCDIR)/\$(PACKAGE).chi]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).chi]])["]], [[DX_SNIPPET_chi=""]]) AS_IF([[test $DX_FLAG_chm -eq 1]], [[DX_SNIPPET_chm="## ------------------------------ ## ## Rules specific for CHM output. ## ## ------------------------------ ## DX_CLEAN_CHM = \$(DX_DOCDIR)/chm]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/chm]])[\ ${DX_SNIPPET_chi} "]], [[DX_SNIPPET_chm=""]]) AS_IF([[test $DX_FLAG_man -eq 1]], [[DX_SNIPPET_man="## ------------------------------ ## ## Rules specific for MAN output. ## ## ------------------------------ ## DX_CLEAN_MAN = \$(DX_DOCDIR)/man]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/man]])[ "]], [[DX_SNIPPET_man=""]]) AS_IF([[test $DX_FLAG_rtf -eq 1]], [[DX_SNIPPET_rtf="## ------------------------------ ## ## Rules specific for RTF output. ## ## ------------------------------ ## DX_CLEAN_RTF = \$(DX_DOCDIR)/rtf]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/rtf]])[ "]], [[DX_SNIPPET_rtf=""]]) AS_IF([[test $DX_FLAG_xml -eq 1]], [[DX_SNIPPET_xml="## ------------------------------ ## ## Rules specific for XML output. ## ## ------------------------------ ## DX_CLEAN_XML = \$(DX_DOCDIR)/xml]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/xml]])[ "]], [[DX_SNIPPET_xml=""]]) AS_IF([[test $DX_FLAG_ps -eq 1]], [[DX_SNIPPET_ps="## ----------------------------- ## ## Rules specific for PS output. ## ## ----------------------------- ## DX_CLEAN_PS = \$(DX_DOCDIR)/\$(PACKAGE).ps]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps]])[ DX_PS_GOAL = doxygen-ps doxygen-ps: \$(DX_CLEAN_PS) ]m4_foreach([DX_i], [DX_loop], [[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\ \$(DX_LATEX) refman.tex; \\ \$(DX_MAKEINDEX) refman.idx; \\ \$(DX_LATEX) refman.tex; \\ countdown=5; \\ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\ refman.log > /dev/null 2>&1 \\ && test \$\$countdown -gt 0; do \\ \$(DX_LATEX) refman.tex; \\ countdown=\`expr \$\$countdown - 1\`; \\ done; \\ \$(DX_DVIPS) -o ../\$(PACKAGE).ps refman.dvi ]])["]], [[DX_SNIPPET_ps=""]]) AS_IF([[test $DX_FLAG_pdf -eq 1]], [[DX_SNIPPET_pdf="## ------------------------------ ## ## Rules specific for PDF output. ## ## ------------------------------ ## DX_CLEAN_PDF = \$(DX_DOCDIR)/\$(PACKAGE).pdf]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf]])[ DX_PDF_GOAL = doxygen-pdf doxygen-pdf: \$(DX_CLEAN_PDF) ]m4_foreach([DX_i], [DX_loop], [[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\ \$(DX_PDFLATEX) refman.tex; \\ \$(DX_MAKEINDEX) refman.idx; \\ \$(DX_PDFLATEX) refman.tex; \\ countdown=5; \\ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\ refman.log > /dev/null 2>&1 \\ && test \$\$countdown -gt 0; do \\ \$(DX_PDFLATEX) refman.tex; \\ countdown=\`expr \$\$countdown - 1\`; \\ done; \\ mv refman.pdf ../\$(PACKAGE).pdf ]])["]], [[DX_SNIPPET_pdf=""]]) AS_IF([[test $DX_FLAG_ps -eq 1 -o $DX_FLAG_pdf -eq 1]], [[DX_SNIPPET_latex="## ------------------------------------------------- ## ## Rules specific for LaTeX (shared for PS and PDF). ## ## ------------------------------------------------- ## DX_V_LATEX = \$(_DX_v_LATEX_\$(V)) _DX_v_LATEX_ = \$(_DX_v_LATEX_\$(AM_DEFAULT_VERBOSITY)) _DX_v_LATEX_0 = @echo \" LATEX \" \$][@; DX_CLEAN_LATEX = \$(DX_DOCDIR)/latex]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/latex]])[ "]], [[DX_SNIPPET_latex=""]]) AS_IF([[test $DX_FLAG_doc -eq 1]], [[DX_SNIPPET_doc="## --------------------------------- ## ## Format-independent Doxygen rules. ## ## --------------------------------- ## ${DX_SNIPPET_html}\ ${DX_SNIPPET_chm}\ ${DX_SNIPPET_man}\ ${DX_SNIPPET_rtf}\ ${DX_SNIPPET_xml}\ ${DX_SNIPPET_ps}\ ${DX_SNIPPET_pdf}\ ${DX_SNIPPET_latex}\ DX_V_DXGEN = \$(_DX_v_DXGEN_\$(V)) _DX_v_DXGEN_ = \$(_DX_v_DXGEN_\$(AM_DEFAULT_VERBOSITY)) _DX_v_DXGEN_0 = @echo \" DXGEN \" \$<; .PHONY: doxygen-run doxygen-doc \$(DX_PS_GOAL) \$(DX_PDF_GOAL) .INTERMEDIATE: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL) doxygen-run:]m4_foreach([DX_i], [DX_loop], [[ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag]])[ doxygen-doc: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL) ]m4_foreach([DX_i], [DX_loop], [[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag: \$(DX_CONFIG]DX_i[) \$(pkginclude_HEADERS) \$(A""M_V_at)rm -rf \$(DX_DOCDIR]DX_i[) \$(DX_V_DXGEN)\$(DX_ENV) DOCDIR=\$(DX_DOCDIR]DX_i[) \$(DX_DOXYGEN) \$(DX_CONFIG]DX_i[) \$(A""M_V_at)echo Timestamp >\$][@ ]])dnl [DX_CLEANFILES = \\] m4_foreach([DX_i], [DX_loop], [[ \$(DX_DOCDIR]DX_i[)/doxygen_sqlite3.db \\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \\ ]])dnl [ -r \\ \$(DX_CLEAN_HTML) \\ \$(DX_CLEAN_CHM) \\ \$(DX_CLEAN_CHI) \\ \$(DX_CLEAN_MAN) \\ \$(DX_CLEAN_RTF) \\ \$(DX_CLEAN_XML) \\ \$(DX_CLEAN_PS) \\ \$(DX_CLEAN_PDF) \\ \$(DX_CLEAN_LATEX)"]], [[DX_SNIPPET_doc=""]]) AC_SUBST([DX_RULES], ["${DX_SNIPPET_doc}"])dnl AM_SUBST_NOTMAKE([DX_RULES]) #For debugging: #echo DX_FLAG_doc=$DX_FLAG_doc #echo DX_FLAG_dot=$DX_FLAG_dot #echo DX_FLAG_man=$DX_FLAG_man #echo DX_FLAG_html=$DX_FLAG_html #echo DX_FLAG_chm=$DX_FLAG_chm #echo DX_FLAG_chi=$DX_FLAG_chi #echo DX_FLAG_rtf=$DX_FLAG_rtf #echo DX_FLAG_xml=$DX_FLAG_xml #echo DX_FLAG_pdf=$DX_FLAG_pdf #echo DX_FLAG_ps=$DX_FLAG_ps #echo DX_ENV=$DX_ENV ]) ddcutil-2.2.0/m4/flm_prog_try_doxygen.m40000677000175000001440000000212313015564437013656 # FLM_PROG_TRY_DOXYGEN(["quiet"]) # ------------------------------ # FLM_PROG_TRY_DOXYGEN tests for an existing doxygen source # documentation program. It sets or uses the environment # variable DOXYGEN. # # If no arguments are given to this macro, and no doxygen # program can be found, it prints a warning message to STDOUT # and to the config.log file. If the "quiet" argument is passed, # then only the normal "check" line is displayed. Any other # argument is considered by autoconf to be an error at expansion # time. # # Makes the DOXYGEN variable precious to Autoconf. You can # use the DOXYGEN variable in your Makefile.in files with # @DOXYGEN@. # # Author: John Calcote # Modified: 2009-08-30 # License: AllPermissive # AC_DEFUN([FLM_PROG_TRY_DOXYGEN], [AC_ARG_VAR([DOXYGEN], [Doxygen source doc generation program])dnl AC_CHECK_PROGS([DOXYGEN], [doxygen]) m4_if([$1],, [if test -z "$DOXYGEN"; then AC_MSG_WARN([doxygen not found - continuing without Doxygen support]) fi], [$1], [quiet],, [m4_fatal([Invalid option '$1' in $0])]) ])# FLM_PROG_TRY_DOXYGEN ddcutil-2.2.0/m4/libtool.m40000644000175000001440000112776414671527761011110 # libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # # Copyright (C) 1996-2001, 2003-2019, 2021-2022 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. m4_define([_LT_COPYING], [dnl # Copyright (C) 2014 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program or library that is built # using GNU Libtool, you may include this file under the same # distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . ]) # serial 59 LT_INIT # LT_PREREQ(VERSION) # ------------------ # Complain and exit if this libtool version is less that VERSION. m4_defun([LT_PREREQ], [m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, [m4_default([$3], [m4_fatal([Libtool version $1 or higher is required], 63)])], [$2])]) # _LT_CHECK_BUILDDIR # ------------------ # Complain if the absolute build directory name contains unusual characters m4_defun([_LT_CHECK_BUILDDIR], [case `pwd` in *\ * | *\ *) AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; esac ]) # LT_INIT([OPTIONS]) # ------------------ AC_DEFUN([LT_INIT], [AC_PREREQ([2.62])dnl We use AC_PATH_PROGS_FEATURE_CHECK AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl AC_BEFORE([$0], [LTDL_INIT])dnl m4_require([_LT_CHECK_BUILDDIR])dnl dnl Autoconf doesn't catch unexpanded LT_ macros by default: m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 dnl unless we require an AC_DEFUNed macro: AC_REQUIRE([LTOPTIONS_VERSION])dnl AC_REQUIRE([LTSUGAR_VERSION])dnl AC_REQUIRE([LTVERSION_VERSION])dnl AC_REQUIRE([LTOBSOLETE_VERSION])dnl m4_require([_LT_PROG_LTMAIN])dnl _LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) # This can be used to rebuild libtool when needed LIBTOOL_DEPS=$ltmain # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' AC_SUBST(LIBTOOL)dnl _LT_SETUP # Only expand once: m4_define([LT_INIT]) ])# LT_INIT # Old names: AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PROG_LIBTOOL], []) dnl AC_DEFUN([AM_PROG_LIBTOOL], []) # _LT_PREPARE_CC_BASENAME # ----------------------- m4_defun([_LT_PREPARE_CC_BASENAME], [ # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. func_cc_basename () { for cc_temp in @S|@*""; do case $cc_temp in compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; \-*) ;; *) break;; esac done func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` } ])# _LT_PREPARE_CC_BASENAME # _LT_CC_BASENAME(CC) # ------------------- # It would be clearer to call AC_REQUIREs from _LT_PREPARE_CC_BASENAME, # but that macro is also expanded into generated libtool script, which # arranges for $SED and $ECHO to be set by different means. m4_defun([_LT_CC_BASENAME], [m4_require([_LT_PREPARE_CC_BASENAME])dnl AC_REQUIRE([_LT_DECL_SED])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl func_cc_basename $1 cc_basename=$func_cc_basename_result ]) # _LT_FILEUTILS_DEFAULTS # ---------------------- # It is okay to use these file commands and assume they have been set # sensibly after 'm4_require([_LT_FILEUTILS_DEFAULTS])'. m4_defun([_LT_FILEUTILS_DEFAULTS], [: ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} ])# _LT_FILEUTILS_DEFAULTS # _LT_SETUP # --------- m4_defun([_LT_SETUP], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl _LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl dnl _LT_DECL([], [host_alias], [0], [The host system])dnl _LT_DECL([], [host], [0])dnl _LT_DECL([], [host_os], [0])dnl dnl _LT_DECL([], [build_alias], [0], [The build system])dnl _LT_DECL([], [build], [0])dnl _LT_DECL([], [build_os], [0])dnl dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl dnl AC_REQUIRE([AC_PROG_LN_S])dnl test -z "$LN_S" && LN_S="ln -s" _LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl dnl AC_REQUIRE([LT_CMD_MAX_LEN])dnl _LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl _LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl m4_require([_LT_CMD_RELOAD])dnl m4_require([_LT_DECL_FILECMD])dnl m4_require([_LT_CHECK_MAGIC_METHOD])dnl m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl m4_require([_LT_CMD_OLD_ARCHIVE])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_WITH_SYSROOT])dnl m4_require([_LT_CMD_TRUNCATE])dnl _LT_CONFIG_LIBTOOL_INIT([ # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi ]) if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi _LT_CHECK_OBJDIR m4_require([_LT_TAG_COMPILER])dnl case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a '.a' archive for static linking (except MSVC and # ICC, which need '.lib'). libext=a with_gnu_ld=$lt_cv_prog_gnu_ld old_CC=$CC old_CFLAGS=$CFLAGS # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o _LT_CC_BASENAME([$compiler]) # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then _LT_PATH_MAGIC fi ;; esac # Use C for the default configuration in the libtool script LT_SUPPORTED_TAG([CC]) _LT_LANG_C_CONFIG _LT_LANG_DEFAULT_CONFIG _LT_CONFIG_COMMANDS ])# _LT_SETUP # _LT_PREPARE_SED_QUOTE_VARS # -------------------------- # Define a few sed substitution that help us do robust quoting. m4_defun([_LT_PREPARE_SED_QUOTE_VARS], [# Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\([["`\\]]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ]) # _LT_PROG_LTMAIN # --------------- # Note that this code is called both from 'configure', and 'config.status' # now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, # 'config.status' has no value for ac_aux_dir unless we are using Automake, # so we pass a copy along to make sure it has a sensible value anyway. m4_defun([_LT_PROG_LTMAIN], [m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl _LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) ltmain=$ac_aux_dir/ltmain.sh ])# _LT_PROG_LTMAIN ## ------------------------------------- ## ## Accumulate code for creating libtool. ## ## ------------------------------------- ## # So that we can recreate a full libtool script including additional # tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS # in macros and then make a single call at the end using the 'libtool' # label. # _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) # ---------------------------------------- # Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL_INIT], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_INIT], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_INIT]) # _LT_CONFIG_LIBTOOL([COMMANDS]) # ------------------------------ # Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) # _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) # ----------------------------------------------------- m4_defun([_LT_CONFIG_SAVE_COMMANDS], [_LT_CONFIG_LIBTOOL([$1]) _LT_CONFIG_LIBTOOL_INIT([$2]) ]) # _LT_FORMAT_COMMENT([COMMENT]) # ----------------------------- # Add leading comment marks to the start of each line, and a trailing # full-stop to the whole comment if one is not present already. m4_define([_LT_FORMAT_COMMENT], [m4_ifval([$1], [ m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) )]) ## ------------------------ ## ## FIXME: Eliminate VARNAME ## ## ------------------------ ## # _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) # ------------------------------------------------------------------- # CONFIGNAME is the name given to the value in the libtool script. # VARNAME is the (base) name used in the configure script. # VALUE may be 0, 1 or 2 for a computed quote escaped value based on # VARNAME. Any other value will be used directly. m4_define([_LT_DECL], [lt_if_append_uniq([lt_decl_varnames], [$2], [, ], [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], [m4_ifval([$1], [$1], [$2])]) lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) m4_ifval([$4], [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) lt_dict_add_subkey([lt_decl_dict], [$2], [tagged?], [m4_ifval([$5], [yes], [no])])]) ]) # _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) # -------------------------------------------------------- m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) # lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_tag_varnames], [_lt_decl_filter([tagged?], [yes], $@)]) # _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) # --------------------------------------------------------- m4_define([_lt_decl_filter], [m4_case([$#], [0], [m4_fatal([$0: too few arguments: $#])], [1], [m4_fatal([$0: too few arguments: $#: $1])], [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], [lt_dict_filter([lt_decl_dict], $@)])[]dnl ]) # lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) # -------------------------------------------------- m4_define([lt_decl_quote_varnames], [_lt_decl_filter([value], [1], $@)]) # lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_dquote_varnames], [_lt_decl_filter([value], [2], $@)]) # lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_varnames_tagged], [m4_assert([$# <= 2])dnl _$0(m4_quote(m4_default([$1], [[, ]])), m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) m4_define([_lt_decl_varnames_tagged], [m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) # lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_all_varnames], [_$0(m4_quote(m4_default([$1], [[, ]])), m4_if([$2], [], m4_quote(lt_decl_varnames), m4_quote(m4_shift($@))))[]dnl ]) m4_define([_lt_decl_all_varnames], [lt_join($@, lt_decl_varnames_tagged([$1], lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl ]) # _LT_CONFIG_STATUS_DECLARE([VARNAME]) # ------------------------------------ # Quote a variable value, and forward it to 'config.status' so that its # declaration there will have the same value as in 'configure'. VARNAME # must have a single quote delimited value for this to work. m4_define([_LT_CONFIG_STATUS_DECLARE], [$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`']) # _LT_CONFIG_STATUS_DECLARATIONS # ------------------------------ # We delimit libtool config variables with single quotes, so when # we write them to config.status, we have to be sure to quote all # embedded single quotes properly. In configure, this macro expands # each variable declared with _LT_DECL (and _LT_TAGDECL) into: # # ='`$ECHO "$" | $SED "$delay_single_quote_subst"`' m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], [m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAGS # ---------------- # Output comment and list of tags supported by the script m4_defun([_LT_LIBTOOL_TAGS], [_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl available_tags='_LT_TAGS'dnl ]) # _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) # ----------------------------------- # Extract the dictionary values for VARNAME (optionally with TAG) and # expand to a commented shell variable setting: # # # Some comment about what VAR is for. # visible_name=$lt_internal_name m4_define([_LT_LIBTOOL_DECLARE], [_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [description])))[]dnl m4_pushdef([_libtool_name], m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), [0], [_libtool_name=[$]$1], [1], [_libtool_name=$lt_[]$1], [2], [_libtool_name=$lt_[]$1], [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl ]) # _LT_LIBTOOL_CONFIG_VARS # ----------------------- # Produce commented declarations of non-tagged libtool config variables # suitable for insertion in the LIBTOOL CONFIG section of the 'libtool' # script. Tagged libtool config variables (even for the LIBTOOL CONFIG # section) are produced by _LT_LIBTOOL_TAG_VARS. m4_defun([_LT_LIBTOOL_CONFIG_VARS], [m4_foreach([_lt_var], m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAG_VARS(TAG) # ------------------------- m4_define([_LT_LIBTOOL_TAG_VARS], [m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) # _LT_TAGVAR(VARNAME, [TAGNAME]) # ------------------------------ m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) # _LT_CONFIG_COMMANDS # ------------------- # Send accumulated output to $CONFIG_STATUS. Thanks to the lists of # variables for single and double quote escaping we saved from calls # to _LT_DECL, we can put quote escaped variables declarations # into 'config.status', and then the shell code to quote escape them in # for loops in 'config.status'. Finally, any additional code accumulated # from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. m4_defun([_LT_CONFIG_COMMANDS], [AC_PROVIDE_IFELSE([LT_OUTPUT], dnl If the libtool generation code has been placed in $CONFIG_LT, dnl instead of duplicating it all over again into config.status, dnl then we will have config.status run $CONFIG_LT later, so it dnl needs to know what name is stored there: [AC_CONFIG_COMMANDS([libtool], [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], dnl If the libtool generation code is destined for config.status, dnl expand the accumulated commands and init code now: [AC_CONFIG_COMMANDS([libtool], [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) ])#_LT_CONFIG_COMMANDS # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], [ # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' _LT_CONFIG_STATUS_DECLARATIONS LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$[]1 _LTECHO_EOF' } # Quote evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_quote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_dquote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done _LT_OUTPUT_LIBTOOL_INIT ]) # _LT_GENERATED_FILE_INIT(FILE, [COMMENT]) # ------------------------------------ # Generate a child script FILE with all initialization necessary to # reuse the environment learned by the parent script, and make the # file executable. If COMMENT is supplied, it is inserted after the # '#!' sequence but before initialization text begins. After this # macro, additional text can be appended to FILE to form the body of # the child script. The macro ends with non-zero status if the # file could not be fully written (such as if the disk is full). m4_ifdef([AS_INIT_GENERATED], [m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])], [m4_defun([_LT_GENERATED_FILE_INIT], [m4_require([AS_PREPARE])]dnl [m4_pushdef([AS_MESSAGE_LOG_FD])]dnl [lt_write_fail=0 cat >$1 <<_ASEOF || lt_write_fail=1 #! $SHELL # Generated by $as_me. $2 SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$1 <<\_ASEOF || lt_write_fail=1 AS_SHELL_SANITIZE _AS_PREPARE exec AS_MESSAGE_FD>&1 _ASEOF test 0 = "$lt_write_fail" && chmod +x $1[]dnl m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT # LT_OUTPUT # --------- # This macro allows early generation of the libtool script (before # AC_OUTPUT is called), incase it is used in configure for compilation # tests. AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} AC_MSG_NOTICE([creating $CONFIG_LT]) _LT_GENERATED_FILE_INIT(["$CONFIG_LT"], [# Run this file to recreate a libtool stub with the current configuration.]) cat >>"$CONFIG_LT" <<\_LTEOF lt_cl_silent=false exec AS_MESSAGE_LOG_FD>>config.log { echo AS_BOX([Running $as_me.]) } >&AS_MESSAGE_LOG_FD lt_cl_help="\ '$as_me' creates a local libtool stub from the current configuration, for use in further configure time tests before the real libtool is generated. Usage: $[0] [[OPTIONS]] -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files Report bugs to ." lt_cl_version="\ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. Copyright (C) 2011 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation gives unlimited permision to copy, distribute and modify it." while test 0 != $[#] do case $[1] in --version | --v* | -V ) echo "$lt_cl_version"; exit 0 ;; --help | --h* | -h ) echo "$lt_cl_help"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --quiet | --q* | --silent | --s* | -q ) lt_cl_silent=: ;; -*) AC_MSG_ERROR([unrecognized option: $[1] Try '$[0] --help' for more information.]) ;; *) AC_MSG_ERROR([unrecognized argument: $[1] Try '$[0] --help' for more information.]) ;; esac shift done if $lt_cl_silent; then exec AS_MESSAGE_FD>/dev/null fi _LTEOF cat >>"$CONFIG_LT" <<_LTEOF _LT_OUTPUT_LIBTOOL_COMMANDS_INIT _LTEOF cat >>"$CONFIG_LT" <<\_LTEOF AC_MSG_NOTICE([creating $ofile]) _LT_OUTPUT_LIBTOOL_COMMANDS AS_EXIT(0) _LTEOF chmod +x "$CONFIG_LT" # configure is writing to config.log, but config.lt does its own redirection, # appending to config.log, which fails on DOS, as config.log is still kept # open by configure. Here we exec the FD to /dev/null, effectively closing # config.log, so it can be properly (re)opened and appended to by config.lt. lt_cl_success=: test yes = "$silent" && lt_config_lt_args="$lt_config_lt_args --quiet" exec AS_MESSAGE_LOG_FD>/dev/null $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false exec AS_MESSAGE_LOG_FD>>config.log $lt_cl_success || AS_EXIT(1) ])# LT_OUTPUT # _LT_CONFIG(TAG) # --------------- # If TAG is the built-in tag, create an initial libtool script with a # default configuration from the untagged config vars. Otherwise add code # to config.status for appending the configuration named by TAG from the # matching tagged config vars. m4_defun([_LT_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_CONFIG_SAVE_COMMANDS([ m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl m4_if(_LT_TAG, [C], [ # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi cfgfile=${ofile}T trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # Generated automatically by $as_me ($PACKAGE) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # Provide generalized library-building support services. # Written by Gordon Matzigkeit, 1996 _LT_COPYING _LT_LIBTOOL_TAGS # Configured defaults for sys_lib_dlsearch_path munging. : \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"} # ### BEGIN LIBTOOL CONFIG _LT_LIBTOOL_CONFIG_VARS _LT_LIBTOOL_TAG_VARS # ### END LIBTOOL CONFIG _LT_EOF cat <<'_LT_EOF' >> "$cfgfile" # ### BEGIN FUNCTIONS SHARED WITH CONFIGURE _LT_PREPARE_MUNGE_PATH_LIST _LT_PREPARE_CC_BASENAME # ### END FUNCTIONS SHARED WITH CONFIGURE _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac _LT_PROG_LTMAIN # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? $SED '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ], [cat <<_LT_EOF >> "$ofile" dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded dnl in a comment (ie after a #). # ### BEGIN LIBTOOL TAG CONFIG: $1 _LT_LIBTOOL_TAG_VARS(_LT_TAG) # ### END LIBTOOL TAG CONFIG: $1 _LT_EOF ])dnl /m4_if ], [m4_if([$1], [], [ PACKAGE='$PACKAGE' VERSION='$VERSION' RM='$RM' ofile='$ofile'], []) ])dnl /_LT_CONFIG_SAVE_COMMANDS ])# _LT_CONFIG # LT_SUPPORTED_TAG(TAG) # --------------------- # Trace this macro to discover what tags are supported by the libtool # --tag option, using: # autoconf --trace 'LT_SUPPORTED_TAG:$1' AC_DEFUN([LT_SUPPORTED_TAG], []) # C support is built-in for now m4_define([_LT_LANG_C_enabled], []) m4_define([_LT_TAGS], []) # LT_LANG(LANG) # ------------- # Enable libtool support for the given language if not already enabled. AC_DEFUN([LT_LANG], [AC_BEFORE([$0], [LT_OUTPUT])dnl m4_case([$1], [C], [_LT_LANG(C)], [C++], [_LT_LANG(CXX)], [Go], [_LT_LANG(GO)], [Java], [_LT_LANG(GCJ)], [Fortran 77], [_LT_LANG(F77)], [Fortran], [_LT_LANG(FC)], [Windows Resource], [_LT_LANG(RC)], [m4_ifdef([_LT_LANG_]$1[_CONFIG], [_LT_LANG($1)], [m4_fatal([$0: unsupported language: "$1"])])])dnl ])# LT_LANG # _LT_LANG(LANGNAME) # ------------------ m4_defun([_LT_LANG], [m4_ifdef([_LT_LANG_]$1[_enabled], [], [LT_SUPPORTED_TAG([$1])dnl m4_append([_LT_TAGS], [$1 ])dnl m4_define([_LT_LANG_]$1[_enabled], [])dnl _LT_LANG_$1_CONFIG($1)])dnl ])# _LT_LANG m4_ifndef([AC_PROG_GO], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_GO. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_GO], [AC_LANG_PUSH(Go)dnl AC_ARG_VAR([GOC], [Go compiler command])dnl AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl _AC_ARG_VAR_LDFLAGS()dnl AC_CHECK_TOOL(GOC, gccgo) if test -z "$GOC"; then if test -n "$ac_tool_prefix"; then AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo]) fi fi if test -z "$GOC"; then AC_CHECK_PROG(GOC, gccgo, gccgo, false) fi ])#m4_defun ])#m4_ifndef # _LT_LANG_DEFAULT_CONFIG # ----------------------- m4_defun([_LT_LANG_DEFAULT_CONFIG], [AC_PROVIDE_IFELSE([AC_PROG_CXX], [LT_LANG(CXX)], [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) AC_PROVIDE_IFELSE([AC_PROG_F77], [LT_LANG(F77)], [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) AC_PROVIDE_IFELSE([AC_PROG_FC], [LT_LANG(FC)], [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal dnl pulling things in needlessly. AC_PROVIDE_IFELSE([AC_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([LT_PROG_GCJ], [LT_LANG(GCJ)], [m4_ifdef([AC_PROG_GCJ], [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([A][M_PROG_GCJ], [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([LT_PROG_GCJ], [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) AC_PROVIDE_IFELSE([AC_PROG_GO], [LT_LANG(GO)], [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])]) AC_PROVIDE_IFELSE([LT_PROG_RC], [LT_LANG(RC)], [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) ])# _LT_LANG_DEFAULT_CONFIG # Obsolete macros: AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_CXX], []) dnl AC_DEFUN([AC_LIBTOOL_F77], []) dnl AC_DEFUN([AC_LIBTOOL_FC], []) dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) dnl AC_DEFUN([AC_LIBTOOL_RC], []) # _LT_TAG_COMPILER # ---------------- m4_defun([_LT_TAG_COMPILER], [AC_REQUIRE([AC_PROG_CC])dnl _LT_DECL([LTCC], [CC], [1], [A C compiler])dnl _LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl _LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl _LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC ])# _LT_TAG_COMPILER # _LT_COMPILER_BOILERPLATE # ------------------------ # Check for compiler boilerplate output or warnings with # the simple compiler test code. m4_defun([_LT_COMPILER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ])# _LT_COMPILER_BOILERPLATE # _LT_LINKER_BOILERPLATE # ---------------------- # Check for linker boilerplate output or warnings with # the simple link test code. m4_defun([_LT_LINKER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ])# _LT_LINKER_BOILERPLATE # _LT_REQUIRED_DARWIN_CHECKS # ------------------------- m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ case $host_os in rhapsody* | darwin*) AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) AC_CHECK_TOOL([LIPO], [lipo], [:]) AC_CHECK_TOOL([OTOOL], [otool], [:]) AC_CHECK_TOOL([OTOOL64], [otool64], [:]) _LT_DECL([], [DSYMUTIL], [1], [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) _LT_DECL([], [NMEDIT], [1], [Tool to change global to local symbols on Mac OS X]) _LT_DECL([], [LIPO], [1], [Tool to manipulate fat objects and archives on Mac OS X]) _LT_DECL([], [OTOOL], [1], [ldd/readelf like tool for Mach-O binaries on Mac OS X]) _LT_DECL([], [OTOOL64], [1], [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], [lt_cv_apple_cc_single_mod=no if test -z "$LT_MULTI_MODULE"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test 0 = "$_lt_result"; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -rf libconftest.dylib* rm -f conftest.* fi]) AC_CACHE_CHECK([for -exported_symbols_list linker flag], [lt_cv_ld_exported_symbols_list], [lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [lt_cv_ld_exported_symbols_list=yes], [lt_cv_ld_exported_symbols_list=no]) LDFLAGS=$save_LDFLAGS ]) AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load], [lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD echo "$AR $AR_FLAGS libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD $AR $AR_FLAGS libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then lt_cv_ld_force_load=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM ]) case $host_os in rhapsody* | darwin1.[[012]]) _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; darwin*) case $MACOSX_DEPLOYMENT_TARGET,$host in 10.[[012]],*|,*powerpc*-darwin[[5-8]]*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; *) _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test yes = "$lt_cv_apple_cc_single_mod"; then _lt_dar_single_mod='$single_module' fi if test yes = "$lt_cv_ld_exported_symbols_list"; then _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib' fi if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ]) # _LT_DARWIN_LINKER_FEATURES([TAG]) # --------------------------------- # Checks for linker and compiler features on darwin m4_defun([_LT_DARWIN_LINKER_FEATURES], [ m4_require([_LT_REQUIRED_DARWIN_CHECKS]) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported if test yes = "$lt_cv_ld_force_load"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes], [FC], [_LT_TAGVAR(compiler_needs_object, $1)=yes]) else _LT_TAGVAR(whole_archive_flag_spec, $1)='' fi _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=$_lt_dar_allow_undefined case $cc_basename in ifort*|nagfor*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test yes = "$_lt_dar_can_shared"; then output_verbose_link_cmd=func_echo_all _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil" _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil" _LT_TAGVAR(archive_expsym_cmds, $1)="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" _LT_TAGVAR(module_expsym_cmds, $1)="$SED -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" m4_if([$1], [CXX], [ if test yes != "$lt_cv_apple_cc_single_mod"; then _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dsymutil" _LT_TAGVAR(archive_expsym_cmds, $1)="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dar_export_syms$_lt_dsymutil" fi ],[]) else _LT_TAGVAR(ld_shlibs, $1)=no fi ]) # _LT_SYS_MODULE_PATH_AIX([TAGNAME]) # ---------------------------------- # Links a minimal program and checks the executable # for the system default hardcoded library path. In most cases, # this is /usr/lib:/lib, but when the MPI compilers are used # the location of the communication and MPI libs are included too. # If we don't find anything, use the default library path according # to the aix ld manual. # Store the results from the different compilers for each TAGNAME. # Allow to override them for all tags through lt_cv_aix_libpath. m4_defun([_LT_SYS_MODULE_PATH_AIX], [m4_require([_LT_DECL_SED])dnl if test set = "${lt_cv_aix_libpath+set}"; then aix_libpath=$lt_cv_aix_libpath else AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])], [AC_LINK_IFELSE([AC_LANG_PROGRAM],[ lt_aix_libpath_sed='[ /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }]' _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi],[]) if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=/usr/lib:/lib fi ]) aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1]) fi ])# _LT_SYS_MODULE_PATH_AIX # _LT_SHELL_INIT(ARG) # ------------------- m4_define([_LT_SHELL_INIT], [m4_divert_text([M4SH-INIT], [$1 ])])# _LT_SHELL_INIT # _LT_PROG_ECHO_BACKSLASH # ----------------------- # Find how we can fake an echo command that does not interpret backslash. # In particular, with Autoconf 2.60 or later we add some code to the start # of the generated configure script that will find a shell with a builtin # printf (that we can use as an echo command). m4_defun([_LT_PROG_ECHO_BACKSLASH], [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO AC_MSG_CHECKING([how to print strings]) # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $[]1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } case $ECHO in printf*) AC_MSG_RESULT([printf]) ;; print*) AC_MSG_RESULT([print -r]) ;; *) AC_MSG_RESULT([cat]) ;; esac m4_ifdef([_AS_DETECT_SUGGESTED], [_AS_DETECT_SUGGESTED([ test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test "X`printf %s $ECHO`" = "X$ECHO" \ || test "X`print -r -- $ECHO`" = "X$ECHO" )])]) _LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) _LT_DECL([], [ECHO], [1], [An echo program that protects backslashes]) ])# _LT_PROG_ECHO_BACKSLASH # _LT_WITH_SYSROOT # ---------------- AC_DEFUN([_LT_WITH_SYSROOT], [m4_require([_LT_DECL_SED])dnl AC_MSG_CHECKING([for sysroot]) AC_ARG_WITH([sysroot], [AS_HELP_STRING([--with-sysroot@<:@=DIR@:>@], [Search for dependent libraries within DIR (or the compiler's sysroot if not specified).])], [], [with_sysroot=no]) dnl lt_sysroot will always be passed unquoted. We quote it here dnl in case the user passed a directory name. lt_sysroot= case $with_sysroot in #( yes) if test yes = "$GCC"; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | $SED -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) AC_MSG_RESULT([$with_sysroot]) AC_MSG_ERROR([The sysroot must be an absolute path.]) ;; esac AC_MSG_RESULT([${lt_sysroot:-no}]) _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl [dependent libraries, and where our libraries should be installed.])]) # _LT_ENABLE_LOCK # --------------- m4_defun([_LT_ENABLE_LOCK], [AC_ARG_ENABLE([libtool-lock], [AS_HELP_STRING([--disable-libtool-lock], [avoid locking (might break parallel builds)])]) test no = "$enable_libtool_lock" || enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out what ABI is being produced by ac_compile, and set mode # options accordingly. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `$FILECMD conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE=32 ;; *ELF-64*) HPUX_IA64_MODE=64 ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then if test yes = "$lt_cv_prog_gnu_ld"; then case `$FILECMD conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `$FILECMD conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; mips64*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then emul=elf case `$FILECMD conftest.$ac_objext` in *32-bit*) emul="${emul}32" ;; *64-bit*) emul="${emul}64" ;; esac case `$FILECMD conftest.$ac_objext` in *MSB*) emul="${emul}btsmip" ;; *LSB*) emul="${emul}ltsmip" ;; esac case `$FILECMD conftest.$ac_objext` in *N32*) emul="${emul}n32" ;; esac LD="${LD-ld} -m $emul" fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. Note that the listed cases only cover the # situations where additional linker options are needed (such as when # doing 32-bit compilation for a host where ld defaults to 64-bit, or # vice versa); the common cases where no linker options are needed do # not appear in the list. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `$FILECMD conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) case `$FILECMD conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" ;; *) LD="${LD-ld} -m elf_i386" ;; esac ;; powerpc64le-*linux*) LD="${LD-ld} -m elf32lppclinux" ;; powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*linux*) LD="${LD-ld} -m elf64lppc" ;; powerpc-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -belf" AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, [AC_LANG_PUSH(C) AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) AC_LANG_POP]) if test yes != "$lt_cv_cc_needs_belf"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS=$SAVE_CFLAGS fi ;; *-*solaris*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `$FILECMD conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*|x86_64-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD=${LD-ld}_sol2 fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks=$enable_libtool_lock ])# _LT_ENABLE_LOCK # _LT_PROG_AR # ----------- m4_defun([_LT_PROG_AR], [AC_CHECK_TOOLS(AR, [ar], false) : ${AR=ar} _LT_DECL([], [AR], [1], [The archiver]) # Use ARFLAGS variable as AR's operation code to sync the variable naming with # Automake. If both AR_FLAGS and ARFLAGS are specified, AR_FLAGS should have # higher priority because thats what people were doing historically (setting # ARFLAGS for automake and AR_FLAGS for libtool). FIXME: Make the AR_FLAGS # variable obsoleted/removed. test ${AR_FLAGS+y} || AR_FLAGS=${ARFLAGS-cr} lt_ar_flags=$AR_FLAGS _LT_DECL([], [lt_ar_flags], [0], [Flags to create an archive (by configure)]) # Make AR_FLAGS overridable by 'make ARFLAGS='. Don't try to run-time override # by AR_FLAGS because that was never working and AR_FLAGS is about to die. _LT_DECL([], [AR_FLAGS], [\@S|@{ARFLAGS-"\@S|@lt_ar_flags"}], [Flags to create an archive]) AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file], [lt_cv_ar_at_file=no AC_COMPILE_IFELSE([AC_LANG_PROGRAM], [echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([lt_ar_try]) if test 0 -eq "$ac_status"; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a AC_TRY_EVAL([lt_ar_try]) if test 0 -ne "$ac_status"; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a ]) ]) if test no = "$lt_cv_ar_at_file"; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi _LT_DECL([], [archiver_list_spec], [1], [How to feed a file listing to the archiver]) ])# _LT_PROG_AR # _LT_CMD_OLD_ARCHIVE # ------------------- m4_defun([_LT_CMD_OLD_ARCHIVE], [_LT_PROG_AR AC_CHECK_TOOL(STRIP, strip, :) test -z "$STRIP" && STRIP=: _LT_DECL([], [STRIP], [1], [A symbol stripping program]) AC_CHECK_TOOL(RANLIB, ranlib, :) test -z "$RANLIB" && RANLIB=: _LT_DECL([], [RANLIB], [1], [Commands used to install an old-style archive]) # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in bitrig* | openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac _LT_DECL([], [old_postinstall_cmds], [2]) _LT_DECL([], [old_postuninstall_cmds], [2]) _LT_TAGDECL([], [old_archive_cmds], [2], [Commands used to build an old-style archive]) _LT_DECL([], [lock_old_archive_extraction], [0], [Whether to use a lock for old archive extraction]) ])# _LT_CMD_OLD_ARCHIVE # _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------------------- # Check whether the given compiler option works AC_DEFUN([_LT_COMPILER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$3" ## exclude from sc_useless_quotes_in_assignment # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi fi $RM conftest* ]) if test yes = "[$]$2"; then m4_if([$5], , :, [$5]) else m4_if([$6], , :, [$6]) fi ])# _LT_COMPILER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) # _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------- # Check whether the given linker option works AC_DEFUN([_LT_LINKER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS $3" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&AS_MESSAGE_LOG_FD $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi else $2=yes fi fi $RM -r conftest* LDFLAGS=$save_LDFLAGS ]) if test yes = "[$]$2"; then m4_if([$4], , :, [$4]) else m4_if([$5], , :, [$5]) fi ])# _LT_LINKER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) # LT_CMD_MAX_LEN #--------------- AC_DEFUN([LT_CMD_MAX_LEN], [AC_REQUIRE([AC_CANONICAL_HOST])dnl # find the maximum length of command line arguments AC_MSG_CHECKING([the maximum length of command line arguments]) AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl i=0 teststring=ABCD case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; bitrig* | darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | $SED 's/.*[[ ]]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len" && \ test undefined != "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test X`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test 17 != "$i" # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ]) if test -n "$lt_cv_sys_max_cmd_len"; then AC_MSG_RESULT($lt_cv_sys_max_cmd_len) else AC_MSG_RESULT(none) fi max_cmd_len=$lt_cv_sys_max_cmd_len _LT_DECL([], [max_cmd_len], [0], [What is the maximum length of a command?]) ])# LT_CMD_MAX_LEN # Old name: AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) # _LT_HEADER_DLFCN # ---------------- m4_defun([_LT_HEADER_DLFCN], [AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl ])# _LT_HEADER_DLFCN # _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, # ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) # ---------------------------------------------------------------- m4_defun([_LT_TRY_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test yes = "$cross_compiling"; then : [$4] else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; }] _LT_EOF if AC_TRY_EVAL(ac_link) && test -s "conftest$ac_exeext" 2>/dev/null; then (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) $1 ;; x$lt_dlneed_uscore) $2 ;; x$lt_dlunknown|x*) $3 ;; esac else : # compilation failed $3 fi fi rm -fr conftest* ])# _LT_TRY_DLOPEN_SELF # LT_SYS_DLOPEN_SELF # ------------------ AC_DEFUN([LT_SYS_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test yes != "$enable_dlopen"; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen=load_add_on lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen=LoadLibrary lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen=dlopen lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl],[ lt_cv_dlopen=dyld lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ]) ;; tpf*) # Don't try to run any link tests for TPF. We know it's impossible # because TPF is a cross-compiler, and we know how we open DSOs. lt_cv_dlopen=dlopen lt_cv_dlopen_libs= lt_cv_dlopen_self=no ;; *) AC_CHECK_FUNC([shl_load], [lt_cv_dlopen=shl_load], [AC_CHECK_LIB([dld], [shl_load], [lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld], [AC_CHECK_FUNC([dlopen], [lt_cv_dlopen=dlopen], [AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl], [AC_CHECK_LIB([svld], [dlopen], [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld], [AC_CHECK_LIB([dld], [dld_link], [lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld]) ]) ]) ]) ]) ]) ;; esac if test no = "$lt_cv_dlopen"; then enable_dlopen=no else enable_dlopen=yes fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS=$CPPFLAGS test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS=$LDFLAGS wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS=$LIBS LIBS="$lt_cv_dlopen_libs $LIBS" AC_CACHE_CHECK([whether a program can dlopen itself], lt_cv_dlopen_self, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) ]) if test yes = "$lt_cv_dlopen_self"; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" AC_CACHE_CHECK([whether a statically linked program can dlopen itself], lt_cv_dlopen_self_static, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) ]) fi CPPFLAGS=$save_CPPFLAGS LDFLAGS=$save_LDFLAGS LIBS=$save_LIBS ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi _LT_DECL([dlopen_support], [enable_dlopen], [0], [Whether dlopen is supported]) _LT_DECL([dlopen_self], [enable_dlopen_self], [0], [Whether dlopen of programs is supported]) _LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], [Whether dlopen of statically linked programs is supported]) ])# LT_SYS_DLOPEN_SELF # Old name: AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) # _LT_COMPILER_C_O([TAGNAME]) # --------------------------- # Check to see if options -c and -o are simultaneously supported by compiler. # This macro does not hard code the compiler like AC_PROG_CC_C_O. m4_defun([_LT_COMPILER_C_O], [m4_require([_LT_DECL_SED])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes fi fi chmod u+w . 2>&AS_MESSAGE_LOG_FD $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ]) _LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], [Does compiler simultaneously support -c and -o options?]) ])# _LT_COMPILER_C_O # _LT_COMPILER_FILE_LOCKS([TAGNAME]) # ---------------------------------- # Check to see if we can do hard links to lock some files if needed m4_defun([_LT_COMPILER_FILE_LOCKS], [m4_require([_LT_ENABLE_LOCK])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_COMPILER_C_O([$1]) hard_links=nottested if test no = "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" && test no != "$need_locks"; then # do not overwrite the value of need_locks provided by the user AC_MSG_CHECKING([if we can lock with hard links]) hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no AC_MSG_RESULT([$hard_links]) if test no = "$hard_links"; then AC_MSG_WARN(['$CC' does not support '-c -o', so 'make -j' may be unsafe]) need_locks=warn fi else need_locks=no fi _LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) ])# _LT_COMPILER_FILE_LOCKS # _LT_CHECK_OBJDIR # ---------------- m4_defun([_LT_CHECK_OBJDIR], [AC_CACHE_CHECK([for objdir], [lt_cv_objdir], [rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null]) objdir=$lt_cv_objdir _LT_DECL([], [objdir], [0], [The name of the directory that contains temporary libtool files])dnl m4_pattern_allow([LT_OBJDIR])dnl AC_DEFINE_UNQUOTED([LT_OBJDIR], "$lt_cv_objdir/", [Define to the sub-directory where libtool stores uninstalled libraries.]) ])# _LT_CHECK_OBJDIR # _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) # -------------------------------------- # Check hardcoding attributes. m4_defun([_LT_LINKER_HARDCODE_LIBPATH], [AC_MSG_CHECKING([how to hardcode library paths into programs]) _LT_TAGVAR(hardcode_action, $1)= if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || test -n "$_LT_TAGVAR(runpath_var, $1)" || test yes = "$_LT_TAGVAR(hardcode_automatic, $1)"; then # We can hardcode non-existent directories. if test no != "$_LT_TAGVAR(hardcode_direct, $1)" && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" && test no != "$_LT_TAGVAR(hardcode_minus_L, $1)"; then # Linking always hardcodes the temporary library directory. _LT_TAGVAR(hardcode_action, $1)=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. _LT_TAGVAR(hardcode_action, $1)=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. _LT_TAGVAR(hardcode_action, $1)=unsupported fi AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) if test relink = "$_LT_TAGVAR(hardcode_action, $1)" || test yes = "$_LT_TAGVAR(inherit_rpath, $1)"; then # Fast installation is not supported enable_fast_install=no elif test yes = "$shlibpath_overrides_runpath" || test no = "$enable_shared"; then # Fast installation is not necessary enable_fast_install=needless fi _LT_TAGDECL([], [hardcode_action], [0], [How to hardcode a shared library path into an executable]) ])# _LT_LINKER_HARDCODE_LIBPATH # _LT_CMD_STRIPLIB # ---------------- m4_defun([_LT_CMD_STRIPLIB], [m4_require([_LT_DECL_EGREP]) striplib= old_striplib= AC_MSG_CHECKING([whether stripping libraries is possible]) if test -z "$STRIP"; then AC_MSG_RESULT([no]) else if $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then old_striplib="$STRIP --strip-debug" striplib="$STRIP --strip-unneeded" AC_MSG_RESULT([yes]) else case $host_os in darwin*) # FIXME - insert some real tests, host_os isn't really good enough striplib="$STRIP -x" old_striplib="$STRIP -S" AC_MSG_RESULT([yes]) ;; freebsd*) if $STRIP -V 2>&1 | $GREP "elftoolchain" >/dev/null; then old_striplib="$STRIP --strip-debug" striplib="$STRIP --strip-unneeded" AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) fi ;; *) AC_MSG_RESULT([no]) ;; esac fi fi _LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) _LT_DECL([], [striplib], [1]) ])# _LT_CMD_STRIPLIB # _LT_PREPARE_MUNGE_PATH_LIST # --------------------------- # Make sure func_munge_path_list() is defined correctly. m4_defun([_LT_PREPARE_MUNGE_PATH_LIST], [[# func_munge_path_list VARIABLE PATH # ----------------------------------- # VARIABLE is name of variable containing _space_ separated list of # directories to be munged by the contents of PATH, which is string # having a format: # "DIR[:DIR]:" # string "DIR[ DIR]" will be prepended to VARIABLE # ":DIR[:DIR]" # string "DIR[ DIR]" will be appended to VARIABLE # "DIRP[:DIRP]::[DIRA:]DIRA" # string "DIRP[ DIRP]" will be prepended to VARIABLE and string # "DIRA[ DIRA]" will be appended to VARIABLE # "DIR[:DIR]" # VARIABLE will be replaced by "DIR[ DIR]" func_munge_path_list () { case x@S|@2 in x) ;; *:) eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'` \@S|@@S|@1\" ;; x:*) eval @S|@1=\"\@S|@@S|@1 `$ECHO @S|@2 | $SED 's/:/ /g'`\" ;; *::*) eval @S|@1=\"\@S|@@S|@1\ `$ECHO @S|@2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" eval @S|@1=\"`$ECHO @S|@2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \@S|@@S|@1\" ;; *) eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'`\" ;; esac } ]])# _LT_PREPARE_PATH_LIST # _LT_SYS_DYNAMIC_LINKER([TAG]) # ----------------------------- # PORTME Fill in your ld.so characteristics m4_defun([_LT_SYS_DYNAMIC_LINKER], [AC_REQUIRE([AC_CANONICAL_HOST])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_OBJDUMP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PREPARE_MUNGE_PATH_LIST])dnl AC_MSG_CHECKING([dynamic linker characteristics]) m4_if([$1], [], [ if test yes = "$GCC"; then case $host_os in darwin*) lt_awk_arg='/^libraries:/,/LR/' ;; *) lt_awk_arg='/^libraries:/' ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq='s|=\([[A-Za-z]]:\)|\1|g' ;; *) lt_sed_strip_eq='s|=/|/|g' ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary... lt_tmp_lt_search_path_spec= lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` # ...but if some path component already ends with the multilib dir we assume # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer). case "$lt_multi_os_dir; $lt_search_path_spec " in "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*) lt_multi_os_dir= ;; esac for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir" elif test -n "$lt_multi_os_dir"; then test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS = " "; FS = "/|\n";} { lt_foo = ""; lt_count = 0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo = "/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[[lt_foo]]++; } if (lt_freq[[lt_foo]] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's|/\([[A-Za-z]]:\)|\1|g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi]) library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=.so postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown AC_ARG_VAR([LT_SYS_LIBRARY_PATH], [User-defined run-time library search path.]) case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='$libname$release$shared_ext$major' ;; aix[[4-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test ia64 = "$host_cpu"; then # AIX 5 supports IA64 library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line '#! .'. This would cause the generated library to # depend on '.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[[01]] | aix4.[[01]].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # Using Import Files as archive members, it is possible to support # filename-based versioning of shared library archives on AIX. While # this would work for both with and without runtime linking, it will # prevent static linking of such archives. So we do filename-based # shared library versioning with .so extension only, which is used # when both runtime linking and shared linking is enabled. # Unfortunately, runtime linking may impact performance, so we do # not want this to be the default eventually. Also, we use the # versioned .so libs for executables only if there is the -brtl # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. # To allow for filename-based versioning support, we need to create # libNAME.so.V as an archive file, containing: # *) an Import File, referring to the versioned filename of the # archive as well as the shared archive member, telling the # bitwidth (32 or 64) of that shared object, and providing the # list of exported symbols of that shared object, eventually # decorated with the 'weak' keyword # *) the shared object with the F_LOADONLY flag set, to really avoid # it being seen by the linker. # At run time we better use the real file rather than another symlink, # but for link time we create the symlink libNAME.so -> libNAME.so.V case $with_aix_soname,$aix_use_runtimelinking in # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. aix,yes) # traditional libtool dynamic_linker='AIX unversionable lib.so' # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; aix,no) # traditional AIX only dynamic_linker='AIX lib.a[(]lib.so.V[)]' # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' ;; svr4,*) # full svr4 only dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)]" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,yes) # both, prefer svr4 dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)], lib.a[(]lib.so.V[)]" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # unpreferred sharedlib libNAME.a needs extra handling postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"' postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,no) # both, prefer aix dynamic_linker="AIX lib.a[(]lib.so.V[)], lib.so.V[(]$shared_archive_member_spec.o[)]" library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)' postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"' ;; esac shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='$libname$shared_ext' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[[45]]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo $libname | $SED -e 's/^lib/pw/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl* | *,icl*) # Native MSVC or ICC libname_spec='$name' soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' library_names_spec='$libname.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec=$LIB if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC and ICC wrapper library_names_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='$libname$release$major$shared_ext $libname$shared_ext' soname_spec='$libname$release$major$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly* | midnightbsd*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[[23]].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[[01]]* | freebsdelf3.[[01]]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=no sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' if test 32 = "$HPUX_IA64_MODE"; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" sys_lib_dlsearch_path_spec=/usr/lib/hpux32 else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" sys_lib_dlsearch_path_spec=/usr/lib/hpux64 fi ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[[3-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test yes = "$lt_cv_prog_gnu_ld"; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff" sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; linux*android*) version_type=none # Android doesn't support versioned libraries. need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext' soname_spec='$libname$release$shared_ext' finish_cmds= shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes dynamic_linker='Android linker' # Don't embed -rpath directories since the linker doesn't support them. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath], [lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], [lt_cv_shlibpath_overrides_runpath=yes])]) LDFLAGS=$save_LDFLAGS libdir=$save_libdir ]) shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Add ABI-specific directories to the system library path. sys_lib_dlsearch_path_spec="/lib64 /usr/lib64 /lib /usr/lib" # Ideally, we could use ldconfig to report *all* directores which are # searched for libraries, however this is still not possible. Aside from not # being certain /sbin/ldconfig is available, command # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, # even though it is searched at run-time. Try to do the best guess by # appending ld.so.conf contents (and includes) to the search path. if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd* | bitrig*) version_type=sunos sys_lib_dlsearch_path_spec=/usr/lib need_lib_prefix=no if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then need_version=no else need_version=yes fi library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; os2*) libname_spec='$name' version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no # OS/2 can only load a DLL with a base name of 8 characters or less. soname_spec='`test -n "$os2dllname" && libname="$os2dllname"; v=$($ECHO $release$versuffix | tr -d .-); n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _); $ECHO $n$v`$shared_ext' library_names_spec='${libname}_dll.$libext' dynamic_linker='OS/2 ld.exe' shlibpath_var=BEGINLIBPATH sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test yes = "$with_gnu_ld"; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec; then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' soname_spec='$libname$shared_ext.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=sco need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test yes = "$with_gnu_ld"; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac AC_MSG_RESULT([$dynamic_linker]) test no = "$dynamic_linker" && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test yes = "$GCC"; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec fi if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec fi # remember unaugmented sys_lib_dlsearch_path content for libtool script decls... configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec # ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" # to be used as default LT_SYS_LIBRARY_PATH value in generated libtool configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH _LT_DECL([], [variables_saved_for_relink], [1], [Variables whose values should be saved in libtool wrapper scripts and restored at link time]) _LT_DECL([], [need_lib_prefix], [0], [Do we need the "lib" prefix for modules?]) _LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) _LT_DECL([], [version_type], [0], [Library versioning type]) _LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) _LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) _LT_DECL([], [shlibpath_overrides_runpath], [0], [Is shlibpath searched before the hard-coded library search path?]) _LT_DECL([], [libname_spec], [1], [Format of library name prefix]) _LT_DECL([], [library_names_spec], [1], [[List of archive names. First name is the real one, the rest are links. The last name is the one that the linker finds with -lNAME]]) _LT_DECL([], [soname_spec], [1], [[The coded name of the library, if different from the real name]]) _LT_DECL([], [install_override_mode], [1], [Permission mode override for installation of shared libraries]) _LT_DECL([], [postinstall_cmds], [2], [Command to use after installation of a shared archive]) _LT_DECL([], [postuninstall_cmds], [2], [Command to use after uninstallation of a shared archive]) _LT_DECL([], [finish_cmds], [2], [Commands used to finish a libtool library installation in a directory]) _LT_DECL([], [finish_eval], [1], [[As "finish_cmds", except a single script fragment to be evaled but not shown]]) _LT_DECL([], [hardcode_into_libs], [0], [Whether we should hardcode library paths into libraries]) _LT_DECL([], [sys_lib_search_path_spec], [2], [Compile-time system search path for libraries]) _LT_DECL([sys_lib_dlsearch_path_spec], [configure_time_dlsearch_path], [2], [Detected run-time system search path for libraries]) _LT_DECL([], [configure_time_lt_sys_library_path], [2], [Explicit LT_SYS_LIBRARY_PATH set during ./configure time]) ])# _LT_SYS_DYNAMIC_LINKER # _LT_PATH_TOOL_PREFIX(TOOL) # -------------------------- # find a file program that can recognize shared library AC_DEFUN([_LT_PATH_TOOL_PREFIX], [m4_require([_LT_DECL_EGREP])dnl AC_MSG_CHECKING([for $1]) AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, [case $MAGIC_CMD in [[\\/*] | ?:[\\/]*]) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD=$MAGIC_CMD lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR dnl $ac_dummy forces splitting on constant user-supplied paths. dnl POSIX.2 word splitting is done only on the output of word expansions, dnl not every word. This closes a longstanding sh security hole. ac_dummy="m4_if([$2], , $PATH, [$2])" for ac_dir in $ac_dummy; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$1"; then lt_cv_path_MAGIC_CMD=$ac_dir/"$1" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD=$lt_cv_path_MAGIC_CMD if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; esac]) MAGIC_CMD=$lt_cv_path_MAGIC_CMD if test -n "$MAGIC_CMD"; then AC_MSG_RESULT($MAGIC_CMD) else AC_MSG_RESULT(no) fi _LT_DECL([], [MAGIC_CMD], [0], [Used to examine libraries when file_magic_cmd begins with "file"])dnl ])# _LT_PATH_TOOL_PREFIX # Old name: AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) # _LT_PATH_MAGIC # -------------- # find a file program that can recognize a shared library m4_defun([_LT_PATH_MAGIC], [_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) else MAGIC_CMD=: fi fi ])# _LT_PATH_MAGIC # LT_PATH_LD # ---------- # find the pathname to the GNU or non-GNU linker AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test no = "$withval" || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD=$ac_prog ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test yes = "$with_gnu_ld"; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD=$ac_dir/$ac_prog # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &1 conftest.i cat conftest.i conftest.i >conftest2.i : ${lt_DD:=$DD} AC_PATH_PROGS_FEATURE_CHECK([lt_DD], [dd], [if "$ac_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=: fi]) rm -f conftest.i conftest2.i conftest.out]) ])# _LT_PATH_DD # _LT_CMD_TRUNCATE # ---------------- # find command to truncate a binary pipe m4_defun([_LT_CMD_TRUNCATE], [m4_require([_LT_PATH_DD]) AC_CACHE_CHECK([how to truncate binary pipes], [lt_cv_truncate_bin], [printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i lt_cv_truncate_bin= if "$ac_cv_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1" fi rm -f conftest.i conftest2.i conftest.out test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q"]) _LT_DECL([lt_truncate_bin], [lt_cv_truncate_bin], [1], [Command to truncate a binary pipe]) ])# _LT_CMD_TRUNCATE # _LT_CHECK_MAGIC_METHOD # ---------------------- # how to check for library dependencies # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_MAGIC_METHOD], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) AC_CACHE_CHECK([how to recognize dependent libraries], lt_cv_deplibs_check_method, [lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # 'unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # that responds to the $file_magic_cmd with a given extended regex. # If you have 'file' or equivalent on your system and you're not sure # whether 'pass_all' will *always* work, you probably want this one. case $host_os in aix[[4-9]]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[[45]]*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='$FILECMD -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. if ( file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly* | midnightbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=$FILECMD lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=$FILECMD case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'] lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[[3-9]]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=$FILECMD lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd* | bitrig*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; os2*) lt_cv_deplibs_check_method=pass_all ;; esac ]) file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown _LT_DECL([], [deplibs_check_method], [1], [Method to check whether dependent libraries are shared objects]) _LT_DECL([], [file_magic_cmd], [1], [Command to use when deplibs_check_method = "file_magic"]) _LT_DECL([], [file_magic_glob], [1], [How to find potential files when deplibs_check_method = "file_magic"]) _LT_DECL([], [want_nocaseglob], [1], [Find potential files using nocaseglob when deplibs_check_method = "file_magic"]) ])# _LT_CHECK_MAGIC_METHOD # LT_PATH_NM # ---------- # find the pathname to a BSD- or MS-compatible name lister AC_DEFUN([LT_PATH_NM], [AC_REQUIRE([AC_PROG_CC])dnl AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, [if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM=$NM else lt_nm_to_check=${ac_tool_prefix}nm if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. tmp_nm=$ac_dir/$lt_tmp_nm if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then # Check to see if the nm accepts a BSD-compat flag. # Adding the 'sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty case $build_os in mingw*) lt_bad_file=conftest.nm/nofile ;; *) lt_bad_file=/dev/null ;; esac case `"$tmp_nm" -B $lt_bad_file 2>&1 | $SED '1q'` in *$lt_bad_file* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break 2 ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | $SED '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break 2 ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS=$lt_save_ifs done : ${lt_cv_path_NM=no} fi]) if test no != "$lt_cv_path_NM"; then NM=$lt_cv_path_NM else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) case `$DUMPBIN -symbols -headers /dev/null 2>&1 | $SED '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols -headers" ;; *) DUMPBIN=: ;; esac fi AC_SUBST([DUMPBIN]) if test : != "$DUMPBIN"; then NM=$DUMPBIN fi fi test -z "$NM" && NM=nm AC_SUBST([NM]) _LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], [lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) cat conftest.out >&AS_MESSAGE_LOG_FD if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest*]) ])# LT_PATH_NM # Old names: AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_PROG_NM], []) dnl AC_DEFUN([AC_PROG_NM], []) # _LT_CHECK_SHAREDLIB_FROM_LINKLIB # -------------------------------- # how to determine the name of the shared library # associated with a specific link library. # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) m4_require([_LT_DECL_DLLTOOL]) AC_CACHE_CHECK([how to associate runtime and link libraries], lt_cv_sharedlib_from_linklib_cmd, [lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh; # decide which one to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd=$ECHO ;; esac ]) sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO _LT_DECL([], [sharedlib_from_linklib_cmd], [1], [Command to associate shared and link libraries]) ])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB # _LT_PATH_MANIFEST_TOOL # ---------------------- # locate the manifest tool m4_defun([_LT_PATH_MANIFEST_TOOL], [AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], [lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&AS_MESSAGE_LOG_FD if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest*]) if test yes != "$lt_cv_path_mainfest_tool"; then MANIFEST_TOOL=: fi _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl ])# _LT_PATH_MANIFEST_TOOL # _LT_DLL_DEF_P([FILE]) # --------------------- # True iff FILE is a Windows DLL '.def' file. # Keep in sync with func_dll_def_p in the libtool script AC_DEFUN([_LT_DLL_DEF_P], [dnl test DEF = "`$SED -n dnl -e '\''s/^[[ ]]*//'\'' dnl Strip leading whitespace -e '\''/^\(;.*\)*$/d'\'' dnl Delete empty lines and comments -e '\''s/^\(EXPORTS\|LIBRARY\)\([[ ]].*\)*$/DEF/p'\'' dnl -e q dnl Only consider the first "real" line $1`" dnl ])# _LT_DLL_DEF_P # LT_LIB_M # -------- # check for math library AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in *-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM=-lmw) AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") ;; *) AC_CHECK_LIB(m, cos, LIBM=-lm) ;; esac AC_SUBST([LIBM]) ])# LT_LIB_M # Old name: AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_CHECK_LIBM], []) # _LT_COMPILER_NO_RTTI([TAGNAME]) # ------------------------------- m4_defun([_LT_COMPILER_NO_RTTI], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= if test yes = "$GCC"; then case $cc_basename in nvcc*) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;; *) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;; esac _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], lt_cv_prog_compiler_rtti_exceptions, [-fno-rtti -fno-exceptions], [], [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) fi _LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], [Compiler flag to turn off builtin functions]) ])# _LT_COMPILER_NO_RTTI # _LT_CMD_GLOBAL_SYMBOLS # ---------------------- m4_defun([_LT_CMD_GLOBAL_SYMBOLS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([LT_PATH_NM])dnl AC_REQUIRE([LT_PATH_LD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_TAG_COMPILER])dnl # Check for command to grab the raw symbol name followed by C symbol from nm. AC_MSG_CHECKING([command to parse $NM output from $compiler object]) AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], [ # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[[BCDEGRST]]' # Regexp to match symbols that can be accessed directly from C. sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[[BCDT]]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[[ABCDGISTW]]' ;; hpux*) if test ia64 = "$host_cpu"; then symcode='[[ABCDEGRST]]' fi ;; irix* | nonstopux*) symcode='[[BCDEGRST]]' ;; osf*) symcode='[[BCDEGQRST]]' ;; solaris*) symcode='[[BDRT]]' ;; sco3.2v5*) symcode='[[DT]]' ;; sysv4.2uw2*) symcode='[[DT]]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[[ABDT]]' ;; sysv4) symcode='[[DFNSTU]]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[[ABCDGIRSTW]]' ;; esac if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Gets list of data symbols to import. lt_cv_sys_global_symbol_to_import="$SED -n -e 's/^I .* \(.*\)$/\1/p'" # Adjust the below global symbol transforms to fixup imported variables. lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'" lt_c_name_hook=" -e 's/^I .* \(.*\)$/ {\"\1\", (void *) 0},/p'" lt_c_name_lib_hook="\ -e 's/^I .* \(lib.*\)$/ {\"\1\", (void *) 0},/p'\ -e 's/^I .* \(.*\)$/ {\"lib\1\", (void *) 0},/p'" else # Disable hooks by default. lt_cv_sys_global_symbol_to_import= lt_cdecl_hook= lt_c_name_hook= lt_c_name_lib_hook= fi # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="$SED -n"\ $lt_cdecl_hook\ " -e 's/^T .* \(.*\)$/extern int \1();/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="$SED -n"\ $lt_c_name_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/p'" # Transform an extracted symbol line into symbol name with lib prefix and # symbol address. lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="$SED -n"\ $lt_c_name_lib_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(lib.*\)$/ {\"\1\", (void *) \&\1},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"lib\1\", (void *) \&\1},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function, # D for any global variable and I for any imported variable. # Also find C++ and __fastcall symbols from MSVC++ or ICC, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK ['"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\ " /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\ " /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\ " {split(\$ 0,a,/\||\r/); split(a[2],s)};"\ " s[1]~/^[@?]/{print f,s[1],s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx]" else lt_cv_sys_global_symbol_pipe="$SED -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | $SED '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. nlist=conftest.nm if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT@&t@_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT@&t@_DLSYM_CONST #else # define LT@&t@_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT@&t@_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[[]] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS=conftstm.$ac_objext CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" if AC_TRY_EVAL(ac_link) && test -s conftest$ac_exeext; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD fi else echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test yes = "$pipe_works"; then break else lt_cv_sys_global_symbol_pipe= fi done ]) if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then AC_MSG_RESULT(failed) else AC_MSG_RESULT(ok) fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then nm_file_list_spec='@' fi _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], [Take the output of nm and produce a listing of raw symbols and C names]) _LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], [Transform the output of nm in a proper C declaration]) _LT_DECL([global_symbol_to_import], [lt_cv_sys_global_symbol_to_import], [1], [Transform the output of nm into a list of symbols to manually relocate]) _LT_DECL([global_symbol_to_c_name_address], [lt_cv_sys_global_symbol_to_c_name_address], [1], [Transform the output of nm in a C name address pair]) _LT_DECL([global_symbol_to_c_name_address_lib_prefix], [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], [Transform the output of nm in a C name address pair when lib prefix is needed]) _LT_DECL([nm_interface], [lt_cv_nm_interface], [1], [The name lister interface]) _LT_DECL([], [nm_file_list_spec], [1], [Specify filename containing input files for $NM]) ]) # _LT_CMD_GLOBAL_SYMBOLS # _LT_COMPILER_PIC([TAGNAME]) # --------------------------- m4_defun([_LT_COMPILER_PIC], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_wl, $1)= _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)= m4_if([$1], [CXX], [ # C++ specific cases for pic, static, wl, etc. if test yes = "$GXX"; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the '-m68020' flag to GCC prevents building anything better, # like '-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) case $host_os in os2*) _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' ;; esac ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac else case $host_os in aix[[4-9]]*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; dgux*) case $cc_basename in ec++*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; ghcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; freebsd* | dragonfly* | midnightbsd*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' if test ia64 != "$host_cpu"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' fi ;; aCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # KAI C++ Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64, which still supported -KPIC. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL 8.0, 9.0 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | $SED 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' ;; *) ;; esac ;; netbsd*) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; cxx*) # Digital/Compaq C++ _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; lcc*) # Lucid _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ], [ if test yes = "$GCC"; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the '-m68020' flag to GCC prevents building anything better, # like '-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) case $host_os in os2*) _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' ;; esac ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker ' if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' case $cc_basename in nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) case $host_os in os2*) _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static' ;; esac ;; hpux9* | hpux10* | hpux11*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC (with -KPIC) is the default. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64, which still supported -KPIC. ecc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # Lahey Fortran 8.1. lf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' ;; nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; tcc*) # Fabrice Bellard et al's Tiny C Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; ccc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All Alpha code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | $SED 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='' ;; *Sun\ F* | *Sun*Fortran*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' ;; *Intel*\ [[CF]]*Compiler*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; *Portland\ Group*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; esac ;; newsos6) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All OSF/1 code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; rdos*) _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; solaris*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; *) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; esac ;; sunos4*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; unicos*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; uts4*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ]) case $host_os in # For platforms that do not support PIC, -DPIC is meaningless: *djgpp*) _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" ;; esac AC_CACHE_CHECK([for $compiler option to produce PIC], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) _LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1) # # Check to make sure the PIC flag actually works. # if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in "" | " "*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; esac], [_LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) fi _LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], [Additional compiler flags for building library objects]) _LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], [How to pass a linker flag through the compiler]) # # Check to make sure the static flag actually works. # wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" _LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), $lt_tmp_static_flag, [], [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) _LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], [Compiler flag to prevent dynamic linking]) ])# _LT_COMPILER_PIC # _LT_LINKER_SHLIBS([TAGNAME]) # ---------------------------- # See if the linker supports building shared libraries. m4_defun([_LT_LINKER_SHLIBS], [AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) m4_if([$1], [CXX], [ _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] case $host_os in aix[[4-9]]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to GNU nm, but means don't demangle to AIX nm. # Without the "-l" option, or with the "-B" option, AIX nm treats # weak defined symbols like other global defined symbols, whereas # GNU nm marks them as "W". # While the 'weak' keyword is ignored in the Export File, we need # it in the Import File for the 'aix-soname' feature, so we have # to replace the "-B" option with "-P" for AIX nm. if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "L") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' fi ;; pw32*) _LT_TAGVAR(export_symbols_cmds, $1)=$ltdll_cmds ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl* | icl*) _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] ;; esac ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac ], [ runpath_var= _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_cmds, $1)= _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(old_archive_from_new_cmds, $1)= _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= _LT_TAGVAR(thread_safe_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list _LT_TAGVAR(include_expsyms, $1)= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ' (' and ')$', so one must not match beginning or # end of line. Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc', # as well as any symbol that contains 'd'. _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. dnl Note also adjust exclude_expsyms for C++ above. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. if test yes != "$GCC"; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++ or ICC) with_gnu_ld=yes ;; openbsd* | bitrig*) with_gnu_ld=no ;; esac _LT_TAGVAR(ld_shlibs, $1)=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test yes = "$with_gnu_ld"; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;; *\ \(GNU\ Binutils\)\ [[3-9]]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test yes = "$lt_use_gnu_ld_interface"; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='$wl' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi supports_anon_versioning=no case `$LD -v | $SED -e 's/([[^)]]\+)\s\+//' 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[[3-9]]*) # On AIX/PPC, the GNU linker is very broken if test ia64 != "$host_cpu"; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file, use it as # is; otherwise, prepend EXPORTS... _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported shrext_cmds=.dll _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test linux-dietlibc = "$host_os"; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test no = "$tmp_diet" then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 _LT_TAGVAR(whole_archive_flag_spec, $1)= tmp_sharedflag='--shared' ;; nagfor*) # NAGFOR 5.3 tmp_sharedflag='-Wl,-shared' ;; xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes ;; esac case `$CC -V 2>&1 | $SED 5q` in *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' if test yes = "$supports_anon_versioning"; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' fi case $cc_basename in tcc*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='-rdynamic' ;; xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test yes = "$supports_anon_versioning"; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; sunos4*) _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac if test no = "$_LT_TAGVAR(ld_shlibs, $1)"; then runpath_var= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. _LT_TAGVAR(hardcode_minus_L, $1)=yes if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. _LT_TAGVAR(hardcode_direct, $1)=unsupported fi ;; aix[[4-9]]*) if test ia64 = "$host_cpu"; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag= else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to GNU nm, but means don't demangle to AIX nm. # Without the "-l" option, or with the "-B" option, AIX nm treats # weak defined symbols like other global defined symbols, whereas # GNU nm marks them as "W". # While the 'weak' keyword is ignored in the Export File, we need # it in the Import File for the 'aix-soname' feature, so we have # to replace the "-B" option with "-P" for AIX nm. if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "L") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # have runtime linking enabled, and use it for executables. # For shared libraries, we enable/disable runtime linking # depending on the kind of the shared library created - # when "with_aix_soname,aix_use_runtimelinking" is: # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables # "aix,yes" lib.so shared, rtl:yes, for executables # lib.a static archive # "both,no" lib.so.V(shr.o) shared, rtl:yes # lib.a(lib.so.V) shared, rtl:no, for executables # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a(lib.so.V) shared, rtl:no # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a static archive case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then aix_use_runtimelinking=yes break fi done if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then # With aix-soname=svr4, we create the lib.so.V shared archives only, # so we don't have lib.a shared libs to link our executables. # We have to force runtime linking in this case. aix_use_runtimelinking=yes LDFLAGS="$LDFLAGS -Wl,-brtl" fi ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='$wl-f,' case $with_aix_soname,$aix_use_runtimelinking in aix,*) ;; # traditional, no import file svr4,* | *,yes) # use import file # The Import File defines what to hardcode. _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no ;; esac if test yes = "$GCC"; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`$CC -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi ;; esac shared_flag='-shared' if test yes = "$aix_use_runtimelinking"; then shared_flag="$shared_flag "'$wl-G' fi # Need to ensure runtime linking is disabled for the traditional # shared library, or the linker may eventually find shared libraries # /with/ Import File - we do not want to mix them. shared_flag_aix='-shared' shared_flag_svr4='-shared $wl-G' else # not using gcc if test ia64 = "$host_cpu"; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test yes = "$aix_use_runtimelinking"; then shared_flag='$wl-G' else shared_flag='$wl-bM:SRE' fi shared_flag_aix='$wl-bM:SRE' shared_flag_svr4='$wl-G' fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. _LT_TAGVAR(always_export_symbols, $1)=yes if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag else if test ia64 = "$host_cpu"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok' if test yes = "$with_gnu_ld"; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' # -brtl affects multiple linker settings, -berok does not and is overridden later compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`' if test svr4 != "$with_aix_soname"; then # This is similar to how AIX traditionally builds its shared libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' fi if test aix != "$with_aix_soname"; then _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' else # used by -dlpreopen to get the symbols _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV $output_objdir/$realname.d/$soname $output_objdir' fi _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; bsdi[[45]]*) _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl* | icl*) # Native MSVC or ICC _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile=$lt_outputfile.exe lt_tool_outputfile=$lt_tool_outputfile.exe ;; esac~ if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC and ICC wrapper _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' # FIXME: Should let the user specify the lib program. _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly* | midnightbsd*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; hpux9*) if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' else _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' ;; hpux10*) if test yes,no = "$GCC,$with_gnu_ld"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test no = "$with_gnu_ld"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes fi ;; hpux11*) if test yes,no = "$GCC,$with_gnu_ld"; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) m4_if($1, [], [ # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) _LT_LINKER_OPTION([if $CC understands -b], _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b], [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])], [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags']) ;; esac fi if test no = "$with_gnu_ld"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol], [lt_cv_irix_exported_symbol], [save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null" AC_LINK_IFELSE( [AC_LANG_SOURCE( [AC_LANG_CASE([C], [[int foo (void) { return 0; }]], [C++], [[int foo (void) { return 0; }]], [Fortran 77], [[ subroutine foo end]], [Fortran], [[ subroutine foo end]])])], [lt_cv_irix_exported_symbol=yes], [lt_cv_irix_exported_symbol=no]) LDFLAGS=$save_LDFLAGS]) if test yes = "$lt_cv_irix_exported_symbol"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib' fi else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes _LT_TAGVAR(link_all_deplibs, $1)=yes ;; linux*) case $cc_basename in tcc*) # Fabrice Bellard et al's Tiny C Compiler _LT_TAGVAR(ld_shlibs, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; newsos6) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *nto* | *qnx*) ;; openbsd* | bitrig*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' fi else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported shrext_cmds=.dll _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' ;; osf3*) if test yes = "$GCC"; then _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test yes = "$GCC"; then _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; solaris*) _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' if test yes = "$GCC"; then wlarc='$wl' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' _LT_TAGVAR(archive_cmds, $1)='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='$wl' _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands '-z linker_flag'. GCC discards it without '$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test yes = "$GCC"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' else _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' fi ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes ;; sunos4*) if test sequent = "$host_vendor"; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4) case $host_vendor in sni) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' _LT_TAGVAR(hardcode_direct, $1)=no ;; motorola) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4.3*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes _LT_TAGVAR(ld_shlibs, $1)=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We CANNOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport' runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(ld_shlibs, $1)=no ;; esac if test sni = "$host_vendor"; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Blargedynsym' ;; esac fi fi ]) AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no _LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld _LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl _LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl _LT_DECL([], [extract_expsyms_cmds], [2], [The commands to extract the exported symbol list from a shared archive]) # # Do we need to explicitly link libc? # case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in x|xyes) # Assume -lc should be added _LT_TAGVAR(archive_cmds_need_lc, $1)=yes if test yes,yes = "$GCC,$enable_shared"; then case $_LT_TAGVAR(archive_cmds, $1) in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. AC_CACHE_CHECK([whether -lc should be explicitly linked in], [lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1), [$RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if AC_TRY_EVAL(ac_compile) 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) _LT_TAGVAR(allow_undefined_flag, $1)= if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) then lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no else lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes fi _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* ]) _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1) ;; esac fi ;; esac _LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], [Whether or not to add -lc for building shared libraries]) _LT_TAGDECL([allow_libtool_libs_with_static_runtimes], [enable_shared_with_static_runtimes], [0], [Whether or not to disallow shared libs when runtime libs are static]) _LT_TAGDECL([], [export_dynamic_flag_spec], [1], [Compiler flag to allow reflexive dlopens]) _LT_TAGDECL([], [whole_archive_flag_spec], [1], [Compiler flag to generate shared objects directly from archives]) _LT_TAGDECL([], [compiler_needs_object], [1], [Whether the compiler copes with passing no objects directly]) _LT_TAGDECL([], [old_archive_from_new_cmds], [2], [Create an old-style archive from a shared archive]) _LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], [Create a temporary old-style archive to link instead of a shared archive]) _LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) _LT_TAGDECL([], [archive_expsym_cmds], [2]) _LT_TAGDECL([], [module_cmds], [2], [Commands used to build a loadable module if different from building a shared archive.]) _LT_TAGDECL([], [module_expsym_cmds], [2]) _LT_TAGDECL([], [with_gnu_ld], [1], [Whether we are building with GNU ld or not]) _LT_TAGDECL([], [allow_undefined_flag], [1], [Flag that allows shared libraries with undefined symbols to be built]) _LT_TAGDECL([], [no_undefined_flag], [1], [Flag that enforces no undefined symbols]) _LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], [Flag to hardcode $libdir into a binary during linking. This must work even if $libdir does not exist]) _LT_TAGDECL([], [hardcode_libdir_separator], [1], [Whether we need a single "-rpath" flag with a separated argument]) _LT_TAGDECL([], [hardcode_direct], [0], [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_direct_absolute], [0], [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes DIR into the resulting binary and the resulting library dependency is "absolute", i.e impossible to change by setting $shlibpath_var if the library is relocated]) _LT_TAGDECL([], [hardcode_minus_L], [0], [Set to "yes" if using the -LDIR flag during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_shlibpath_var], [0], [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_automatic], [0], [Set to "yes" if building a shared library automatically hardcodes DIR into the library and all subsequent libraries and executables linked against it]) _LT_TAGDECL([], [inherit_rpath], [0], [Set to yes if linker adds runtime paths of dependent libraries to runtime path list]) _LT_TAGDECL([], [link_all_deplibs], [0], [Whether libtool must link a program against all its dependency libraries]) _LT_TAGDECL([], [always_export_symbols], [0], [Set to "yes" if exported symbols are required]) _LT_TAGDECL([], [export_symbols_cmds], [2], [The commands to list exported symbols]) _LT_TAGDECL([], [exclude_expsyms], [1], [Symbols that should not be listed in the preloaded symbols]) _LT_TAGDECL([], [include_expsyms], [1], [Symbols that must always be exported]) _LT_TAGDECL([], [prelink_cmds], [2], [Commands necessary for linking programs (against libraries) with templates]) _LT_TAGDECL([], [postlink_cmds], [2], [Commands necessary for finishing linking programs]) _LT_TAGDECL([], [file_list_spec], [1], [Specify filename containing input files]) dnl FIXME: Not yet implemented dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], dnl [Compiler flag to generate thread safe objects]) ])# _LT_LINKER_SHLIBS # _LT_LANG_C_CONFIG([TAG]) # ------------------------ # Ensure that the configuration variables for a C compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to 'libtool'. m4_defun([_LT_LANG_C_CONFIG], [m4_require([_LT_DECL_EGREP])dnl lt_save_CC=$CC AC_LANG_PUSH(C) # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' _LT_TAG_COMPILER # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) LT_SYS_DLOPEN_SELF _LT_CMD_STRIPLIB # Report what library types will actually be built AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_CONFIG($1) fi AC_LANG_POP CC=$lt_save_CC ])# _LT_LANG_C_CONFIG # _LT_LANG_CXX_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a C++ compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to 'libtool'. m4_defun([_LT_LANG_CXX_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl if test -n "$CXX" && ( test no != "$CXX" && ( (test g++ = "$CXX" && `g++ -v >/dev/null 2>&1` ) || (test g++ != "$CXX"))); then AC_PROG_CXXCPP else _lt_caught_CXX_error=yes fi AC_LANG_PUSH(C++) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test yes != "$_lt_caught_CXX_error"; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test yes = "$GXX"; then _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' else _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= fi if test yes = "$GXX"; then # Set up default GNU C++ configuration LT_PATH_LD # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test yes = "$with_gnu_ld"; then _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='$wl' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) _LT_TAGVAR(ld_shlibs, $1)=yes case $host_os in aix3*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aix[[4-9]]*) if test ia64 = "$host_cpu"; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag= else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # have runtime linking enabled, and use it for executables. # For shared libraries, we enable/disable runtime linking # depending on the kind of the shared library created - # when "with_aix_soname,aix_use_runtimelinking" is: # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables # "aix,yes" lib.so shared, rtl:yes, for executables # lib.a static archive # "both,no" lib.so.V(shr.o) shared, rtl:yes # lib.a(lib.so.V) shared, rtl:no, for executables # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a(lib.so.V) shared, rtl:no # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a static archive case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then # With aix-soname=svr4, we create the lib.so.V shared archives only, # so we don't have lib.a shared libs to link our executables. # We have to force runtime linking in this case. aix_use_runtimelinking=yes LDFLAGS="$LDFLAGS -Wl,-brtl" fi ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='$wl-f,' case $with_aix_soname,$aix_use_runtimelinking in aix,*) ;; # no import file svr4,* | *,yes) # use import file # The Import File defines what to hardcode. _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no ;; esac if test yes = "$GXX"; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`$CC -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi esac shared_flag='-shared' if test yes = "$aix_use_runtimelinking"; then shared_flag=$shared_flag' $wl-G' fi # Need to ensure runtime linking is disabled for the traditional # shared library, or the linker may eventually find shared libraries # /with/ Import File - we do not want to mix them. shared_flag_aix='-shared' shared_flag_svr4='-shared $wl-G' else # not using gcc if test ia64 = "$host_cpu"; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test yes = "$aix_use_runtimelinking"; then shared_flag='$wl-G' else shared_flag='$wl-bM:SRE' fi shared_flag_aix='$wl-bM:SRE' shared_flag_svr4='$wl-G' fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. _LT_TAGVAR(always_export_symbols, $1)=yes if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. # The "-G" linker flag allows undefined symbols. _LT_TAGVAR(no_undefined_flag, $1)='-bernotok' # Determine the default libpath from the value encoded in an empty # executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag else if test ia64 = "$host_cpu"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok' if test yes = "$with_gnu_ld"; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' # -brtl affects multiple linker settings, -berok does not and is overridden later compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`' if test svr4 != "$with_aix_soname"; then # This is similar to how AIX traditionally builds its shared # libraries. Need -bnortl late, we may have -brtl in LDFLAGS. _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' fi if test aix != "$with_aix_soname"; then _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' else # used by -dlpreopen to get the symbols _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV $output_objdir/$realname.d/$soname $output_objdir' fi _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl* | ,icl* | no,icl*) # Native MSVC or ICC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile=$lt_outputfile.exe lt_tool_outputfile=$lt_tool_outputfile.exe ;; esac~ func_to_tool_file "$lt_outputfile"~ if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file, use it as # is; otherwise, prepend EXPORTS... _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported shrext_cmds=.dll _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF _LT_TAGVAR(ld_shlibs, $1)=no ;; freebsd-elf*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; freebsd* | dragonfly* | midnightbsd*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions _LT_TAGVAR(ld_shlibs, $1)=yes ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; hpux9*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; hpux10*|hpux11*) if test no = "$with_gnu_ld"; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) ;; *) _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then if test no = "$with_gnu_ld"; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test yes = "$GXX"; then if test no = "$with_gnu_ld"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` -o $lib' fi fi _LT_TAGVAR(link_all_deplibs, $1)=yes ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib $wl-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*) _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl--rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' ;; cxx*) # Compaq C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib $wl-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic' _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' if test yes = "$supports_anon_versioning"; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | $SED 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file $wl$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; m88k*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) _LT_TAGVAR(ld_shlibs, $1)=yes ;; openbsd* | bitrig*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file,$export_symbols -o $lib' _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E' _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; cxx*) case $host in osf3*) _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $soname `test -n "$verstring" && func_echo_all "$wl-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' ;; *) _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname $wl-input $wl$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~ $RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' ;; esac _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes,no = "$GXX,$with_gnu_ld"; then _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*' case $host in osf3*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(archive_cmds_need_lc,$1)=yes _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G$allow_undefined_flag $wl-M $wl$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands '-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test yes,no = "$GXX,$with_gnu_ld"; then _LT_TAGVAR(no_undefined_flag, $1)=' $wl-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require '-G' NOT '-shared' on this # platform. _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $wl$libdir' case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We CANNOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~ '"$_LT_TAGVAR(old_archive_cmds, $1)" _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~ '"$_LT_TAGVAR(reload_cmds, $1)" ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no _LT_TAGVAR(GCC, $1)=$GXX _LT_TAGVAR(LD, $1)=$LD ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test yes != "$_lt_caught_CXX_error" AC_LANG_POP ])# _LT_LANG_CXX_CONFIG # _LT_FUNC_STRIPNAME_CNF # ---------------------- # func_stripname_cnf prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # # This function is identical to the (non-XSI) version of func_stripname, # except this one can be used by m4 code that may be executed by configure, # rather than the libtool script. m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl AC_REQUIRE([_LT_DECL_SED]) AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH]) func_stripname_cnf () { case @S|@2 in .*) func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%\\\\@S|@2\$%%"`;; *) func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%@S|@2\$%%"`;; esac } # func_stripname_cnf ])# _LT_FUNC_STRIPNAME_CNF # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) # --------------------------------- # Figure out "hidden" library dependencies from verbose # compiler output when linking a shared library. # Parse the compiler output and extract the necessary # objects, libraries and library flags. m4_defun([_LT_SYS_HIDDEN_LIBDEPS], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl # Dependencies to place before and after the object being linked: _LT_TAGVAR(predep_objects, $1)= _LT_TAGVAR(postdep_objects, $1)= _LT_TAGVAR(predeps, $1)= _LT_TAGVAR(postdeps, $1)= _LT_TAGVAR(compiler_lib_search_path, $1)= dnl we can't use the lt_simple_compile_test_code here, dnl because it contains code intended for an executable, dnl not a library. It's possible we should let each dnl tag define a new lt_????_link_test_code variable, dnl but it's only used here... m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF int a; void foo (void) { a = 0; } _LT_EOF ], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF ], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer*4 a a=0 return end _LT_EOF ], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer a a=0 return end _LT_EOF ], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF public class foo { private int a; public void bar (void) { a = 0; } }; _LT_EOF ], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF package foo func foo() { } _LT_EOF ]) _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac dnl Parse the compiler output and extract the necessary dnl objects, libraries and library flags. if AC_TRY_EVAL(ac_compile); then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case $prev$p in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test x-L = "$p" || test x-R = "$p"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test no = "$pre_test_object_deps_done"; then case $prev in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then _LT_TAGVAR(compiler_lib_search_path, $1)=$prev$p else _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} $prev$p" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$_LT_TAGVAR(postdeps, $1)"; then _LT_TAGVAR(postdeps, $1)=$prev$p else _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} $prev$p" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test no = "$pre_test_object_deps_done"; then if test -z "$_LT_TAGVAR(predep_objects, $1)"; then _LT_TAGVAR(predep_objects, $1)=$p else _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" fi else if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then _LT_TAGVAR(postdep_objects, $1)=$p else _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling $1 test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken m4_if([$1], [CXX], [case $host_os in interix[[3-9]]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. _LT_TAGVAR(predep_objects,$1)= _LT_TAGVAR(postdep_objects,$1)= _LT_TAGVAR(postdeps,$1)= ;; esac ]) case " $_LT_TAGVAR(postdeps, $1) " in *" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; esac _LT_TAGVAR(compiler_lib_search_dirs, $1)= if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | $SED -e 's! -L! !g' -e 's!^ !!'` fi _LT_TAGDECL([], [compiler_lib_search_dirs], [1], [The directories searched by this compiler when creating a shared library]) _LT_TAGDECL([], [predep_objects], [1], [Dependencies to place before and after the objects being linked to create a shared library]) _LT_TAGDECL([], [postdep_objects], [1]) _LT_TAGDECL([], [predeps], [1]) _LT_TAGDECL([], [postdeps], [1]) _LT_TAGDECL([], [compiler_lib_search_path], [1], [The library search path used internally by the compiler when linking a shared library]) ])# _LT_SYS_HIDDEN_LIBDEPS # _LT_LANG_F77_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a Fortran 77 compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_F77_CONFIG], [AC_LANG_PUSH(Fortran 77) if test -z "$F77" || test no = "$F77"; then _lt_disable_F77=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for f77 test sources. ac_ext=f # Object file extension for compiled f77 test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the F77 compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test yes != "$_lt_disable_F77"; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${F77-"f77"} CFLAGS=$FFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) GCC=$G77 if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)=$G77 _LT_TAGVAR(LD, $1)=$LD ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test yes != "$_lt_disable_F77" AC_LANG_POP ])# _LT_LANG_F77_CONFIG # _LT_LANG_FC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for a Fortran compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_FC_CONFIG], [AC_LANG_PUSH(Fortran) if test -z "$FC" || test no = "$FC"; then _lt_disable_FC=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for fc test sources. ac_ext=${ac_fc_srcext-f} # Object file extension for compiled fc test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the FC compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test yes != "$_lt_disable_FC"; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${FC-"f95"} CFLAGS=$FCFLAGS compiler=$CC GCC=$ac_cv_fc_compiler_gnu _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)=$ac_cv_fc_compiler_gnu _LT_TAGVAR(LD, $1)=$LD ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test yes != "$_lt_disable_FC" AC_LANG_POP ])# _LT_LANG_FC_CONFIG # _LT_LANG_GCJ_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Java Compiler compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_GCJ_CONFIG], [AC_REQUIRE([LT_PROG_GCJ])dnl AC_LANG_SAVE # Source file extension for Java test sources. ac_ext=java # Object file extension for compiled Java test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="class foo {}" # Code to be used in simple link tests lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GCJ-"gcj"} CFLAGS=$GCJFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)=$LD _LT_CC_BASENAME([$compiler]) # GCJ did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GCJ_CONFIG # _LT_LANG_GO_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Go compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_GO_CONFIG], [AC_REQUIRE([LT_PROG_GO])dnl AC_LANG_SAVE # Source file extension for Go test sources. ac_ext=go # Object file extension for compiled Go test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="package main; func main() { }" # Code to be used in simple link tests lt_simple_link_test_code='package main; func main() { }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GOC-"gccgo"} CFLAGS=$GOFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)=$LD _LT_CC_BASENAME([$compiler]) # Go did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GO_CONFIG # _LT_LANG_RC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for the Windows resource compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to 'libtool'. m4_defun([_LT_LANG_RC_CONFIG], [AC_REQUIRE([LT_PROG_RC])dnl AC_LANG_SAVE # Source file extension for RC test sources. ac_ext=rc # Object file extension for compiled RC test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' # Code to be used in simple link tests lt_simple_link_test_code=$lt_simple_compile_test_code # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC= CC=${RC-"windres"} CFLAGS= compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes if test -n "$compiler"; then : _LT_CONFIG($1) fi GCC=$lt_save_GCC AC_LANG_RESTORE CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_RC_CONFIG # LT_PROG_GCJ # ----------- AC_DEFUN([LT_PROG_GCJ], [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], [AC_CHECK_TOOL(GCJ, gcj,) test set = "${GCJFLAGS+set}" || GCJFLAGS="-g -O2" AC_SUBST(GCJFLAGS)])])[]dnl ]) # Old name: AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_GCJ], []) # LT_PROG_GO # ---------- AC_DEFUN([LT_PROG_GO], [AC_CHECK_TOOL(GOC, gccgo,) ]) # LT_PROG_RC # ---------- AC_DEFUN([LT_PROG_RC], [AC_CHECK_TOOL(RC, windres,) ]) # Old name: AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_RC], []) # _LT_DECL_EGREP # -------------- # If we don't have a new enough Autoconf to choose the best grep # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_EGREP], [AC_REQUIRE([AC_PROG_EGREP])dnl AC_REQUIRE([AC_PROG_FGREP])dnl test -z "$GREP" && GREP=grep _LT_DECL([], [GREP], [1], [A grep program that handles long lines]) _LT_DECL([], [EGREP], [1], [An ERE matcher]) _LT_DECL([], [FGREP], [1], [A literal string matcher]) dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too AC_SUBST([GREP]) ]) # _LT_DECL_OBJDUMP # -------------- # If we don't have a new enough Autoconf to choose the best objdump # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_OBJDUMP], [AC_CHECK_TOOL(OBJDUMP, objdump, false) test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) AC_SUBST([OBJDUMP]) ]) # _LT_DECL_DLLTOOL # ---------------- # Ensure DLLTOOL variable is set. m4_defun([_LT_DECL_DLLTOOL], [AC_CHECK_TOOL(DLLTOOL, dlltool, false) test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program]) AC_SUBST([DLLTOOL]) ]) # _LT_DECL_FILECMD # ---------------- # Check for a file(cmd) program that can be used to detect file type and magic m4_defun([_LT_DECL_FILECMD], [AC_CHECK_TOOL([FILECMD], [file], [:]) _LT_DECL([], [FILECMD], [1], [A file(cmd) program that detects file types]) ])# _LD_DECL_FILECMD # _LT_DECL_SED # ------------ # Check for a fully-functional sed program, that truncates # as few characters as possible. Prefer GNU sed if found. m4_defun([_LT_DECL_SED], [AC_PROG_SED test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" _LT_DECL([], [SED], [1], [A sed program that does not truncate output]) _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], [Sed that helps us avoid accidentally triggering echo(1) options like -n]) ])# _LT_DECL_SED m4_ifndef([AC_PROG_SED], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_SED. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_SED], [AC_MSG_CHECKING([for a sed that does not truncate output]) AC_CACHE_VAL(lt_cv_path_SED, [# Loop through the user's path and test for sed and gsed. # Then use that list of sed's as ones to test for truncation. as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for lt_ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" fi done done done IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris # along with /bin/sed that truncates output. for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do test ! -f "$lt_ac_sed" && continue cat /dev/null > conftest.in lt_ac_count=0 echo $ECHO_N "0123456789$ECHO_C" >conftest.in # Check for GNU sed and select it if it is found. if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then lt_cv_path_SED=$lt_ac_sed break fi while true; do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo >>conftest.nl $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break cmp -s conftest.out conftest.nl || break # 10000 chars as input seems more than enough test 10 -lt "$lt_ac_count" && break lt_ac_count=`expr $lt_ac_count + 1` if test "$lt_ac_count" -gt "$lt_ac_max"; then lt_ac_max=$lt_ac_count lt_cv_path_SED=$lt_ac_sed fi done done ]) SED=$lt_cv_path_SED AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ])#AC_PROG_SED ])#m4_ifndef # Old name: AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_SED], []) # _LT_CHECK_SHELL_FEATURES # ------------------------ # Find out whether the shell is Bourne or XSI compatible, # or has some other useful features. m4_defun([_LT_CHECK_SHELL_FEATURES], [if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi _LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac _LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl _LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl ])# _LT_CHECK_SHELL_FEATURES # _LT_PATH_CONVERSION_FUNCTIONS # ----------------------------- # Determine what file name conversion functions should be used by # func_to_host_file (and, implicitly, by func_to_host_path). These are needed # for certain cross-compile configurations and native mingw. m4_defun([_LT_PATH_CONVERSION_FUNCTIONS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_MSG_CHECKING([how to convert $build file names to $host format]) AC_CACHE_VAL(lt_cv_to_host_file_cmd, [case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac ]) to_host_file_cmd=$lt_cv_to_host_file_cmd AC_MSG_RESULT([$lt_cv_to_host_file_cmd]) _LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd], [0], [convert $build file names to $host format])dnl AC_MSG_CHECKING([how to convert $build file names to toolchain format]) AC_CACHE_VAL(lt_cv_to_tool_file_cmd, [#assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac ]) to_tool_file_cmd=$lt_cv_to_tool_file_cmd AC_MSG_RESULT([$lt_cv_to_tool_file_cmd]) _LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd], [0], [convert $build files to toolchain format])dnl ])# _LT_PATH_CONVERSION_FUNCTIONS ddcutil-2.2.0/m4/ltoptions.m40000644000175000001440000003427514671527762011471 # Helper functions for option handling. -*- Autoconf -*- # # Copyright (C) 2004-2005, 2007-2009, 2011-2019, 2021-2022 Free # Software Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 8 ltoptions.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) # _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) # ------------------------------------------ m4_define([_LT_MANGLE_OPTION], [[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) # _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) # --------------------------------------- # Set option OPTION-NAME for macro MACRO-NAME, and if there is a # matching handler defined, dispatch to it. Other OPTION-NAMEs are # saved as a flag. m4_define([_LT_SET_OPTION], [m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), _LT_MANGLE_DEFUN([$1], [$2]), [m4_warning([Unknown $1 option '$2'])])[]dnl ]) # _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) # ------------------------------------------------------------ # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. m4_define([_LT_IF_OPTION], [m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) # _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) # ------------------------------------------------------- # Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME # are set. m4_define([_LT_UNLESS_OPTIONS], [m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), [m4_define([$0_found])])])[]dnl m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 ])[]dnl ]) # _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) # ---------------------------------------- # OPTION-LIST is a space-separated list of Libtool options associated # with MACRO-NAME. If any OPTION has a matching handler declared with # LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about # the unknown option and exit. m4_defun([_LT_SET_OPTIONS], [# Set options m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [_LT_SET_OPTION([$1], _LT_Option)]) m4_if([$1],[LT_INIT],[ dnl dnl Simply set some default values (i.e off) if boolean options were not dnl specified: _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no ]) _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no ]) dnl dnl If no reference was made to various pairs of opposing options, then dnl we run the default mode handler for the pair. For example, if neither dnl 'shared' nor 'disable-shared' was passed, we enable building of shared dnl archives by default: _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], [_LT_ENABLE_FAST_INSTALL]) _LT_UNLESS_OPTIONS([LT_INIT], [aix-soname=aix aix-soname=both aix-soname=svr4], [_LT_WITH_AIX_SONAME([aix])]) ]) ])# _LT_SET_OPTIONS ## --------------------------------- ## ## Macros to handle LT_INIT options. ## ## --------------------------------- ## # _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) # ----------------------------------------- m4_define([_LT_MANGLE_DEFUN], [[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) # LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) # ----------------------------------------------- m4_define([LT_OPTION_DEFINE], [m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl ])# LT_OPTION_DEFINE # dlopen # ------ LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes ]) AU_DEFUN([AC_LIBTOOL_DLOPEN], [_LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'dlopen' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) # win32-dll # --------- # Declare package support for building win32 dll's. LT_OPTION_DEFINE([LT_INIT], [win32-dll], [enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) AC_CHECK_TOOL(AS, as, false) AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(OBJDUMP, objdump, false) ;; esac test -z "$AS" && AS=as _LT_DECL([], [AS], [1], [Assembler program])dnl test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl ])# win32-dll AU_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'win32-dll' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) # _LT_ENABLE_SHARED([DEFAULT]) # ---------------------------- # implement the --enable-shared flag, and supports the 'shared' and # 'disable-shared' LT_INIT options. # DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. m4_define([_LT_ENABLE_SHARED], [m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([shared], [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS=$lt_save_ifs ;; esac], [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) _LT_DECL([build_libtool_libs], [enable_shared], [0], [Whether or not to build shared libraries]) ])# _LT_ENABLE_SHARED LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) # Old names: AC_DEFUN([AC_ENABLE_SHARED], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) ]) AC_DEFUN([AC_DISABLE_SHARED], [_LT_SET_OPTION([LT_INIT], [disable-shared]) ]) AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_SHARED], []) dnl AC_DEFUN([AM_DISABLE_SHARED], []) # _LT_ENABLE_STATIC([DEFAULT]) # ---------------------------- # implement the --enable-static flag, and support the 'static' and # 'disable-static' LT_INIT options. # DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. m4_define([_LT_ENABLE_STATIC], [m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([static], [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS=$lt_save_ifs ;; esac], [enable_static=]_LT_ENABLE_STATIC_DEFAULT) _LT_DECL([build_old_libs], [enable_static], [0], [Whether or not to build static libraries]) ])# _LT_ENABLE_STATIC LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) # Old names: AC_DEFUN([AC_ENABLE_STATIC], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) ]) AC_DEFUN([AC_DISABLE_STATIC], [_LT_SET_OPTION([LT_INIT], [disable-static]) ]) AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_STATIC], []) dnl AC_DEFUN([AM_DISABLE_STATIC], []) # _LT_ENABLE_FAST_INSTALL([DEFAULT]) # ---------------------------------- # implement the --enable-fast-install flag, and support the 'fast-install' # and 'disable-fast-install' LT_INIT options. # DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'. m4_define([_LT_ENABLE_FAST_INSTALL], [m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([fast-install], [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS=$lt_save_ifs ;; esac], [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) _LT_DECL([fast_install], [enable_fast_install], [0], [Whether or not to optimize for fast installation])dnl ])# _LT_ENABLE_FAST_INSTALL LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) # Old names: AU_DEFUN([AC_ENABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'fast-install' option into LT_INIT's first parameter.]) ]) AU_DEFUN([AC_DISABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'disable-fast-install' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) # _LT_WITH_AIX_SONAME([DEFAULT]) # ---------------------------------- # implement the --with-aix-soname flag, and support the `aix-soname=aix' # and `aix-soname=both' and `aix-soname=svr4' LT_INIT options. DEFAULT # is either `aix', `both' or `svr4'. If omitted, it defaults to `aix'. m4_define([_LT_WITH_AIX_SONAME], [m4_define([_LT_WITH_AIX_SONAME_DEFAULT], [m4_if($1, svr4, svr4, m4_if($1, both, both, aix))])dnl shared_archive_member_spec= case $host,$enable_shared in power*-*-aix[[5-9]]*,yes) AC_MSG_CHECKING([which variant of shared library versioning to provide]) AC_ARG_WITH([aix-soname], [AS_HELP_STRING([--with-aix-soname=aix|svr4|both], [shared library versioning (aka "SONAME") variant to provide on AIX, @<:@default=]_LT_WITH_AIX_SONAME_DEFAULT[@:>@.])], [case $withval in aix|svr4|both) ;; *) AC_MSG_ERROR([Unknown argument to --with-aix-soname]) ;; esac lt_cv_with_aix_soname=$with_aix_soname], [AC_CACHE_VAL([lt_cv_with_aix_soname], [lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT) with_aix_soname=$lt_cv_with_aix_soname]) AC_MSG_RESULT([$with_aix_soname]) if test aix != "$with_aix_soname"; then # For the AIX way of multilib, we name the shared archive member # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o', # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File. # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag, # the AIX toolchain works better with OBJECT_MODE set (default 32). if test 64 = "${OBJECT_MODE-32}"; then shared_archive_member_spec=shr_64 else shared_archive_member_spec=shr fi fi ;; *) with_aix_soname=aix ;; esac _LT_DECL([], [shared_archive_member_spec], [0], [Shared archive member basename, for filename based shared library versioning on AIX])dnl ])# _LT_WITH_AIX_SONAME LT_OPTION_DEFINE([LT_INIT], [aix-soname=aix], [_LT_WITH_AIX_SONAME([aix])]) LT_OPTION_DEFINE([LT_INIT], [aix-soname=both], [_LT_WITH_AIX_SONAME([both])]) LT_OPTION_DEFINE([LT_INIT], [aix-soname=svr4], [_LT_WITH_AIX_SONAME([svr4])]) # _LT_WITH_PIC([MODE]) # -------------------- # implement the --with-pic flag, and support the 'pic-only' and 'no-pic' # LT_INIT options. # MODE is either 'yes' or 'no'. If omitted, it defaults to 'both'. m4_define([_LT_WITH_PIC], [AC_ARG_WITH([pic], [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], [lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for lt_pkg in $withval; do IFS=$lt_save_ifs if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS=$lt_save_ifs ;; esac], [pic_mode=m4_default([$1], [default])]) _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl ])# _LT_WITH_PIC LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) # Old name: AU_DEFUN([AC_LIBTOOL_PICMODE], [_LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the 'pic-only' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) ## ----------------- ## ## LTDL_INIT Options ## ## ----------------- ## m4_define([_LTDL_MODE], []) LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], [m4_define([_LTDL_MODE], [nonrecursive])]) LT_OPTION_DEFINE([LTDL_INIT], [recursive], [m4_define([_LTDL_MODE], [recursive])]) LT_OPTION_DEFINE([LTDL_INIT], [subproject], [m4_define([_LTDL_MODE], [subproject])]) m4_define([_LTDL_TYPE], []) LT_OPTION_DEFINE([LTDL_INIT], [installable], [m4_define([_LTDL_TYPE], [installable])]) LT_OPTION_DEFINE([LTDL_INIT], [convenience], [m4_define([_LTDL_TYPE], [convenience])]) ddcutil-2.2.0/m4/ltsugar.m40000644000175000001440000001045314671527762011107 # ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # # Copyright (C) 2004-2005, 2007-2008, 2011-2019, 2021-2022 Free Software # Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 6 ltsugar.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) # lt_join(SEP, ARG1, [ARG2...]) # ----------------------------- # Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their # associated separator. # Needed until we can rely on m4_join from Autoconf 2.62, since all earlier # versions in m4sugar had bugs. m4_define([lt_join], [m4_if([$#], [1], [], [$#], [2], [[$2]], [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) m4_define([_lt_join], [m4_if([$#$2], [2], [], [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) # lt_car(LIST) # lt_cdr(LIST) # ------------ # Manipulate m4 lists. # These macros are necessary as long as will still need to support # Autoconf-2.59, which quotes differently. m4_define([lt_car], [[$1]]) m4_define([lt_cdr], [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], [$#], 1, [], [m4_dquote(m4_shift($@))])]) m4_define([lt_unquote], $1) # lt_append(MACRO-NAME, STRING, [SEPARATOR]) # ------------------------------------------ # Redefine MACRO-NAME to hold its former content plus 'SEPARATOR''STRING'. # Note that neither SEPARATOR nor STRING are expanded; they are appended # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). # No SEPARATOR is output if MACRO-NAME was previously undefined (different # than defined and empty). # # This macro is needed until we can rely on Autoconf 2.62, since earlier # versions of m4sugar mistakenly expanded SEPARATOR but not STRING. m4_define([lt_append], [m4_define([$1], m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) # lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) # ---------------------------------------------------------- # Produce a SEP delimited list of all paired combinations of elements of # PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list # has the form PREFIXmINFIXSUFFIXn. # Needed until we can rely on m4_combine added in Autoconf 2.62. m4_define([lt_combine], [m4_if(m4_eval([$# > 3]), [1], [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl [[m4_foreach([_Lt_prefix], [$2], [m4_foreach([_Lt_suffix], ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) # lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) # ----------------------------------------------------------------------- # Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited # by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. m4_define([lt_if_append_uniq], [m4_ifdef([$1], [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], [lt_append([$1], [$2], [$3])$4], [$5])], [lt_append([$1], [$2], [$3])$4])]) # lt_dict_add(DICT, KEY, VALUE) # ----------------------------- m4_define([lt_dict_add], [m4_define([$1($2)], [$3])]) # lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) # -------------------------------------------- m4_define([lt_dict_add_subkey], [m4_define([$1($2:$3)], [$4])]) # lt_dict_fetch(DICT, KEY, [SUBKEY]) # ---------------------------------- m4_define([lt_dict_fetch], [m4_ifval([$3], m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) # lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) # ----------------------------------------------------------------- m4_define([lt_if_dict_fetch], [m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], [$5], [$6])]) # lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) # -------------------------------------------------------------- m4_define([lt_dict_filter], [m4_if([$5], [], [], [lt_join(m4_quote(m4_default([$4], [[, ]])), lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl ]) ddcutil-2.2.0/m4/ltversion.m40000644000175000001440000000131214671527762011445 # ltversion.m4 -- version numbers -*- Autoconf -*- # # Copyright (C) 2004, 2011-2019, 2021-2022 Free Software Foundation, # Inc. # Written by Scott James Remnant, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # @configure_input@ # serial 4245 ltversion.m4 # This file is part of GNU Libtool m4_define([LT_PACKAGE_VERSION], [2.4.7]) m4_define([LT_PACKAGE_REVISION], [2.4.7]) AC_DEFUN([LTVERSION_VERSION], [macro_version='2.4.7' macro_revision='2.4.7' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) ddcutil-2.2.0/m4/lt~obsolete.m40000644000175000001440000001400714671527762011777 # lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- # # Copyright (C) 2004-2005, 2007, 2009, 2011-2019, 2021-2022 Free # Software Foundation, Inc. # Written by Scott James Remnant, 2004. # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 5 lt~obsolete.m4 # These exist entirely to fool aclocal when bootstrapping libtool. # # In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN), # which have later been changed to m4_define as they aren't part of the # exported API, or moved to Autoconf or Automake where they belong. # # The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN # in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us # using a macro with the same name in our local m4/libtool.m4 it'll # pull the old libtool.m4 in (it doesn't see our shiny new m4_define # and doesn't know about Autoconf macros at all.) # # So we provide this file, which has a silly filename so it's always # included after everything else. This provides aclocal with the # AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything # because those macros already exist, or will be overwritten later. # We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. # # Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. # Yes, that means every name once taken will need to remain here until # we give up compatibility with versions before 1.7, at which point # we need to keep only those names which we still refer to. # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) ddcutil-2.2.0/m4/introspection.m40000677000175000001440000000673613014535131012320 dnl -*- mode: autoconf -*- dnl Copyright 2009 Johan Dahlin dnl dnl This file is free software; the author(s) gives unlimited dnl permission to copy and/or distribute it, with or without dnl modifications, as long as this notice is preserved. dnl # serial 1 m4_define([_GOBJECT_INTROSPECTION_CHECK_INTERNAL], [ AC_BEFORE([AC_PROG_LIBTOOL],[$0])dnl setup libtool first AC_BEFORE([AM_PROG_LIBTOOL],[$0])dnl setup libtool first AC_BEFORE([LT_INIT],[$0])dnl setup libtool first dnl enable/disable introspection m4_if([$2], [require], [dnl enable_introspection=yes ],[dnl AC_ARG_ENABLE(introspection, AS_HELP_STRING([--enable-introspection[=@<:@no/auto/yes@:>@]], [Enable introspection for this build]),, [enable_introspection=auto]) ])dnl AC_MSG_CHECKING([for gobject-introspection]) dnl presence/version checking AS_CASE([$enable_introspection], [no], [dnl found_introspection="no (disabled, use --enable-introspection to enable)" ],dnl [yes],[dnl PKG_CHECK_EXISTS([gobject-introspection-1.0],, AC_MSG_ERROR([gobject-introspection-1.0 is not installed])) PKG_CHECK_EXISTS([gobject-introspection-1.0 >= $1], found_introspection=yes, AC_MSG_ERROR([You need to have gobject-introspection >= $1 installed to build AC_PACKAGE_NAME])) ],dnl [auto],[dnl PKG_CHECK_EXISTS([gobject-introspection-1.0 >= $1], found_introspection=yes, found_introspection=no) dnl Canonicalize enable_introspection enable_introspection=$found_introspection ],dnl [dnl AC_MSG_ERROR([invalid argument passed to --enable-introspection, should be one of @<:@no/auto/yes@:>@]) ])dnl AC_MSG_RESULT([$found_introspection]) INTROSPECTION_SCANNER= INTROSPECTION_COMPILER= INTROSPECTION_GENERATE= INTROSPECTION_GIRDIR= INTROSPECTION_TYPELIBDIR= if test "x$found_introspection" = "xyes"; then INTROSPECTION_SCANNER=`$PKG_CONFIG --variable=g_ir_scanner gobject-introspection-1.0` INTROSPECTION_COMPILER=`$PKG_CONFIG --variable=g_ir_compiler gobject-introspection-1.0` INTROSPECTION_GENERATE=`$PKG_CONFIG --variable=g_ir_generate gobject-introspection-1.0` INTROSPECTION_GIRDIR=`$PKG_CONFIG --variable=girdir gobject-introspection-1.0` INTROSPECTION_TYPELIBDIR="$($PKG_CONFIG --variable=typelibdir gobject-introspection-1.0)" INTROSPECTION_CFLAGS=`$PKG_CONFIG --cflags gobject-introspection-1.0` INTROSPECTION_LIBS=`$PKG_CONFIG --libs gobject-introspection-1.0` INTROSPECTION_MAKEFILE=`$PKG_CONFIG --variable=datadir gobject-introspection-1.0`/gobject-introspection-1.0/Makefile.introspection fi AC_SUBST(INTROSPECTION_SCANNER) AC_SUBST(INTROSPECTION_COMPILER) AC_SUBST(INTROSPECTION_GENERATE) AC_SUBST(INTROSPECTION_GIRDIR) AC_SUBST(INTROSPECTION_TYPELIBDIR) AC_SUBST(INTROSPECTION_CFLAGS) AC_SUBST(INTROSPECTION_LIBS) AC_SUBST(INTROSPECTION_MAKEFILE) AM_CONDITIONAL(HAVE_INTROSPECTION, test "x$found_introspection" = "xyes") ]) dnl Usage: dnl GOBJECT_INTROSPECTION_CHECK([minimum-g-i-version]) AC_DEFUN([GOBJECT_INTROSPECTION_CHECK], [ _GOBJECT_INTROSPECTION_CHECK_INTERNAL([$1]) ]) dnl Usage: dnl GOBJECT_INTROSPECTION_REQUIRE([minimum-g-i-version]) AC_DEFUN([GOBJECT_INTROSPECTION_REQUIRE], [ _GOBJECT_INTROSPECTION_CHECK_INTERNAL([$1], [require]) ]) ddcutil-2.2.0/src/0000775000175000001440000000000014754576332007511 5ddcutil-2.2.0/src/public/0000777000175000001440000000000014754576333010772 5ddcutil-2.2.0/src/public/ddcutil_macros.h.in0000644000175000001440000000077614754576332014471 /** @file ddcutil_macros.h.in * * Macros for checking ddcutil version at compile time. * The Autotools build system converts this file to ddcutil.macros.h. * The version values are set from those in configure.ac. */ // Copyright (C) 2018-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #define DDCUTIL_VMAJOR @VERSION_VMAJOR@ #define DDCUTIL_VMINOR @VERSION_VMINOR@ #define DDCUTIL_VMICRO @VERSION_VMICRO@ #define DDCUTIL_VSUFFIX @VERSION_VSUFFIX@ ddcutil-2.2.0/src/public/ddcutil_status_codes.h0000644000175000001440000001062114754576332015266 /** @file ddcutil_status_codes.h * * This file defines the DDC specific status codes that can be returned in #DDCA_Status. * In addition to these codes, #DDCA_Status can contain: * - negative Linux errno values * * Because the DDC specific status codes are merged with the Linux status codes * (which are \#defines), they are specified as \#defines rather than enum values. * * If status codes are added, an entry must also be added to the description table * in base/ddc_errno.c. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDCUTIL_STATUS_CODES_H_ #define DDCUTIL_STATUS_CODES_H_ #define RCRANGE_DDC_START 3000 #define DDCRC_OK 0 ///< Success #define DDCRC_DDC_DATA (-(RCRANGE_DDC_START+1 ) ) ///< DDC data error #define DDCRC_NULL_RESPONSE (-(RCRANGE_DDC_START+2 ) ) //!< DDC Null Response received #define DDCRC_MULTI_PART_READ_FRAGMENT (-(RCRANGE_DDC_START+3) ) ///< Error in multi-part read fragment #define DDCRC_ALL_TRIES_ZERO (-(RCRANGE_DDC_START+4 ) ) ///< packet data entirely 0 for all tries #define DDCRC_REPORTED_UNSUPPORTED (-(RCRANGE_DDC_START+5 ) ) ///< DDC reply says unsupported #define DDCRC_READ_ALL_ZERO (-(RCRANGE_DDC_START+6 ) ) ///< all bytes in response packet 0 #define DDCRC_RETRIES (-(RCRANGE_DDC_START+7 ) ) ///< too many retries #define DDCRC_EDID (-(RCRANGE_DDC_START+8 ) ) ///< still in use, use DDCRC_READ_EDID or DDCRC_INVALID_EDID #define DDCRC_READ_EDID (-(RCRANGE_DDC_START+9 ) ) ///< error reading EDID #define DDCRC_INVALID_EDID (-(RCRANGE_DDC_START+10) ) ///< error parsing EDID #define DDCRC_ALL_RESPONSES_NULL (-(RCRANGE_DDC_START+11) ) ///< all responses are DDC Null Message #define DDCRC_DETERMINED_UNSUPPORTED (-(RCRANGE_DDC_START+12) ) ///< feature determined to be unsupported #define DDCRC_ARG (-(RCRANGE_DDC_START+13) ) ///< illegal argument #define DDCRC_INVALID_OPERATION (-(RCRANGE_DDC_START+14) ) ///< e.g. writing a r/o feature #define DDCRC_UNIMPLEMENTED (-(RCRANGE_DDC_START+15) ) ///< unimplemented service #define DDCRC_UNINITIALIZED (-(RCRANGE_DDC_START+16) ) ///< library not initialized #define DDCRC_UNKNOWN_FEATURE (-(RCRANGE_DDC_START+17) ) ///< feature not in feature table #define DDCRC_INTERPRETATION_FAILED (-(RCRANGE_DDC_START+18) ) ///< value format failed #define DDCRC_MULTI_FEATURE_ERROR (-(RCRANGE_DDC_START+19) ) ///< an error occurred on a multi-feature request #define DDCRC_INVALID_DISPLAY (-(RCRANGE_DDC_START+20) ) ///< monitor not found, can't open, no DDC support, etc #define DDCRC_INTERNAL_ERROR (-(RCRANGE_DDC_START+21) ) ///< error that triggers program failure #define DDCRC_OTHER (-(RCRANGE_DDC_START+22) ) ///< other error (for use during development) #define DDCRC_VERIFY (-(RCRANGE_DDC_START+23) ) ///< read after VCP write failed or wrong value #define DDCRC_NOT_FOUND (-(RCRANGE_DDC_START+24) ) ///< generic not found #define DDCRC_LOCKED (-(RCRANGE_DDC_START+25) ) ///< resource locked #define DDCRC_ALREADY_OPEN (-(RCRANGE_DDC_START+26) ) ///< already open in current thread #define DDCRC_BAD_DATA (-(RCRANGE_DDC_START+27) ) ///< invalid data #define DDCRC_CONFIG_ERROR (-(RCRANGE_DDC_START+28) ) ///< invalid configuration parm, invalid config file #define DDCRC_INVALID_CONFIG_FILE DDCRC_CONFIG_ERROR ///< for backward compatibility #define DDCRC_DISCONNECTED (-(RCRANGE_DDC_START+29) ) ///< display has been disconnected #define DDCRC_DPMS_ASLEEP (-(RCRANGE_DDC_START+30) ) ///< display is in a DPMS sleep mode #define DDCRC_FLOCKED (-(RCRANGE_DDC_START+31) ) ///< flock() failure, cross-process locking #define DDCRC_QUIESCED (-(RCRANGE_DDC_START+32) ) ///< API temporarily disabled // #define DDCRC_CAP_FATAL (-(RCRANGE_DDC_START+28) ) ///< invalid, unusable capabilities string" // #define DDCRC_CAP_WARNING (-(RCRANGE_DDC_START+29) ) ///< capabilities string has errors but is usable // TODO: consider replacing DDCRC_INVALID_EDID by a more generic DDCRC_BAD_DATA, // or DDC_INVALID_DATA, could be used for e.g. invalid capabilities string #endif /* DDCUTIL_STATUS_CODES_H_ */ ddcutil-2.2.0/src/public/ddcutil_types.h0000644000175000001440000005521114754576332013736 /** @file ddcutil_types.h * @brief File ddcutil_types.h contains type declarations for the C API. * * API function declarations are specified in a separate file, ddcutil_c_api.h. * The reason for this split is that the type declarations are used throughout the * **ddcutil** implementation, whereas the function declarations are only referenced * within the code that implements the API. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDCUTIL_TYPES_H_ #define DDCUTIL_TYPES_H_ #ifdef __cplusplus extern "C" { #endif /** @cond */ #include #include // for uint8_t, unit16_t /** @endcond */ // // Status Code // /** * **ddcutil** Status Code * * Most public **ddcutil** functions return a status code. * These status codes have 3 sources: * - Linux * - ADL (AMD Display Library) (no longer used) * - **ddcutil** itself * * These multiple status code sources are consolidated by "modulating" * the raw values into non-overlapping ranges. * - Linux errno values are returned as negative numbers (e.g. -EIO) * - ADL values are modulated by 2000 (i.e., 2000 subtracted from negative ADL status codes, * or added to positive ADL status codes) (no longer used) * - ddcutil errors are always in the -3000 range * * In summary: * - 0 always indicates a normal successful status * - Positive values (possible with ADL) represent qualified success of some sort (no longer used) * - Negative values indicate an error condition. */ typedef int DDCA_Status; // // Build Information // //! ddcutil version //! typedef struct { uint8_t major; ///< Major release number uint8_t minor; ///< Minor release number uint8_t micro; ///< Micro release number } DDCA_Ddcutil_Version_Spec; //! Build option flags, as returned by #ddca_build_options() //! The enum values are defined as 1,2,4 etc so that they can be or'd. typedef enum { DDCA_BUILT_WITH_NONE = 0x00, /** @brief ddcutil was built with support for USB connected monitors */ DDCA_BUILT_WITH_USB = 0x02, /** @brief ddcutil was built with support for failure simulation */ DDCA_BUILT_WITH_FAILSIM = 0x04 } DDCA_Build_Option_Flags; // // Error Reporting // #define DDCA_ERROR_DETAIL_MARKER "EDTL" //! Detailed error report typedef struct ddca_error_detail { char marker[4]; ///< Always "EDTL" DDCA_Status status_code; ///< Error code char * detail; ///< Optional explanation string uint16_t cause_ct; ///< Number of sub-errors struct ddca_error_detail * causes[]; ///< Variable length array of contributing errors } DDCA_Error_Detail; // // Initialization // //! Options passed to #ddca_init() typedef enum { DDCA_INIT_OPTIONS_NONE = 0, DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE = 1, ///< Do not process configuration file DDCA_INIT_OPTIONS_CLIENT_OPENED_SYSLOG = 2, ///< Client has already opened syslog DDCA_INIT_OPTIONS_ENABLE_INIT_MSGS = 4 ///< Emit msgs re how config file and passed options merged } DDCA_Init_Options; // // Message Control // //! Output Level //! //! Values assigned to constants allow them to be or'd in bit flags. //! //! Values are ascending in order of verbosity typedef enum { DDCA_OL_TERSE =0x04, /**< Brief output */ DDCA_OL_NORMAL =0x08, /**< Normal output */ DDCA_OL_VERBOSE=0x10, /**< Verbose output */ DDCA_OL_VV =0x20 /**< Very verbose output */ } DDCA_Output_Level; // // Tracing // //! ddcutil message severity maps to syslog() severity. //! //! Gaps in values allow for further refinement typedef enum { DDCA_SYSLOG_NOT_SET = -1, DDCA_SYSLOG_NEVER = 0, DDCA_SYSLOG_ERROR = 3, DDCA_SYSLOG_WARNING = 6, DDCA_SYSLOG_NOTICE = 9, DDCA_SYSLOG_INFO = 12, DDCA_SYSLOG_VERBOSE = 15, DDCA_SYSLOG_DEBUG = 18, } DDCA_Syslog_Level; // // Performance statistics // //! Used as values to specify a single statistics type, and as //! bitflags to select statistics types. typedef enum { DDCA_STATS_NONE = 0x00, ///< no statistics DDCA_STATS_TRIES = 0x01, ///< retry statistics DDCA_STATS_ERRORS = 0x02, ///< error statistics DDCA_STATS_CALLS = 0x04, ///< system calls DDCA_STATS_ELAPSED = 0x08, ///< total elapsed time DDCA_STATS_API = 0x10, ///< API specific stats DDCA_STATS_ALL = 0xFF ///< indicates all statistics types } DDCA_Stats_Type; // // Miscellaneous types // typedef double DDCA_Sleep_Multiplier; // // Output capture // //! Capture option flags, used by #ddca_start_capture() //! //! The enum values are defined as 1,2,4 etc so that they can be or'd. //! //! @since 0.9.0 typedef enum { DDCA_CAPTURE_NOOPTS = 0, ///< @brief no options specified DDCA_CAPTURE_STDERR = 1 ///< @brief capture **stderr** as well as **stdout** } DDCA_Capture_Option_Flags; // // Display Specification // /** @defgroup api_display_spec API Display Specification */ /** Opaque display identifier * * A **DDCA_Display_Identifier** holds the criteria for selecting a monitor, * typically as specified by the user. * * It can take several forms: * - the display number assigned by **dccutil** * - an I2C bus number * - an ADL (adapter index, display index) pair (deprecated) * - a USB (bus number, device number) pair or USB device number * - an EDID * - manufacturer, model, and serial number strings * * @ingroup api_display_spec * */ typedef void * DDCA_Display_Identifier; /** Opaque display reference. * * A #DDCA_Display_Ref describes a monitor. It contains 3 kinds of information: * - Assigned ddcutil display number * - The operating system path to the monitor, which is an I2C bus number or * a USB device number. * - Accumulated information about the monitor, such as the EDID or capabilities string. * * @remark * When libddcutil is started, it detects all connected monitors and creates * a persistent #DDCA_DisplayRef for each. * @remark * A #DDCA_Display_Ref can be obtained in 2 ways: * - From the DDCA_Display_List returned by #ddca_get_display_info_list2() * - Searching based on #DDCA_Display_Identifier using #ddca_get_display_ref() * * @ingroup api_display_spec */ typedef void * DDCA_Display_Ref; /** Opaque display handle * * A **DDCA_Display_Handle** represents an "open" display on which actions can be * performed. This is required for communicating with a display. It is obtained by * calling #ddca_open_display2(). * * For I2C and USB connected displays, an operating system open is performed by * # ddca_open_display2(). #DDCA_Display_Handle then contains the file handle * returned by the operating system. * * @ingroup api_display_spec */ typedef void * DDCA_Display_Handle; ///@} // // VCP Feature Information // /** MCCS Version in binary form */ typedef struct { uint8_t major; /**< major version number */ uint8_t minor; /*** minor version number */ } DDCA_MCCS_Version_Spec; extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_V10; ///< MCCS version 1.0 extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_V20; ///< MCCS version 2.0 extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_V21; ///< MCCS version 2.1 extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_V30; ///< MCCS version 3.0 extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_V22; ///< MCCS version 2.2 extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_ANY; ///< used as query specifier extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_UNKNOWN; ///< value for monitor has been queried unsuccessfully extern const DDCA_MCCS_Version_Spec DDCA_VSPEC_UNQUERIED; ///< indicates version not queried /** MCCS VCP Feature Id */ typedef uint8_t DDCA_Vcp_Feature_Code; /** Bitfield specifying a collection of VCP feature codes * * @remark * This struct might be more appropriately named DDCA_Feature_Set, but * that results in confusing function names such as ddca_feature_set_set() */ typedef struct { uint8_t bytes[32]; } DDCA_Feature_List; extern const DDCA_Feature_List DDCA_EMPTY_FEATURE_LIST; /** Identifiers for publicly useful VCP feature subsets * * @remark * These subset identifiers represent a subset of the much * larger collection of subset ids used internally. */ typedef enum { DDCA_SUBSET_UNSET = 0, ///< No subset selected DDCA_SUBSET_KNOWN, ///< All features defined in a MCCS spec DDCA_SUBSET_COLOR, ///< Color related features DDCA_SUBSET_PROFILE, ///< Features saved and restored by loadvcp/setvcp DDCA_SUBSET_MFG, ///< Feature codes reserved for manufacturer use (0x0e..0xff) DDCA_SUBSET_CAPABILITIES, ///< Feature codes specified in capabilities string DDCA_SUBSET_SCAN, ///< All feature codes other than known write-only or table DDCA_SUBSET_CUSTOM } DDCA_Feature_Subset_Id; // // Display Information // /** Indicates how MCCS communication is performed */ typedef enum { DDCA_IO_I2C, /**< Use DDC to communicate with a /dev/i2c-n device */ DDCA_IO_USB /**< Use USB reports for a USB connected monitor */ } DDCA_IO_Mode; /** Describes a display's physical access mode and the location identifiers for that mode */ typedef struct { DDCA_IO_Mode io_mode; ///< physical access mode union { int i2c_busno; ///< I2C bus number int hiddev_devno; ///* USB hiddev device number } path; } DDCA_IO_Path; // Maximum length of strings extracted from EDID, plus 1 for trailing NULL #define DDCA_EDID_MFG_ID_FIELD_SIZE 4 #define DDCA_EDID_MODEL_NAME_FIELD_SIZE 14 #define DDCA_EDID_SN_ASCII_FIELD_SIZE 14 #define DDCA_DISPLAY_INFO_MARKER "DDIN" /** Describes one monitor detected by ddcutil. * * This struct is copied to the caller and can simply be freed. */ typedef struct { char marker[4]; ///< always "DDIN" int dispno; ///< ddcutil assigned display number DDCA_IO_Path path; ///< physical access path to display int usb_bus; ///< USB bus number, if USB connection int usb_device; ///< USB device number, if USB connection char mfg_id[ DDCA_EDID_MFG_ID_FIELD_SIZE ]; ///< 3 character mfg id from EDID char model_name[DDCA_EDID_MODEL_NAME_FIELD_SIZE]; ///< model name from EDID, 13 char max char sn[ DDCA_EDID_SN_ASCII_FIELD_SIZE ]; ///< "serial number" from EDID, 13 char max uint16_t product_code; ///< model product number uint8_t edid_bytes[128]; ///< first 128 bytes of EDID DDCA_MCCS_Version_Spec vcp_version; ///< VCP version as pair of numbers DDCA_Display_Ref dref; ///< opaque display reference } DDCA_Display_Info; /** Collection of #DDCA_Display_Info */ typedef struct { int ct; ///< number of records DDCA_Display_Info info[]; ///< array whose size is determined by ct } DDCA_Display_Info_List; /** @name Version Feature Flags * * #DDCA_Version_Feature_Flags is a byte of flags describing attributes of a * VCP feature that can vary by MCCS version. * * @remark * Exactly 1 of #DDCA_RO, #DDCA_WO, #DDCA_RW is set. * @remark * Flags #DDCA_STD_CONT, #DDCA_COMPLEX_CONT, #DDCA_SIMPLE_NC, #DDCA_COMPLEX_NC, * #DDCA_WO_NC, #DDCA_NORMAL_TABLE, #DDCA_WO_TABLE refine the C/NC/TABLE categorization * of the VESA MCCS specification. Exactly 1 of these bits is set. */ ///@{ /** Flags specifying VCP feature attributes, which can be VCP version dependent. */ typedef uint16_t DDCA_Version_Feature_Flags; // Bits in DDCA_Version_Feature_Flags: // Exactly 1 of DDCA_RO, DDCA_WO, DDCA_RW is set #define DDCA_RO 0x0400 /**< Read only feature */ #define DDCA_WO 0x0200 /**< Write only feature */ #define DDCA_RW 0x0100 /**< Feature is both readable and writable */ #define DDCA_READABLE (DDCA_RO | DDCA_RW) /**< Feature is either RW or RO */ #define DDCA_WRITABLE (DDCA_WO | DDCA_RW) /**< Feature is either RW or WO */ // Further refine the C/NC/TABLE categorization of the MCCS spec // Exactly 1 of the following 8 bits is set #define DDCA_STD_CONT 0x0080 /**< Normal continuous feature */ #define DDCA_COMPLEX_CONT 0x0040 /**< Continuous feature with special interpretation */ #define DDCA_SIMPLE_NC 0x0020 /**< Non-continuous feature, having a defined list of values in byte SL */ #define DDCA_EXTENDED_NC 0x8000 /**< Like DDCA_SIMPLE_NC, but also using byte SH */ #define DDCA_COMPLEX_NC 0x0010 /**< Non-continuous feature, having a complex interpretation using one or more of SL, SH, ML, MH */ #define DDCA_NC_CONT 0x0800 /**< NC feature combining reserved values with continuous range */ // For WO NC features. There's no interpretation function or lookup table // Used to mark that the feature is defined for a version #define DDCA_WO_NC 0x0008 /**< Used internally for write-only non-continuous features */ #define DDCA_NORMAL_TABLE 0x0004 /**< Normal RW table type feature */ #define DDCA_WO_TABLE 0x0002 /**< Write only table feature */ #define DDCA_CONT (DDCA_STD_CONT|DDCA_COMPLEX_CONT) /**< Continuous feature, of any subtype */ #define DDCA_NC (DDCA_EXTENDED_NC |DDCA_SIMPLE_NC|DDCA_COMPLEX_NC|DDCA_WO_NC|DDCA_NC_CONT) /**< Non-continuous feature of any subtype */ #define DDCA_NON_TABLE (DDCA_CONT | DDCA_NC) /**< Non-table feature of any type */ #define DDCA_TABLE (DDCA_NORMAL_TABLE | DDCA_WO_TABLE) /**< Table type feature, of any subtype */ // #define DDCA_KNOWN (DDCA_CONT | DDCA_NC | DDCA_TABLE) // *** unused *** // Additional bits: #define DDCA_DEPRECATED 0x0001 /**< Feature is deprecated in the specified VCP version */ ///@} typedef uint16_t DDCA_Global_Feature_Flags; // Bits in DDCA_Global_Feature_Flags: // Lifecycle: #define DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY 0x8000 /**< Used internally to indicate a temporary VCP_Feature_Table_Entry */ #define DDCA_PERSISTENT_METADATA 0x1000 /**< Part of internal feature tables, do not free */ // Describe Provenance: #define DDCA_USER_DEFINED 0x4000 /**< User provided feature definition */ #define DDCA_SYNTHETIC 0x2000 /**< Generated feature definition */ typedef uint16_t DDCA_Feature_Flags; // union (DDCA_Version_Feature_Flags, DDCA_Global_Feature_Flags) /** One entry in array listing defined simple NC values. * * An entry of {0x00,NULL} terminates the list. */ typedef struct { uint8_t value_code; char * value_name; } DDCA_Feature_Value_Entry; // Makes reference to feature value table less implementation specific // deprecated // typedef DDCA_Feature_Value_Entry * DDCA_Feature_Value_Table; #define DDCA_FEATURE_METADATA_MARKER "FMET" /** Describes a VCP feature code, tailored for a specific monitor. * Feature metadata can vary by VCP version and user defined features */ typedef struct { char marker[4]; /**< always "FMET" */ DDCA_Vcp_Feature_Code feature_code; /**< VCP feature code */ DDCA_MCCS_Version_Spec vcp_version; /**< MCCS version */ DDCA_Feature_Flags feature_flags; /**< feature type description */ DDCA_Feature_Value_Entry * sl_values; /**< valid when DDCA_SIMPLE_NC set */ void * unused; /** no longer used, was latest_sl_values */ char * feature_name; /**< feature name */ char * feature_desc; /**< feature description */ // possibly add pointers to formatting functions } DDCA_Feature_Metadata; // // Represent the Capabilities string returned by a monitor // #define DDCA_CAP_VCP_MARKER "DCVP" /** Represents one feature code in the vcp() section of the capabilities string. */ typedef struct { char marker[4]; /**< Always DDCA_CAP_VCP_MARKER */ DDCA_Vcp_Feature_Code feature_code; /**< VCP feature code */ int value_ct; /**< number of values declared */ uint8_t * values; /**< array of declared values */ } DDCA_Cap_Vcp; #define DDCA_CAPABILITIES_MARKER "DCAP" /** Represents a monitor capabilities string */ typedef struct { char marker[4]; /**< always DDCA_CAPABILITIES_MARKER */ char * unparsed_string; /**< unparsed capabilities string */ DDCA_MCCS_Version_Spec version_spec; /**< parsed mccs_ver() field */ int cmd_ct; /**< number of command codes */ uint8_t * cmd_codes; /**< array of command codes */ int vcp_code_ct; /**< number of features in vcp() field */ DDCA_Cap_Vcp * vcp_codes; /**< array of pointers to structs describing each vcp code */ int msg_ct; char ** messages; } DDCA_Capabilities; // // Get and set VCP feature values // /** Indicates the physical data type. At the DDC level, continuous (C) and * non-continuous (NC) features are treated identically. They share the same * DDC commands (Get VCP Feature and VCP Feature Reply) and data structure. * Table (T) features use DDC commands Table Write and Table Read, which take * different data structures. */ typedef enum { DDCA_NON_TABLE_VCP_VALUE = 1, /**< Continuous (C) or Non-Continuous (NC) value */ DDCA_TABLE_VCP_VALUE = 2, /**< Table (T) value */ } DDCA_Vcp_Value_Type; typedef struct { uint8_t mh; uint8_t ml; uint8_t sh; uint8_t sl; } DDCA_Non_Table_Vcp_Value; /** Represents a single table VCP value. Consists of a count, and a pointer to the bytes */ typedef struct { uint16_t bytect; /**< Number of bytes in value */ uint8_t* bytes; /**< Bytes of the value */ } DDCA_Table_Vcp_Value; /** Stores a VCP feature value of any type */ typedef struct { DDCA_Vcp_Feature_Code opcode; /**< VCP feature code */ DDCA_Vcp_Value_Type value_type; // probably a different type would be better union { struct { uint8_t * bytes; /**< pointer to bytes of table value */ uint16_t bytect; /**< number of bytes in table value */ } t; /**< table value */ struct { uint8_t mh; uint8_t ml; uint8_t sh; uint8_t sl; } c_nc; /**< continuous non-continuous, i.e. non-table, value */ } val; } DDCA_Any_Vcp_Value; #define VALREC_CUR_VAL(valrec) ( valrec->val.c_nc.sh << 8 | valrec->val.c_nc.sl ) #define VALREC_MAX_VAL(valrec) ( valrec->val.c_nc.mh << 8 | valrec->val.c_nc.ml ) // // For reporting display status changes to client // //! Type of event being reported //! //! @since 2.1.0 typedef enum { DDCA_EVENT_DPMS_AWAKE, DDCA_EVENT_DPMS_ASLEEP, DDCA_EVENT_DISPLAY_CONNECTED, DDCA_EVENT_DISPLAY_DISCONNECTED, DDCA_EVENT_DDC_ENABLED, DDCA_EVENT_UNUSED2, } DDCA_Display_Event_Type; //! Specifies groups of Display_Status_Event_Type to watch for //! //! The enum values are defined as 1,2,4 etc so that they can be or'd. //! //! @since 2.1.0 typedef enum { DDCA_EVENT_CLASS_NONE = 0, DDCA_EVENT_CLASS_DPMS = 1, DDCA_EVENT_CLASS_DISPLAY_CONNECTION = 2, DDCA_EVENT_CLASS_UNUSED1 = 4, } DDCA_Display_Event_Class; #define DDCA_EVENT_CLASS_ALL (DDCA_EVENT_CLASS_DPMS | DDCA_EVENT_CLASS_DISPLAY_CONNECTION) /** Event record passed by a display status callback function. * * @remark * Strictly speaking, connector names can have a maximum length of 32 characters. * In practice, no connector names longer than 16 characters have ever been * seen. Therefore, it should be safe for connector_name to allow for a * maximum of 31 printable characters and a termination byte. * * @remark * The DDCA_Display_Status_Event is defined with unused fields at the end to allow * for future extension without breaking the ABI. * * @since 2.1.0 * * @remark * Field flags with bit DDCA_DISPLAY_EVENT_DDC_WORKING added in 2.2.0 */ #define DDCA_DISPLAY_EVENT_DDC_WORKING 0x08 typedef struct { uint64_t timestamp_nanos; DDCA_Display_Event_Type event_type; DDCA_IO_Path io_path; char connector_name[32]; DDCA_Display_Ref dref; uint8_t flags; void * unused[1]; } DDCA_Display_Status_Event; /** Signature of a function to be invoked by the shared library notifying the * client that a change in connected displays has been detected. * * The client program should call #ddca_redetect_displays() and then * #ddca_get_display_refs() to get the currently valid display references. * * @remark * The DDCA_Display_Status_Event is passed on the stack, not allocated on * the heap. Callback invocation is extremely infrequent, the struct size is * not large, and passing the event on the stack relieves clients of * responsibility for memory management. * * @since 2.1.0 */ typedef void (*DDCA_Display_Status_Callback_Func)(DDCA_Display_Status_Event event); /** Parameter record for tuning watching display connection changes. * * @remark * This struct is defined with unused fields at the end to allow for future * extension without breaking the ABI. * * @since 2.2.0 */ //! @remark see init_display_watch_options() for consideration of what to add typedef struct { // Polling loop intervals for each of the watch modes uint16_t xevent_watch_interval_millisec; /**< For watch mode XEVENT */ uint16_t poll_watch_interval_millisec; /**< For watch mode POLL */ // Once an event is received that possibly indicates a display change, libddcutil // repeatedly checks /sys/class/drm until the reported displays stabilize uint16_t initial_stabilization_millisec; /**< Delay before first_initialization check */ uint16_t stabilization_poll_millisec; /**< Polling interval between stabilization checks */ // Interval at which to check that DDC has become enabled if it is not // immediately enabled when the EDID is detected. uint16_t watch_retry_interval_millisec; void * unused[4]; } DDCA_DW_Settings; #ifdef __cplusplus } #endif #endif /* DDCUTIL_TYPES_H_ */ ddcutil-2.2.0/src/public/ddcutil_c_api.h0000644000175000001440000015260014754576332013645 /** @file ddcutil_c_api.h * * @brief Public C API for ddcutil * * Function names in the public C API begin with "ddca_"\n * Status codes begin with "DDCRC_".\n * Typedefs, other constants, etc. begin with "DDCA_". */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDCUTIL_C_API_H_ #define DDCUTIL_C_API_H_ /** @cond */ #include #include #include /** @endcond */ #ifdef __cplusplus extern "C" { #endif #include "ddcutil_types.h" /* Note on report functions. * * Functions whose names begin with "ddca_report" or "ddca_dbgrpt", * e.g. ddca_report_display_ref(), ddca_report_display_info_list(), write * formatted reports to (normally) the terminal. Sometimes, these are intended * to display data structures for debugging. Other times, they are used to * format output for the ddcutil command line program. * * The operation of these functions can be tweaked in two ways. * - The "depth" parameter is a logical indentation depth. This enables * reports that invoke other reports to indent the subreports * sensibly. At the level of the ddcutil_c_api(), one unit of * logical indentation depth translates to 3 spaces. * - The destination of reports is normally the STDOUT device. This can * be changed by calling set_fout(). */ /* Note on convenience functions. * * Many functions in this API are "convenience" functions. They perform tasks * that could be executed entirely on the client. By providing access to the * server's implementation of these tasks, they exist to avoid having to * recreate such code on the client. In some cases, such as "free" functions, * they relieve the client programmer of having to consider implementation details. */ // // Library build information // /** * Returns the ddcutil version as a struct of 3 8 bit integers. * * @return version numbers */ DDCA_Ddcutil_Version_Spec ddca_ddcutil_version(void); /** * Returns the ddcutil version as a string in the form "major.minor.micro". * * @return version string (caller must not free) */ const char * ddca_ddcutil_version_string(void); /** Returns the full ddcutil version as a string, possibly with a suffix, * * @return string in form "1.3.0" or "1.3.0-dev" (caller must not free) * * @since 1.2.0 */ const char * ddca_ddcutil_extended_version_string(void); /** Queries the options with which the **ddcutil** library was built. * * @return flags byte */ DDCA_Build_Option_Flags ddca_build_options(void); /** Returns the fully qualified name of the shared library file * * @return file name * * @since 2.0.0 */ const char * ddca_libddcutil_filename(void); // // Error Detail // /** Gets a copy of the detailed error information for the previous * API call, if the call supports detailed error information (only * some do). * * @return copy of detailed error information (user must free) * * @since 0.9.0 */ DDCA_Error_Detail * ddca_get_error_detail(void); /** Frees a detailed error information record * * @param[in] ddca_erec error information to free * * @remark * This is a convenience function. * * @since 0.9.0 */ void ddca_free_error_detail( DDCA_Error_Detail * ddca_erec); /** Issues a detailed report of a #DDCA_Error_Detail instance. * * @param[in] ddca_erec error information record * @param[in] depth logical indentation depth * * @remark * This is a convenience function. */ void ddca_report_error_detail( DDCA_Error_Detail * ddca_erec, int depth); // // Status Codes // /** Returns the symbolic name for a ddcutil status code * * @param[in] status_code numeric status code * @return symbolic name, e.g. EBUSY, DDCRC_INVALID_DATA * @retval NULL if unrecognized code * * @remark * The returned value is a pointer into internal persistent * data structures and should not be freed by the caller. */ const char * ddca_rc_name( DDCA_Status status_code); /** Returns a description of a ddcutil status code * * @param[in] status_code numeric status code * @return explanation of status code, e.g. "device or resource busy" * @retval "unknown status code" if unrecognized code * * @remark * The returned value is a pointer into internal persistent * data structures and should not be free'd by the caller. */ const char * ddca_rc_desc( DDCA_Status status_code); // // Initialization // /** Performs library initialization. * * @deprecated * Use ddca_init2() * * @param[in] library_options string of **libddcutil** options * @param[in] syslog_level severity cutoff for system log * @param[in] opts option flags * @return status code * * Unless flag DDC_INIT_OPTIONS_DISABLE_CONFIG_FILE is set in **opts**, * libddcutil options are read from the ddcutil configuration file. * These are combined with any options passed in string **libopts** * and then processed. * * If the returned status code is other than **DDCRC_OK**, a detailed * error report can be obtained using #ddca_get_error_detail(). * * @since 2.0.0 */ DDCA_Status ddca_init(const char * libopts, DDCA_Syslog_Level syslog_level, DDCA_Init_Options opts); /** Performs library initialization. * * @param[in] library_options string of **libddcutil** options * @param[in] syslog_level severity cutoff for system log * @param[in] opts option flags * @param[out] infomsg_loc if non-null, return null terminated list of * informational msgs here * @return status code * * Unless flag DDC_INIT_OPTIONS_DISABLE_CONFIG_FILE is set in **opts**, * libddcutil options are read from the ddcutil configuration file. * These are combined with any options passed in string **libopts** * and then processed. * * If the returned status code is other than **DDCRC_OK**, a detailed * error report can be obtained using #ddca_get_error_detail(). * * The caller is responsible for freeing the null terminated list of * messages returned in infomsg_loc. * * @since 2.1.0 */ DDCA_Status ddca_init2(const char * libopts, DDCA_Syslog_Level syslog_level_arg, DDCA_Init_Options opts, char*** infomsg_loc); // // Global Settings // /** Controls whether VCP values are read after being set. * * @param[in] onoff true/false * @return prior value * * @remark This setting is thread-specific. */ bool ddca_enable_verify( bool onoff); /** Query whether VCP values are read after being set. * @retval true values are verified after being set * @retval false values are not verified * * @remark This setting is thread-specific. */ bool ddca_is_verify_enabled(void); // // Performance // /** Sets the sleep multiplier factor for the open display on current thread. * * The semantics of this function has changed. Prior to release 1.5, * this function set the sleep multiplier for the current thread. * As of release 2.0, it sets the sleep multiplier for open display * (if any) on the current thread. * * @param[in] multiplier, must be >= 0 and <= 10 * @return old multiplier, -1.0f if invalid multiplier specified, or no display open * * @deprecated * This function provides backwards compatibility with applications * written for libddcutil release 1.x. It should not be used in new applications. */ __attribute__ ((deprecated)) double ddca_set_sleep_multiplier(double multiplier); /** Gets the sleep multiplier for the open display on the current thread * * As of release 2.0, the semantics of this function changed. * See #ddca_set_sleep_multiplier(). * * @return sleep multiplier, -1.0f if no display open on current thread */ __attribute__ ((deprecated)) double ddca_get_sleep_multiplier(); /** Sets an explicit sleep multiplier factor for the specified display. * If set, it takes precedence over any other sleep multiplier calculation. * * @param[in] dref display reference * @param[in] multiplier must be >= 0 and <= 10 * @retval DDCRC_OK * @retval DDCRC_ARG invalid display reference or multiplier value */ DDCA_Status ddca_set_display_sleep_multiplier( DDCA_Display_Ref dref, DDCA_Sleep_Multiplier multiplier); /** Gets the current effective sleep multiplier for the specified display. * * This value can vary if dynamic sleep adjustment is active. * * @param dref display reference * @param multiplier_loc where to return answer * @retval DDCRC_OK * @retval DDCRC_ARG invalid display reference */ DDCA_Status ddca_get_current_display_sleep_multiplier( DDCA_Display_Ref dref, DDCA_Sleep_Multiplier* multiplier_loc); /** Controls whether dynamic sleep adjustment is enabled. * This is a global setting that applies to all displays. * * @param onoff * @return previous setting * * @since 2.1.0 */ bool ddca_enable_dynamic_sleep(bool onoff); /** Reports whether dynamic sleep adjustment is enabled. * * @return current setting * * @since 2.1.0 */ bool ddca_is_dynamic_sleep_enabled(); // // Output Redirection // /** Redirects output on the current thread that normally would go to **stdout** */ void ddca_set_fout( FILE * fout); /**< where to write normal messages, if NULL, suppress output */ /** Redirects output on the current thread that normally goes to **stdout** back to **stdout** */ void ddca_set_fout_to_default(void); /** Redirects output on the current thread that normally would go to **stderr** */ void ddca_set_ferr( FILE * ferr); /**< where to write error messages, If NULL, suppress output */ /** Redirects output on the current thread that normally goes to **stderr** back to **stderr** */ void ddca_set_ferr_to_default(void); // // Utility functions for capturing output by redirecting // to an in-memory buffer. // /** Begins capture of **stdout** and optionally **stderr** output on the * current thread to a thread-specific in-memory buffer. * * @param[in] flags option flags * * @note If output is already being captured, this function has no effect. * @since 0.9.0 */ void ddca_start_capture( DDCA_Capture_Option_Flags flags); /** Ends capture of **stdout** output and returns the contents of the * in-memory buffer. * * Upon termination, normal thread output is directed to **stdout**. * If error output was also being captured, error output is redirected * to **stderr**. * * @return captured output as a string, caller responsible for freeing * * @note * If output is not currently being captured, returns a 0 length string. * * @note Writes messages to actual **stderr** in case of error. * @since 0.9.0 */ char * ddca_end_capture(void); // // Message Control // /** Gets the current output level for the current thread * @return output level */ DDCA_Output_Level ddca_get_output_level(void); /** Sets the output level for the current thread * * @param[in] new output level * @return prior output level */ DDCA_Output_Level ddca_set_output_level( DDCA_Output_Level newval); /** Gets the name of an output level * * @param[in] val output level id * @return output level name (do not free) * * @remark * This is a convenience function. */ char * ddca_output_level_name( DDCA_Output_Level val); /**< output level id */ /** Given an external syslog level name returns the syslog level id. * * @param[in] name e.g. ERROR * @return syslog level id, DDCA_SYSLOG_NOT FOUND if invalid name * * @remark * This is a convenience function. * * @since 2.0.0 */ DDCA_Syslog_Level ddca_syslog_level_from_name(const char * name); // // Statistics and Diagnostics // /** Resets all **ddcutil** statistics */ void ddca_reset_stats(void); /** Show execution statistics. * * @param[in] stats bitflags of statistics types to show * @param[in] include_per_display_data include per display detail * @param[in] depth logical indentation depth * * @remark * Prior to version 2.0.0, the second parm was named **include_per_thread_data** * and caused per-thread data to be reported. Most of this data is now * maintained on a per-display basis */ void ddca_show_stats( DDCA_Stats_Type stats, bool include_per_display_data, int depth); // TODO: Add functions to get stats /** Report display locks. * * @param[in] depth logical indentation depth * * @since 2.0.0 */ void ddca_report_locks( int depth); // // Display Detection // /** Gets display references list for all detected displays. * * @param[in] include_invalid_displays if true, displays that do not support DDC are included * @param[out] drefs_loc where to return pointer to null-terminated array of #DDCA_Display_Ref * @retval 0 always succeeds * * @since 1.2.0 */ DDCA_Status ddca_get_display_refs( bool include_invalid_displays, DDCA_Display_Ref** drefs_loc); /** Gets publicly visible information about a display reference * * The returned struct can simply be free()'d by the client. * * @param[in] ddca_dref display reference * @param[out] dinfo_loc where to return pointer to newly allocated #DDCA_Display_Info * @retval DDCRC_OK no error * @retval DDCRC_ARG invalid display reference * * @since 1.2.0 */ DDCA_Status ddca_get_display_info( DDCA_Display_Ref ddca_dref, DDCA_Display_Info ** dinfo_loc); /** Frees a #DDCA_Display_Info struct. * * @param[in] info_rec pointer to instance to free * * @remark * This is a convenience function. #DDCA_Display_Info is copied to * the client and contains no pointers. It could simply be free()'d * by the client. * * @since 1.2.0 */ void ddca_free_display_info(DDCA_Display_Info * info_rec); /** Gets a list of the detected displays. * * @param[in] include_invalid_displays if true, displays that do not support DDC are included * @param[out] dlist_loc where to return pointer to #DDCA_Display_Info_List * @retval 0 always succeeds */ DDCA_Status ddca_get_display_info_list2( bool include_invalid_displays, DDCA_Display_Info_List** dlist_loc); /** Frees a list of detected displays. * * @param[in] dlist pointer to #DDCA_Display_Info_List * * @remark * This is a convenience function. #DDCA_Display_Info_List * contains no pointers and is copied to the client. It could * simply be free'd by the client. */ void ddca_free_display_info_list( DDCA_Display_Info_List * dlist); /** Presents a report on a single display. * The report is written to the current FOUT device for the current thread. * * @param[in] dinfo pointer to a DDCA_Display_Info struct * @param[in] depth logical indentation depth * @retval DDCRC_ARG if precondition failure and precondition failures do not abort * @retval 0 normal * * @remark * For a report intended for users, apply #ddca_report_display_by_dref() * to **dinfo->dref**. */ DDCA_Status ddca_report_display_info( DDCA_Display_Info * dinfo, int depth); /** Reports on all displays in a list of displays. * The report is written to the current FOUT device for the current thread. * * @param[in] dlist pointer to a DDCA_Display_Info_List * @param[in] depth logical indentation depth * * @remark * This is a convenience function. */ void ddca_report_display_info_list( DDCA_Display_Info_List * dlist, int depth); /** Reports on all active displays. * This function hooks into the code used by command "ddcutil detect" * * @param[in] include_invalid_displays if true, report displays that don't support DDC * @param[in] depth logical indentation depth * @return number of MCCS capable displays */ int ddca_report_displays( bool include_invalid_displays, int depth); /** Reinitializes detected displays * * - closes all open displays, releasing any display locks * - n. all existing display handles become invalid * - releases display refs (all existing display refs become invalid) * - releases i2c bus info * - rescans i2c buses * - redetects displays * * @since 1.2.0 */ DDCA_Status ddca_redetect_displays(); // // Display Identifier // /** Creates a display identifier using the display number assigned by ddcutil * * @param[in] dispno display number * @param[out] did_loc where to return display identifier handle * @retval 0 * @ingroup api_display_spec */ DDCA_Status ddca_create_dispno_display_identifier( int dispno, DDCA_Display_Identifier* did_loc); /** Creates a display identifier using an I2C bus number * * @param[in] busno I2C bus number * @param[out] did_loc where to return display identifier handle * @retval 0 * * @ingroup api_display_spec */ DDCA_Status ddca_create_busno_display_identifier( int busno, DDCA_Display_Identifier* did_loc); /** Creates a display identifier using some combination of the manufacturer id, * model name string and serial number string. At least 1 of the 3 must be specified. * * @param[in] mfg_id 3 letter manufacturer id * @param[in] model model name string * @param[in] sn serial number string * @param[out] did_loc where to return display identifier handle * @retval 0 success * @retval DDCRC_ARG all arguments NULL, or at least 1 too long * * @ingroup api_display_spec */ DDCA_Status ddca_create_mfg_model_sn_display_identifier( const char * mfg_id, const char * model, const char * sn, DDCA_Display_Identifier* did_loc); /** Creates a display identifier using a 128 byte EDID * * @param[in] edid pointer to 128 byte EDID * @param[out] did_loc where to return display identifier handle * @retval 0 success * @retval DDCRC_ARG edid==NULL * * @ingroup api_display_spec */ DDCA_Status ddca_create_edid_display_identifier( const uint8_t* edid, DDCA_Display_Identifier * did_loc); // 128 byte edid /** Creates a display identifier using a USB bus number and device number * * @param[in] bus USB bus number * @param[in] device USB device number * @param[out] did_loc where to return display identifier handle * @retval 0 success * * @ingroup api_display_spec */ DDCA_Status ddca_create_usb_display_identifier( int bus, int device, DDCA_Display_Identifier* did_loc); /** Creates a display identifier using a /dev/usb/hiddev device number * * @param[in] hiddev_devno hiddev device number * @param[out] did_loc where to return display identifier handle * @retval 0 success * * @ingroup api_display_spec */ DDCA_Status ddca_create_usb_hiddev_display_identifier( int hiddev_devno, DDCA_Display_Identifier* did_loc); /** Release the memory of a display identifier * * @param[in] did display identifier, may be NULL * @retval 0 success * @retval DDCRC_ARG invalid display identifier * * @remark * Does nothing and returns 0 if **did** is NULL. */ DDCA_Status ddca_free_display_identifier( DDCA_Display_Identifier did); /** Returns a string representation of a display identifier. * * The string is valid until the display identifier is freed. * * @param[in] did display identifier * @return string representation of display identifier, NULL if invalid * * @ingroup api_display_spec */ const char * ddca_did_repr( DDCA_Display_Identifier did); // // Display Reference // /** @deprecated use #ddca_get_display_ref() * Gets a display reference for a display identifier. * Normally, this is a permanently allocated #DDCA_Display_Ref * created by monitor detection and does not need to be freed. * Use #ddca_free_display_ref() to safely free. * * @param[in] did display identifier * @param[out] dref_loc where to return display reference * @retval 0 success * @retval DDCRC_ARG did is not a valid display identifier handle * @retval DDCRC_INVALID_DISPLAY display not found * * @ingroup api_display_spec */ // __attribute__ ((deprecated ("use ddca_get_display_ref()"))) DDCA_Status ddca_create_display_ref( DDCA_Display_Identifier did, DDCA_Display_Ref* dref_loc); /** Gets a display reference for a display identifier. * This is a permanently allocated #DDCA_Display_Ref * created by monitor detection and does not need to be freed. * * @param[in] did display identifier * @param[out] dref_loc where to return display reference * @retval 0 success * @retval DDCRC_ARG did is not a valid display identifier handle * @retval DDCRC_INVALID_DISPLAY display not found * * @since 0.9.5 * @ingroup api_display_spec */ DDCA_Status ddca_get_display_ref( DDCA_Display_Identifier did, DDCA_Display_Ref* dref_loc); /** Checks whether a #DDCA_Display_Ref is valid * * @param dref display reference to validate * @param require_not_asleep include check for DPMS sleep state * @retval DDCRC_OK * @retval DDCRC_ARG dref == NULL or does not point to a valid DDCA_Display_Ref * @retval DDCRC_INTERNAL_ERROR dref->drm_connector == NULL * @retval DDCRC_DISCONNECTED monitor has been disconnected * @retval DDCRC_DPMS_ASLEEP monitor in a DPMS sleep state * @retval DDCRC_INVALID_DISPLAY not found * * @since 2.1.0 */ DDCA_Status ddca_validate_display_ref( DDCA_Display_Ref dref, bool require_not_asleep); /** Returns a string representation of a display reference * * The returned value is valid until the next call to this function on * the current thread. * * @param[in] dref display reference * @return string representation of display reference, NULL if invalid */ const char * ddca_dref_repr( DDCA_Display_Ref dref); /** Writes a report on the specified display reference to the current FOUT device * * @param[in] dref display reference * @param[in] depth logical indentation depth * * @ingroup api_display_spec */ void ddca_dbgrpt_display_ref( DDCA_Display_Ref dref, int depth); // // Display Handle // /** Open a display * * @param[in] ddca_dref display reference for display to open * @param[in] wait if true, wait if display locked by another thread * @param[out] ddca_dh_loc where to return display handle * @return status code * * Fails if display is already opened by another thread. * @ingroup api_display_spec */ DDCA_Status ddca_open_display2( DDCA_Display_Ref ddca_dref, bool wait, DDCA_Display_Handle * ddca_dh_loc); /** Close an open display * * @param[in] ddca_dh display handle, if NULL do nothing * @retval DDCRC_OK close succeeded, or ddca_dh == NULL * @retval DDCRC_ARG invalid handle * @return -errno from underlying OS close() * * @ingroup api_display_spec */ DDCA_Status ddca_close_display( DDCA_Display_Handle ddca_dh); /** Returns a string representation of a display handle. * The string is valid until until the handle is closed. * * @param[in] ddca_dh display handle * @return string representation of display handle, NULL if * argument is NULL or not a display handle * * @ingroup api_display_spec */ const char * ddca_dh_repr( DDCA_Display_Handle ddca_dh); // CHANGE NAME? /** Returns the display reference for display handle. * * @param[in] ddca_dh display handle * @return #DDCA_Display_Ref of the handle, * NULL if invalid display handle * * @since 0.9.0 */ DDCA_Display_Ref ddca_display_ref_from_handle( DDCA_Display_Handle ddca_dh); // // Monitor Capabilities // /** Retrieves the capabilities string for a monitor. * * @param[in] ddca_dh display handle * @param[out] caps_loc address at which to return pointer to capabilities string. * @return status code * * It is the responsibility of the caller to free the returned string. */ DDCA_Status ddca_get_capabilities_string( DDCA_Display_Handle ddca_dh, char** caps_loc); /** Parse the capabilities string. * * @param[in] capabilities_string unparsed capabilities string * @param[out] parsed_capabilities_loc address at which to return pointer to newly allocated * #DDCA_Capabilities struct * @return status code * * It is the responsibility of the caller to free the returned struct * using ddca_free_parsed_capabilities(). * * This function currently parses the VCP feature codes and MCCS version. * It could be extended to parse additional information such as cmds if necessary. */ DDCA_Status ddca_parse_capabilities_string( char * capabilities_string, DDCA_Capabilities ** parsed_capabilities_loc); /** Frees a DDCA_Capabilities struct * * @param[in] parsed_capabilities pointer to struct to free, * does nothing if NULL. */ void ddca_free_parsed_capabilities( DDCA_Capabilities * parsed_capabilities); /** Reports the contents of a DDCA_Capabilities struct. * * The report is written to the current FOUT location. * * If the current output level is #DDCA_OL_VERBOSE, additional * information is written, including command codes. * * @param[in] parsed_capabilities pointer to #DDCA_Capabilities struct * @param[in] ddca_dref display reference, may be NULL * @param[in] depth logical indentation depth * * @remark * If ddca_dref is not NULL, feature value names will reflect any loaded monitor definition files * @since 0.9.3 */ DDCA_Status ddca_report_parsed_capabilities_by_dref( DDCA_Capabilities * parsed_capabilities, DDCA_Display_Ref ddca_dref, int depth); /** Reports the contents of a DDCA_Capabilities struct. * * The report is written to the current FOUT location. * * If the current output level is #DDCA_OL_VERBOSE, additional * information is written, including command codes. * * @param[in] parsed_capabilities pointer to #DDCA_Capabilities struct * @param[in] ddca_dh display handle, may be NULL * @param[in] depth logical indentation depth * @retval 0 success * @retval DDCRC_ARG invalid display handle * * @remark * If ddca_dh is not NULL, feature value names will reflect any loaded monitor definition files * @since 0.9.3 */ DDCA_Status ddca_report_parsed_capabilities_by_dh( DDCA_Capabilities * p_caps, DDCA_Display_Handle ddca_dh, int depth); /** Reports the contents of a DDCA_Capabilities struct. * * The report is written to the current FOUT location. * * If the current output level is #DDCA_OL_VERBOSE, additional * information is written, including command codes. * * @param[in] parsed_capabilities pointer to #DDCA_Capabilities struct * @param[in] ddca_dref display reference * @param[in] depth logical indentation depth * * @remark * Any user supplied feature definitions for the monitor are ignored. */ void ddca_report_parsed_capabilities( DDCA_Capabilities * parsed_capabilities, int depth); /** Returns the VCP feature codes defined in a * parsed capabilities record as a #DDCA_Feature_List * * @param[in] parsed_caps parsed capabilities * @return bitfield of feature ids * @since 0.9.0 */ DDCA_Feature_List ddca_feature_list_from_capabilities( DDCA_Capabilities * parsed_caps); // // MCCS Version Specification // /** Gets the MCCS version of a monitor. * * @param[in] ddca_dh display handle * @param[out] p_vspec where to return version spec * @return DDCRC_ARG invalid display handle * * @remark Returns version 0.0 (#DDCA_VSPEC_UNKNOWN) if feature DF cannot be read */ DDCA_Status ddca_get_mccs_version_by_dh( DDCA_Display_Handle ddca_dh, DDCA_MCCS_Version_Spec* p_vspec); // // VCP Feature Metadata // /** Controls whether user defined features (aka dynamic features) are supported. * * @param[in] onoff true/false * @return prior value * * @since 0.9.3 */ bool ddca_enable_udf(bool onoff); /** Query whether user defined features (aka dynamic features) are supported. * * @retval true UDF enabled * @retval false UDF disabled * * @since 0.9.3 */ bool ddca_is_udf_enabled(void); /** Loads any user supplied feature definition files for the specified * display. Does nothing if they have already been loaded. * * @param[in] ddca_dref display reference * @return status code * * It is not a error if no feature definition file is found, * Feature definition file errors can be retrieved using #ddca_get_error_detail(). * * @remark * Loading feature definition files is a separate operation because errors * are possible when reading and processing the definitions. * @since 0.9.3 */ DDCA_Status ddca_dfr_check_by_dref(DDCA_Display_Ref ddca_dref); /** Loads any user supplied feature definition files for the specified * display. Does nothing if they have already been loaded. * * @param[in] ddca_dh display handle * @return status code * * See #ddca_dfr_check_by_dref() for detailed documentation. * * @since 0.9.3 */ DDCA_Status ddca_dfr_check_by_dh(DDCA_Display_Handle ddca_dh); /** Gets metadata for a VCP feature. * * @param[in] vspec VCP version * @param[in] feature_code VCP feature code * @param[in] create_default_if_not_found * @param[out] meta_loc return pointer to metadata here * @return status code * @retval DDCRC_ARG invalid display handle * @retval DDCRC_UNKNOWN_FEATURE unrecognized feature code and * !create_default_if_not_found * * It is the responsibility of the caller to free the returned DDCA_Feature_Metadata instance. * * @remark * Note that VCP characteristics (C vs NC, RW vs RO, etc) can vary by MCCS version. * @remark * Only takes into account VCP version. Useful for reporting display agnostic * feature information. For display sensitive feature information, i.e. taking * into account the specific monitor model, use #ddca_get_feature_metdata_by_dref() * or #ddca_get_feature_metadata_by_dh(). * * @since 0.9.3 */ DDCA_Status ddca_get_feature_metadata_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, bool create_default_if_not_found, DDCA_Feature_Metadata ** meta_loc); /** Gets metadata for a VCP feature. * * Note that VCP characteristics (C vs NC, RW vs RO, etc) can vary by MCCS version. * * @param[in] ddca_dref display reference * @param[in] feature_code VCP feature code * @param[in] create_default_if_not_found * @param[out] meta_loc return pointer to metadata here * @return status code * @retval DDCRC_ARG invalid display reference * @retval DDCRC_UNKNOWN_FEATURE unrecognized feature code and * !create_default_if_not_found * * It is the responsibility of the caller to free the returned DDCA_Feature_Metadata instance. * * @remark * This function first checks if there is a user supplied feature definition * for the monitor. If not, it looks up feature metadata based on the * VCP version of the monitor. * @remark * Note that feature characteristics (C vs NC, RW vs RO, etc) can vary by MCCS version. * @since 0.9.3 */ DDCA_Status ddca_get_feature_metadata_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, bool create_default_if_not_found, DDCA_Feature_Metadata ** meta_loc); /** Gets metadata for a VCP feature. * * @param[in] ddca_dh display handle * @param[in] feature_code VCP feature code * @param[in] create_default_if_not_found * @param[out] meta_loc return pointer to metadata here * @return status code * @retval DDCRC_ARG invalid display handle * @retval DDCRC_UNKNOWN_FEATURE unrecognized feature code and * !create_default_if_not_found * * It is the responsibility of the caller to free the returned DDCA_Feature_Metadata instance. * * @remark * This function first checks if there is a user supplied feature definition * for the monitor. If not, it looks up feature metadata based on the * VCP version of the monitor. * @remark * Note that feature characteristics (C vs NC, RW vs RO, etc) can vary by MCCS version. * @since 0.9.3 */ DDCA_Status ddca_get_feature_metadata_by_dh( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Handle ddca_dh, bool create_default_if_not_found, DDCA_Feature_Metadata ** meta_loc); /** Frees a #DDCA_Feature_Metadata instance * * @param[in] metadata pointer to instance * @retval 0 normal * @since 0.9.3 * * @remark * It is not an error if the ***metadata*** pointer argument is NULL * @remark * This is a convenience function. */ void ddca_free_feature_metadata(DDCA_Feature_Metadata * metadata); /** Gets the VCP feature name. If different MCCS versions use different names * for the feature, this function makes a best guess. * * @param[in] feature_code feature code * @return pointer to feature name (do not free), NULL if unknown feature code * * @remark * Since no specific display is indicated, this function ignores user defined * monitor feature information. */ const char * ddca_get_feature_name(DDCA_Vcp_Feature_Code feature_code); /** Convenience function that searches a Feature Value Table for a * value and returns the corresponding name. * * @param[in] feature_value_table pointer to first entry of table * @param[in] feature_value value to search for * @param[out] value_name_loc where to return pointer to name * @retval DDCRC_OK value found * @retval DDCRC_NOT_FOUND value not found * * @remark * The value returned in **value_name_loc** is a pointer into the table * data structure. Do not free. * * @remark * This is a convenience function. */ DDCA_Status ddca_get_simple_nc_feature_value_name_by_table( DDCA_Feature_Value_Entry * feature_value_table, uint8_t feature_value, char** value_name_loc); /** Outputs a debugging report of the @DDCA_Feature_Metadata data structure. * * @param[in] md pointer to @DDCA_Feature_Metadata instance * @param[in] depth logical indentation depth */ void ddca_dbgrpt_feature_metadata( DDCA_Feature_Metadata * md, int depth); // // Miscellaneous Monitor Specific Functions // /** Shows information about a display, specified by a #Display_Ref * * Output is written using report functions * * @param[in] dref pointer to display reference * @param[in] depth logical indentation depth * @retval DDCRC_ARG invalid display ref * @retval 0 success * * @remark * The detail level shown is controlled by the output level setting * for the current thread. * * @since 0.9.0 */ DDCA_Status ddca_report_display_by_dref(DDCA_Display_Ref dref, int depth); // // Feature Lists // // Specifies a collection of VCP features as a 256 bit array of flags. // /** Empty feature list * @since 0.9.0 */ extern const DDCA_Feature_List DDCA_EMPTY_FEATURE_LIST; /** Returns feature list symbolic name (for debug messages) * * @param[in] feature_set_id * @return symbolic name (do not free) * * @remark * This is a convenience function. */ const char * ddca_feature_list_id_name( DDCA_Feature_Subset_Id feature_set_id); /** Given a feature set id, returns a #DDCA_Feature_List specifying all the * feature codes in the set. * * @param[in] feature_set_id * @param[in] dref display reference * @param[in] include_table_features if true, Table type features are included * @param[out] points to feature list to be filled in * @retval DDCRC_ARG invalid display reference * @retval DDCRC_OK success * * @since 0.9.0 */ DDCA_Status ddca_get_feature_list_by_dref( DDCA_Feature_Subset_Id feature_set_id, DDCA_Display_Ref dref, bool include_table_features, DDCA_Feature_List* feature_list_loc); /** Empties a #DDCA_Feature_List * * @param[in] vcplist pointer to feature list * * @remark * Alternatively, just set vcplist = DDCA_EMPTY_FEATURE_LIST * @remark * This is a convenience function. * @since 0.9.0 */ void ddca_feature_list_clear( DDCA_Feature_List* vcplist); /** Adds a feature code to a #DDCA_Feature_List * * @param[in] vcplist pointer to feature list * @param[in] vcp_code VCP feature code * @return modified feature list * * @remark * The feature list is modified in place and also returned. * * @since 0.9.0 */ DDCA_Feature_List ddca_feature_list_add( DDCA_Feature_List* vcplist, uint8_t vcp_code); /** Tests if a #DDCA_Feature_List contains a VCP feature code * * @param[in] vcplist feature list * @param[in] vcp_code VCP feature code * @return true/false * * @since 0.9.0 */ bool ddca_feature_list_contains( DDCA_Feature_List vcplist, uint8_t vcp_code); /** Tests if 2 feature lists are equal. * * @param[in] vcplist1 first feature list * @param[in] vcplist2 second feature list * @return true if they contain the same features, false if not * * @remark * The input feature lists are not modified. * @since 0.9.9 */ bool ddca_feature_list_eq( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2); /** Creates a union of 2 feature lists. * * @param[in] vcplist1 first feature list * @param[in] vcplist2 second feature list * @return feature list in which a feature is set if it is in either * of the 2 input feature lists * * @remark * The input feature lists are not modified. * @since 0.9.0 */ DDCA_Feature_List ddca_feature_list_or( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2); /** Creates the intersection of 2 feature lists. * * @param[in] vcplist1 first feature list * @param[in] vcplist2 second feature list * @return feature list in which a feature is set if it is in both * of the 2 input feature lists * * @remark * The input feature lists are not modified. * @since 0.9.0 */ DDCA_Feature_List ddca_feature_list_and( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2); /** Returns a feature list consisting of all the features in the * first list that are not in the second. * * @param[in] vcplist1 first feature list * @param[in] vcplist2 second feature list * @return feature list in which a feature is set if it is in **vcplist1** but * not **vcplist2** * * @remark * The input feature lists are not modified. * @since 0.9.0 */ DDCA_Feature_List ddca_feature_list_and_not( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2); /** Returns the number of features in a feature list * * @param[in] feature_list feature list * @return number of features, 0 if feature_list == NULL * * @since 0.9.0 */ int ddca_feature_list_count( DDCA_Feature_List feature_list); /** Returns a string representation of a feature list as a * sequence of 2 character hex values. * * @param[in] feature_list feature list * @param[in] value_prefix precede each value with this string, e.g. "0x" * if NULL, then no preceding string * @param[in] sepstr separator string between pair of values, e.g. ", " * if NULL, then no separator string * @return string representation; The value is valid until the next call * to this function in the current thread. Caller should not free. * * @since 0.9.0 */ const char * ddca_feature_list_string( DDCA_Feature_List feature_list, const char * value_prefix, const char * sepstr); // // GET AND SET VCP VALUES // /* * The API for getting and setting VCP values is doubly specified, * with both functions specific to Non-Table and Table values, * and more generic functions that can handle values of any type. * * As a practical matter, Table type features have not been observed * on any monitors (as of 3/2018), and applications can probably * safely be implemented using only the Non-Table APIs. * * Note that the functions for #DDCA_Any_Vcp_Value replace those * that previously existed for #DDCA_Single_Vcp_Value. */ // // Free VCP Feature Value // // Note there is no function to free a #Non_Table_Vcp_Value, since // this is a fixed size struct always allocated by the caller. // /** Frees a #DDCA_Table_Vcp_Value instance. * * @param[in] table_value * * @remark * Was previously named **ddca_free_table_value_response(). * @since 0.9.0 */ void ddca_free_table_vcp_value( DDCA_Table_Vcp_Value * table_value); /** Frees a #DDCA_Any_Vcp_Value instance. * * @param[in] valrec pointer to #DDCA_Any_Vcp_Value instance * @since 0.9.0 */ void ddca_free_any_vcp_value( DDCA_Any_Vcp_Value * valrec); // // Get VCP Feature Value // /** Gets the value of a non-table VCP feature. * * @param[in] ddca_dh display handle * @param[in] feature_code VCP feature code * @param[out] valrec pointer to response buffer provided by the caller, * which will be filled in * @return status code * * @remark * If the returned status code is other than **DDCRC_OK**, a detailed * error report can be obtained using #ddca_get_error_detail() * @remark * Renamed from **ddca_get_nontable_vcp_value()** * @since 0.9.0 */ DDCA_Status ddca_get_non_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Non_Table_Vcp_Value* valrec); /** Gets the value of a table VCP feature. * * @param[in] ddca_dh display handle * @param[in] feature_code VCP feature code * @param[out] table_value_loc address at which to return the value * @return status code * * @remark * If the returned status code is other than **DDCRC_OK**, a detailed * error report can be obtained using #ddca_get_error_detail() * @note * Implemented, but untested */ DDCA_Status ddca_get_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Table_Vcp_Value ** table_value_loc); /** Gets the value of a VCP feature of any type. * * @param[in] ddca_dh display handle * @param[in] feature_code VCP feature code * @param[in] value_type value type * @param[out] valrec_loc address at which to return a pointer to a newly * allocated #DDCA_Any_Vcp_Value * @return status code * * @remark * If the returned status code is other than **DDCRC_OK**, a detailed * error report can be obtained using #ddca_get_error_detail() * @remark * Replaces **ddca_get_any_vcp_value() * * @since 0.9.0 */ DDCA_Status ddca_get_any_vcp_value_using_explicit_type( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Vcp_Value_Type value_type, DDCA_Any_Vcp_Value ** valrec_loc); /** Gets the value of a VCP feature of any type. * The type is determined by using ddcutil's internal * feature description table. * * Note that this function cannot be used for manufacturer-specific * feature codes (i.e. those in the range xE0..xFF), since ddcutil * does not know their type information. Nor can it be used for * unrecognized feature codes. * * @param[in] ddca_dh display handle * @param[in] feature_code VCP feature code * @param[out] valrec_loc address at which to return a pointer to a newly * allocated #DDCA_Any_Vcp_Value * @return status code * * @remark * It an error to call this function for a manufacturer-specific feature or * an unrecognized feature. * @remark * If the returned status code is other than **DDCRC_OK**, a detailed * error report can be obtained using #ddca_get_error_detail() */ DDCA_Status ddca_get_any_vcp_value_using_implicit_type( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Any_Vcp_Value ** valrec_loc); /** Returns a formatted representation of a table VCP value. * It is the responsibility of the caller to free the returned string. * * @param[in] feature_code VCP feature code * @param[in] dref display reference * @param[in] table_value table VCP value * @param[out] formatted_value_loc address at which to return the formatted value. * @return status code, 0 if success * @since 0.9.0 */ DDCA_Status ddca_format_table_vcp_value_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, DDCA_Table_Vcp_Value * table_value, char ** formatted_value_loc); /** Returns a formatted representation of a non-table VCP value. * It is the responsibility of the caller to free the returned string. * * @param[in] feature_code VCP feature code * @param[in] dref display reference * @param[in] valrec non-table VCP value * @param[out] formatted_value_loc address at which to return the formatted value. * @return status code, 0 if success * @since 0.9.0 */ DDCA_Status ddca_format_non_table_vcp_value_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref dref, DDCA_Non_Table_Vcp_Value * valrec, char ** formatted_value_loc); /** Returns a formatted representation of a VCP value of any type * It is the responsibility of the caller to free the returned string. * * @param[in] feature_code VCP feature code * @param[in] dref display reference * @param[in] valrec non-table VCP value * @param[out] formatted_value_loc address at which to return the formatted value. * @return status code, 0 if success * @since 0.9.0 */ DDCA_Status ddca_format_any_vcp_value_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref dref, DDCA_Any_Vcp_Value * valrec, char ** formatted_value_loc); // // Set VCP value // /** Sets a non-table VCP value by specifying it's high and low bytes individually. * * @param[in] ddca_dh display handle * @param[in] feature_code feature code * @param[in] hi_byte high byte of new value * @param[in] lo_byte low byte of new value * @return status code */ DDCA_Status ddca_set_non_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, uint8_t hi_byte, uint8_t lo_byte ); /** Sets a Table VCP value. * * @param[in] ddca_dh display handle * @param[in] feature_code feature code * @param[in] new_value value to set * @return status code * @since 0.9.0 */ DDCA_Status ddca_set_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Table_Vcp_Value * new_value); /** Sets a VCP value of any type. * * @param[in] ddca_dh display handle * @param[in] feature_code feature code * @param[in] new_value value to set * @return status code * @since 0.9.0 */ DDCA_Status ddca_set_any_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Any_Vcp_Value * new_value); // // Get or set multiple values // // These functions provide an API version of the **dumpvcp** and **loadvcp** // commands. // /** Returns a string containing monitor identification and values * for all detected features that should be saved when a monitor is * calibrated and restored when the calibration is applied. * * @param[in] ddca_dh display handle * @param[out] profile_values_string_loc address at which to return string, * caller is responsible for freeing * @return status code */ DDCA_Status ddca_get_profile_related_values( DDCA_Display_Handle ddca_dh, char** profile_values_string_loc); /** Sets multiple feature values for a specified monitor. * The monitor identification and feature values are * encoded in the string. * * @param[in] ddca_dh display handle * @param[in] profile_values_string string containing values * @return status code * * @remark * If **ddca_dh** is NULL, this function opens the first display * that matches the display identifiers in the **profile_values_string**. * If **ddca_dh** is non-NULL, then the identifiers in * **profile_values_string** must be consistent with the open display. * @remark * The non-NULL case exists to handle the unusual situation where multiple * displays have the same manufacturer, model, and serial number, * perhaps because the EDID has been cloned. * @remark * If the returned status code is **DDCRC_BAD_DATA** (others?), a detailed * error report can be obtained using #ddca_get_error_detail() */ DDCA_Status ddca_set_profile_related_values( DDCA_Display_Handle ddca_dh, char * profile_values_string); // // Report display status changes // /** Registers a function to be called called when a change in display status is * detected. It is not an error if the function is already registered. * * @param[in] func function of type #DDCA_Display_Detection_Callback_Func() * @return DDCRC_OK * @retval DDCRC_INVALID_OPERATION ddcutil not built with UDEV support, * or not all video devices support DRM * * @since 2.1.0 */ DDCA_Status ddca_register_display_status_callback(DDCA_Display_Status_Callback_Func func); /** Removes a function from the list of registered callbacks * * @param[in] func function that has already been registered * @retval DDCRC_OK function removed from list * @retval DDCRC_INVALID_OPERATION ddcutil not built with UDEV support, * or not all video devices support DRM * @retval DDCRC_NOT_FOUND function not registered * * @since 2.1.0 */ DDCA_Status ddca_unregister_display_status_callback(DDCA_Display_Status_Callback_Func func); /** Returns the name of a #DDCA_Display_Event_Class * * @param event_class event class id * @return printable name * * @remark * The value returned exists in an internal ddcutil table. * Caller should not free. * * @since 2.1.0 */ const char * ddca_display_event_class_name(DDCA_Display_Event_Class event_class); /** Returns the name of a #DDCA_Display_Event_Type * * @param event_type event type id * @return printable event type name * * @remark * The value returned exists in an internal ddcutil table. * Caller should not free. * * @since 2.1.0 */ const char * ddca_display_event_type_name(DDCA_Display_Event_Type event_type); /** Start the thread watching for display status changes. * * @param enabled_clases event classes to watch * @retval DDCRC_OK * #retval DDCRC_ARG no event classes or invalid event classes specified * @retval DDCRC_INVALID_OPERATION watch thread already running * @retval DDCRC_INVALID_OPERATION not all video drivers support DRM * @retval DDCRC_UNIMPLEMENTED watching for DPMS changes unimplemented * * The only valid event_type value is DDCA_EVENT_CLASS_DISPLAY_CONNECTION. * DDCA_EVENT_CLASS_ALL is equivalent to DDCA_EVENT_CLSS_DISPLAY_CONNECTION. */ DDCA_Status ddca_start_watch_displays(DDCA_Display_Event_Class enabled_classes); /** Terminate the thread that watches for display status changes. * * This function is a hack. Without it, the thread can * continue running even though the application has exited. * * @param wait Wait for watch thread to actually terminate * @retval DDCRC_OK * @retval DDCRC_INVALID_OPERATION watch thread not executing * * If this function is being called as part of termination * by the client, there's no need to wait for the watch thread * to actually finish. * * @since 2.1.0 */ DDCA_Status ddca_stop_watch_displays(bool wait); /** If the watch thread is currently executing returns, reports the * currently active display event classes as a bit flag. * * @param classes_loc where to return bit flag * @retval DDCRC_OK * @retval DDCRC_INVALID_OPERATION watch thread not executing */ DDCA_Status ddca_get_active_watch_classes(DDCA_Display_Event_Class * classes_loc); /** Retrieve current display watch settings into a buffer provided * by the caller. * * @param settings_buffer pointer to caller buffer * @retval DDCRC_OK * @retval DDCRC_UNINITIALIZED * * @since 2.2.0 */ DDCA_Status ddca_get_display_watch_settings(DDCA_DW_Settings * settings_buffer); /** Modify the current display watch settings. * * @param settings_buffer pointer to settings buffer * @retval DDCRC_OK * @retval DDCRC_ARG * @retval DDCRC_UNINITIALIZED * * @since 2.2.0 */ DDCA_Status ddca_set_display_watch_settings(DDCA_DW_Settings * settings_buffer); #ifdef __cplusplus } #endif #endif /* DDCUTIL_C_API_H_ */ ddcutil-2.2.0/src/Makefile.am0000644000175000001440000002721214754467221011463 # src/Makefile.am DIST_SUBDIRS = app_ddcutil app_sysenv base cmdline ddc dw dynvcp i2c libmain sysfs sample_clients test usb usb_util util vcp # contain only header files: EXTRA_DIST = bsd private public SUBDIRS = util usb_util base vcp sysfs i2c usb dynvcp ddc dw if INCLUDE_TESTCASES_COND SUBDIRS += test endif if ENABLE_SHARED_LIB_COND SUBDIRS += libmain endif SUBDIRS += app_sysenv app_ddcutil cmdline . sample_clients MOSTLYCLEANFILES = CLEANFILES = DISTCLEANFILES = publc/ddcutil_macros.h # todo: factor out swig # todo: fails if swig/.libs doesn't exist # rm -rf swig/ddc_swig_wrap.c swig/ddc_swig.py swig/ddc_swig.pyc # Plo files in deps directories are automatically included in generated Makefiles for some reason # test -z `find . -name ".deps" -type d` || rm -rf `find . -name ".deps" -type d` # For conditionally included files, e.g. those in usb_util, make clean does not delete # the .lo files. Hence the instructions here to delete all of them # Fails: test: too many arguments: # test -z `find . -name "*lo" -type f` || rm `find . -name "*lo" -type f` # distclean-local => clean-local => mostlyclean->local mostlyclean-local: @echo "(src/Makefile) mostlyclean-local" clean-local: @echo "(src/Makefile) clean-local" find . -name "*plist" -type d -exec ls -ld {} \; rm -rf `find . -name "*plist" -type d` find . -name ".libs" -type d -exec ls -ld {} \; test -z `find . -name "*expand" -type f` || rm `find . -name "*expand" -type f` find . -name "*.lo" -type f -exec rm -fv {} \; find . -name "*.o" -type f -exec rm -fv {} \; find . -name ".deps" -type d -exec ls -ld {} \; find . -path "*/.deps/*" -exec ls -l {} \; distclean-local: @echo "(src/Makefile) distclean-local" find . -name ".libs" -type d -exec ls -ld {} \; rm -rf `find . -name "*plist" -type d` maintainerclean-local: @echo "(src/Makefile) maintainerclean-local" # # Execuatables # bin_PROGRAMS = ddcutil ddcutil_SOURCES = if ENABLE_SHARED_LIB_COND lib_LTLIBRARIES = libddcutil.la libddcutil_la_SOURCES = endif # # Intermediate libraries built in this directory # # Convenience library containing code shared between ddcutil executable and libddcutil shared library noinst_LTLIBRARIES = libcommon.la libcommon_la_SOURCES = # Convenience library to collect code used only in ddcutil executable noinst_LTLIBRARIES += libapp.la libapp_la_SOURCES = if ENABLE_SHARED_LIB_COND include_HEADERS = \ public/ddcutil_macros.h \ public/ddcutil_status_codes.h \ public/ddcutil_types.h \ public/ddcutil_c_api.h endif # Notes: # 1) Without -prune option, the following line fails because list of file is archived internally, get file not found errors after remove # find $(top_distdir) -name ".deps" -exec rm -rf {} \; # 2) Piping to xargs fails if there are no files, which occurs if "make dist" is invoked without anything having been built. # find $(top_distdir) -name ".deps" | xargs rm # 3) Why explicit copy of .h files? # 4) find statements in src/usb_util/Makefile.am find nothing, but those here work. why? dist-hook: @echo "(src/Makefile) Executing hook dist-hook. top_distdir=$(top_distdir) distdir=$(distdir).." find . -type f | grep \.h$ | xargs -i cp --parents "{}" $(distdir) find $(distdir) -name ".deps" -type d -prune -exec rm -rfv {} \; find $(distdir) -name ".libs" -type d -prune -exec rm -rfv {} \; find $(distdir) -name "*.lo" -exec rm -v {} \; find $(distdir) -name "*.o" -exec rm -v {} \; rm -rfv $(distdir)/swig/pyenv rm -rfv $(distdir)/swig/__pycache__ rm -fv ${distdir}/public/ddcutil_macros.h find ${distdir} -name adl_archived -type d -prune -exec rm -rfv {} \; find ${distdir} -name "*old" -type d -prune -exec rm -rfv {} \; find ${distdir} -name "*new" -type d -prune -exec rm -rfv {} \; # # C Pre-Processor Flags # # GLIB_CFLAGS contains output of pkgconfig --cflags glib-2.0 AM_CPPFLAGS= \ $(GLIB_CFLAGS) \ $(XRANDR_CFLAGS) \ $(LIBUSB_CFLAGS) \ -I$(srcdir) \ -I$(srcdir)/public # # Compiler flags # # unused-result defined since at least gcc 5 # format-security defined since gcc 2.95.3, Clang 4.0.0 AM_CFLAGS = -Wall -std=c11 -Werror=unused-result -Wformat-security # Distributing -Werror is bad programming practice. It can result in build failure # on an external site having a different compiler, compiler version, or configuration. # See comments and answers in # https://stackoverflow.com/questions/10275554/how-to-disable-specified-warning-for-specified-file-while-using-autotools # 10/1/2022: now enabled by WARNINGS_ARE_ERRORS_COND in individual Makefile.am # AM_CFLAGS += -Werror # AM_CFLAGS += -Wpedantic # -pedantic issues warnings re code that doesn't conform to ISO C # In particular, -m modifier on sscanf is a POSIX extension, not ISO C # Also flags PROGRAM_LOGIC_ERROR() # If combined with -Werror, will cause some module compilations to fail # AM_CFLAGS += -H # Report header file dependencies # see https://community.ibm.com/community/user/ibmz-and-linuxone/blogs/colton-cox1/2020/03/12/ztpf-cc-performance-hints AM_CFLAGS += -fno-common AM_CFLAGS += -Wimplicit-function-declaration # Will flag glib's use of _Static_assert, which is not in the C99 standard, # but which is in gcc as of 4.6, also other constructs # AM_CFLAGS += -Wc99-c11-compat # Option added in Clang 12, if set causes warnings in WITH_VALIDATED_DH*() macros etc. # The option does not exist in gcc. # The "-Wno-" option form is ignored by gcc, but should be respected when compiling # in an environment, e.g. termux, where this option is enabled by default. AM_CFLAGS += -Wno-compound-token-split-by-macro # https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++ # AM_CFLAGS += -Wformat -Wformat=2 AM_CFLAGS += -Wimplicit-fallthrough # too many errors to be worth fixing # AM_CFLAGS += -Wconversion AM_CFLAGS += -D_GLIBCXX_ASSERTIONS AM_CFLAGS += -Werror=implicit -Werror=incompatible-pointer-types AM_CFLAGS += -Werror=int-conversion if ENABLE_CALLGRAPH_COND AM_CFLAGS += -fdump-rtl-expand endif if ASAN_COND # -fsanitize=address required for both compile and link, what about other -f options? AM_CFLAGS += -fsanitize=address -fsanitize-address-use-after-scope -fno-omit-frame-pointer -g # does this go here or as and environment variable at runtime? # for -fsanitize-address-use-after-scope ASAN_OPTIONS = strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1 ASAN_OPTIONS += verbosity=1 endif # AM_CFLAGS += $(PYTHON_CPPFLAGS) AM_CFLAGS += -fPIC AM_CFLAGS += -D_GNU_SOURCE # unnessary, will use AM_CFLAGS if xxx_CFLAGS undefined # ddcutil_CFLAGS = $(AM_CFLAGS) # libcommon_la_CFLAGS = $(AM_CFLAGS) # libddcutil_la_CFLAGS = $(AM_CFLAGS) # Makefile:420: *** Recursive variable 'AM_CFLAGS' references itself (eventually). Stop. # export AM_CFLAGS AM_CFLAGS_STD=$(AM_CFLAGS) export AM_CFLAGS_STD # # Link convenience library libcommon.la # # Be careful about library ordering. # A library must be listed after any libraries that depend on it # libcommon_la_LIBADD = \ dw/libdw.la \ ddc/libddc.la \ dynvcp/libdynvcp.la \ i2c/libi2c.la \ sysfs/libsysfs.la \ vcp/libvcp.la \ cmdline/libcmdline.la \ base/libbase.la \ util/libutil.la if ENABLE_USB_COND libcommon_la_LIBADD += \ usb_util/libusbutil.la \ usb/libusb.la endif if USE_X11_COND libcommon_la_LIBADD += $(LIBX11_LIBS) $(XEXT_LIBS) $(XRANDR_LIBS) endif # if ENABLE_YAML_COND # libcommon_la_LIBADD += $(YAML_LIBS) # endif libcommon_la_LIBADD += \ $(JANSSON_LIBS) \ $(GLIB_LIBS) \ $(UDEV_LIBS) \ $(LIBUSB_LIBS) # for smbus functions: # libcommon_la_LIBADD += -li2c # # Link convenience library libapp # libapp_la_LIBADD = \ app_ddcutil/libappddcutil.la if ENABLE_ENVCMDS_COND libapp_la_LIBADD += \ app_sysenv/libappsysenv.la endif if INCLUDE_TESTCASES_COND libapp_la_LIBADD += \ test/libtestcases.la endif if USE_LIBDRM_COND libcommon_la_LIBADD += $(LIBDRM_LIBS) endif # # Link ddcutil executable # # ddcutil statically links libcommon, rather than using libddcutil.so # so it needs LDADD references to external libraries as well ddcutil_LDADD = \ libapp.la \ libcommon.la #needed? ddcutil_LDFLAGS = ddcutil_LDFLAGS += -pie # -export-dynamic needed for failsim ddcutil_LDFLAGS += -export-dynamic if ASAN_COND ddcutil_LDFLAGS += -fsanitize=address # needed? ddcutil_LDFLAGS += -fsanitize-address-use-after-scope -fno-omit-frame-pointer ddcutil_LDADD += -lasan endif # # Link libddcutil executable # if ENABLE_SHARED_LIB_COND # libddcutil_la_LIBADD = -lz libddcutil_la_LIBADD = $(ZLIB_LIBS) libddcutil_la_LIBADD += libcommon.la libmain/libsharedlib.la libddcutil_la_LDFLAGS = # Note -export-dynamic not required for failsim, don't need to append # libddcutil_la_LDFLAGS += -export-dynamic libddcutil_la_LDFLAGS += -export-symbols-regex '(^DDCA_|^ddc[ags]_[^_])' libddcutil_la_LDFLAGS += -version-info '@LT_CURRENT@:@LT_REVISION@:@LT_AGE@' libddcutil_la_LDFLAGS += -pie if ASAN_COND libddcutil_la_LDFLAGS += -fsanitize=address # needed? libddcutil_la_LDFLAGS += -fsanitize-address-use-after-scope -fno-omit-frame-pointer # doesn't work: # libddcutil_la_LDFLAGS += -static-libasan libddcutil_la_LIBADD += -lasan endif # doesn't prevent creation of .la # try disabling to create libddcutil.a - doesnt do it libddcutil_la_LDFLAGS += --disable-static endif all-local: @echo "(src/Makefile) all-local" rm -fv base/build_details.h # debug-install-hook: # ls -ld $(DESTDIR)$(libdir) # ls -l $(DESTDIR)$(libdir)/*la # @echo " pythondir = $(pythondir)" # @echo " pyexecdir = $(pyexecdir)" # @echo $(DESTDIR)$(libdir) install-exec-local: @echo "(src/Makefile) Executing install-exec-local ..." @echo "(src/Makefile) install-exec-local done" install-exec-hook: @echo "(src/Makefile) Executing install-exec-hook ..." rm -f $(DESTDIR)$(libdir)/libddcutil.la # rm -f $(DESTDIR)$(libdir)/libddcutil.a # @if [ -f $(DESTDIR)$(libdir)/libddcutil.la ] ; then \ # echo "(src/Makefile) install-exec-hook: Stripping dependency_libs from libddcutil.la" ; \ # sed -i "/dependency_libs/ s/'.*'/''/" $(DESTDIR)$(libdir)/libddcutil.la ; \ # fi if INSTALL_LIB_ONLY_COND rm -f $(DESTDIR)${bindir}/ddcutil rm -f ${DESTDIR}${libdir}/libddcutil.so endif # objdump -p $(DESTDIR)$(libdir)/libddcutil.so | sed -n -e's/^[[:space:]]*SONAME[[:space:]]*//p' | sed -r -e's/([0-9])\.so\./\1-/; s/\.so(\.|$)//; y/_/-/; s/(.*)/\L&/' @echo "(src/Makefile) Completed install-exec-hook" install-data-local: @echo "(src/Makefile) Executing install-data-local ..." @echo "(src/Makefile) install-data-local done" install-data-hook: @echo "(src/Makefile) Executing install-data-hook ..." if INSTALL_LIB_ONLY_COND rm -f ${DESTDIR}${includedir}/ddcutil_macros.h rm -f ${DESTDIR}${includedir}/ddcutil_status_codes.h rm -f ${DESTDIR}${includedir}/ddcutil_types.h rm -f ${DESTDIR}${includedir}/ddcutil_c_api.h endif @echo "(src/Makefile) install-data-hook done" uninstall-local: @echo "(src/Makefile:uninstall-local) Executing..." rm -f $(DESTDIR)$(libdir)/libddcutil* # Rename from all-local-disabled to "all-local" for development all-local-disabled: @echo "" @echo "(src/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" ddcutil-2.2.0/src/Makefile.in0000664000175000001440000012566214754576155011515 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # src/Makefile.am VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @INCLUDE_TESTCASES_COND_TRUE@am__append_1 = test @ENABLE_SHARED_LIB_COND_TRUE@am__append_2 = libmain bin_PROGRAMS = ddcutil$(EXEEXT) @ENABLE_CALLGRAPH_COND_TRUE@am__append_3 = -fdump-rtl-expand @ASAN_COND_TRUE@am__append_4 = -fsanitize=address -fsanitize-address-use-after-scope -fno-omit-frame-pointer -g @ENABLE_USB_COND_TRUE@am__append_5 = \ @ENABLE_USB_COND_TRUE@ usb_util/libusbutil.la \ @ENABLE_USB_COND_TRUE@ usb/libusb.la @USE_X11_COND_TRUE@am__append_6 = $(LIBX11_LIBS) $(XEXT_LIBS) $(XRANDR_LIBS) @ENABLE_ENVCMDS_COND_TRUE@am__append_7 = \ @ENABLE_ENVCMDS_COND_TRUE@app_sysenv/libappsysenv.la @INCLUDE_TESTCASES_COND_TRUE@am__append_8 = \ @INCLUDE_TESTCASES_COND_TRUE@test/libtestcases.la @USE_LIBDRM_COND_TRUE@am__append_9 = $(LIBDRM_LIBS) @ASAN_COND_TRUE@am__append_10 = -fsanitize=address \ @ASAN_COND_TRUE@ -fsanitize-address-use-after-scope \ @ASAN_COND_TRUE@ -fno-omit-frame-pointer @ASAN_COND_TRUE@am__append_11 = -lasan @ASAN_COND_TRUE@@ENABLE_SHARED_LIB_COND_TRUE@am__append_12 = -fsanitize=address \ @ASAN_COND_TRUE@@ENABLE_SHARED_LIB_COND_TRUE@ -fsanitize-address-use-after-scope \ @ASAN_COND_TRUE@@ENABLE_SHARED_LIB_COND_TRUE@ -fno-omit-frame-pointer @ASAN_COND_TRUE@@ENABLE_SHARED_LIB_COND_TRUE@am__append_13 = -lasan subdir = src ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__include_HEADERS_DIST) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libdir)" \ "$(DESTDIR)$(includedir)" PROGRAMS = $(bin_PROGRAMS) am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } LTLIBRARIES = $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES) libapp_la_DEPENDENCIES = app_ddcutil/libappddcutil.la $(am__append_7) \ $(am__append_8) am_libapp_la_OBJECTS = libapp_la_OBJECTS = $(am_libapp_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am__DEPENDENCIES_1 = @USE_X11_COND_TRUE@am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1) \ @USE_X11_COND_TRUE@ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) @USE_LIBDRM_COND_TRUE@am__DEPENDENCIES_3 = $(am__DEPENDENCIES_1) libcommon_la_DEPENDENCIES = dw/libdw.la ddc/libddc.la \ dynvcp/libdynvcp.la i2c/libi2c.la sysfs/libsysfs.la \ vcp/libvcp.la cmdline/libcmdline.la base/libbase.la \ util/libutil.la $(am__append_5) $(am__DEPENDENCIES_2) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_3) am_libcommon_la_OBJECTS = libcommon_la_OBJECTS = $(am_libcommon_la_OBJECTS) @ENABLE_SHARED_LIB_COND_TRUE@libddcutil_la_DEPENDENCIES = \ @ENABLE_SHARED_LIB_COND_TRUE@ $(am__DEPENDENCIES_1) \ @ENABLE_SHARED_LIB_COND_TRUE@ libcommon.la \ @ENABLE_SHARED_LIB_COND_TRUE@ libmain/libsharedlib.la \ @ENABLE_SHARED_LIB_COND_TRUE@ $(am__DEPENDENCIES_1) am_libddcutil_la_OBJECTS = libddcutil_la_OBJECTS = $(am_libddcutil_la_OBJECTS) libddcutil_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libddcutil_la_LDFLAGS) $(LDFLAGS) -o $@ @ENABLE_SHARED_LIB_COND_TRUE@am_libddcutil_la_rpath = -rpath $(libdir) am_ddcutil_OBJECTS = ddcutil_OBJECTS = $(am_ddcutil_OBJECTS) ddcutil_DEPENDENCIES = libapp.la libcommon.la $(am__DEPENDENCIES_1) ddcutil_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(ddcutil_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libapp_la_SOURCES) $(libcommon_la_SOURCES) \ $(libddcutil_la_SOURCES) $(ddcutil_SOURCES) DIST_SOURCES = $(libapp_la_SOURCES) $(libcommon_la_SOURCES) \ $(libddcutil_la_SOURCES) $(ddcutil_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__include_HEADERS_DIST = public/ddcutil_macros.h \ public/ddcutil_status_codes.h public/ddcutil_types.h \ public/ddcutil_c_api.h HEADERS = $(include_HEADERS) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ DIST_SUBDIRS = app_ddcutil app_sysenv base cmdline ddc dw dynvcp i2c libmain sysfs sample_clients test usb usb_util util vcp # contain only header files: EXTRA_DIST = bsd private public SUBDIRS = util usb_util base vcp sysfs i2c usb dynvcp ddc dw \ $(am__append_1) $(am__append_2) app_sysenv app_ddcutil cmdline \ . sample_clients MOSTLYCLEANFILES = CLEANFILES = DISTCLEANFILES = publc/ddcutil_macros.h ddcutil_SOURCES = @ENABLE_SHARED_LIB_COND_TRUE@lib_LTLIBRARIES = libddcutil.la @ENABLE_SHARED_LIB_COND_TRUE@libddcutil_la_SOURCES = # # Intermediate libraries built in this directory # # Convenience library containing code shared between ddcutil executable and libddcutil shared library # Convenience library to collect code used only in ddcutil executable noinst_LTLIBRARIES = libcommon.la libapp.la libcommon_la_SOURCES = libapp_la_SOURCES = @ENABLE_SHARED_LIB_COND_TRUE@include_HEADERS = \ @ENABLE_SHARED_LIB_COND_TRUE@public/ddcutil_macros.h \ @ENABLE_SHARED_LIB_COND_TRUE@public/ddcutil_status_codes.h \ @ENABLE_SHARED_LIB_COND_TRUE@public/ddcutil_types.h \ @ENABLE_SHARED_LIB_COND_TRUE@public/ddcutil_c_api.h # # C Pre-Processor Flags # # GLIB_CFLAGS contains output of pkgconfig --cflags glib-2.0 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ $(XRANDR_CFLAGS) \ $(LIBUSB_CFLAGS) \ -I$(srcdir) \ -I$(srcdir)/public # # Compiler flags # # unused-result defined since at least gcc 5 # format-security defined since gcc 2.95.3, Clang 4.0.0 # Distributing -Werror is bad programming practice. It can result in build failure # on an external site having a different compiler, compiler version, or configuration. # See comments and answers in # https://stackoverflow.com/questions/10275554/how-to-disable-specified-warning-for-specified-file-while-using-autotools # 10/1/2022: now enabled by WARNINGS_ARE_ERRORS_COND in individual Makefile.am # AM_CFLAGS += -Werror # AM_CFLAGS += -Wpedantic # -pedantic issues warnings re code that doesn't conform to ISO C # In particular, -m modifier on sscanf is a POSIX extension, not ISO C # Also flags PROGRAM_LOGIC_ERROR() # If combined with -Werror, will cause some module compilations to fail # AM_CFLAGS += -H # Report header file dependencies # see https://community.ibm.com/community/user/ibmz-and-linuxone/blogs/colton-cox1/2020/03/12/ztpf-cc-performance-hints # Will flag glib's use of _Static_assert, which is not in the C99 standard, # but which is in gcc as of 4.6, also other constructs # AM_CFLAGS += -Wc99-c11-compat # Option added in Clang 12, if set causes warnings in WITH_VALIDATED_DH*() macros etc. # The option does not exist in gcc. # The "-Wno-" option form is ignored by gcc, but should be respected when compiling # in an environment, e.g. termux, where this option is enabled by default. # https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++ # AM_CFLAGS += -Wformat -Wformat=2 # too many errors to be worth fixing # AM_CFLAGS += -Wconversion # AM_CFLAGS += $(PYTHON_CPPFLAGS) AM_CFLAGS = -Wall -std=c11 -Werror=unused-result -Wformat-security \ -fno-common -Wimplicit-function-declaration \ -Wno-compound-token-split-by-macro -Wimplicit-fallthrough \ -D_GLIBCXX_ASSERTIONS -Werror=implicit \ -Werror=incompatible-pointer-types -Werror=int-conversion \ $(am__append_3) $(am__append_4) -fPIC -D_GNU_SOURCE @ASAN_COND_TRUE@ASAN_OPTIONS = strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1 \ @ASAN_COND_TRUE@ verbosity=1 # unnessary, will use AM_CFLAGS if xxx_CFLAGS undefined # ddcutil_CFLAGS = $(AM_CFLAGS) # libcommon_la_CFLAGS = $(AM_CFLAGS) # libddcutil_la_CFLAGS = $(AM_CFLAGS) # Makefile:420: *** Recursive variable 'AM_CFLAGS' references itself (eventually). Stop. # export AM_CFLAGS AM_CFLAGS_STD = $(AM_CFLAGS) # # Link convenience library libcommon.la # # Be careful about library ordering. # A library must be listed after any libraries that depend on it # # if ENABLE_YAML_COND # libcommon_la_LIBADD += $(YAML_LIBS) # endif libcommon_la_LIBADD = dw/libdw.la ddc/libddc.la dynvcp/libdynvcp.la \ i2c/libi2c.la sysfs/libsysfs.la vcp/libvcp.la \ cmdline/libcmdline.la base/libbase.la util/libutil.la \ $(am__append_5) $(am__append_6) $(JANSSON_LIBS) $(GLIB_LIBS) \ $(UDEV_LIBS) $(LIBUSB_LIBS) $(am__append_9) # for smbus functions: # libcommon_la_LIBADD += -li2c # # Link convenience library libapp # libapp_la_LIBADD = app_ddcutil/libappddcutil.la $(am__append_7) \ $(am__append_8) # # Link ddcutil executable # # ddcutil statically links libcommon, rather than using libddcutil.so # so it needs LDADD references to external libraries as well ddcutil_LDADD = libapp.la libcommon.la $(am__append_11) #needed? # -export-dynamic needed for failsim ddcutil_LDFLAGS = -pie -export-dynamic $(am__append_10) # # Link libddcutil executable # # libddcutil_la_LIBADD = -lz @ENABLE_SHARED_LIB_COND_TRUE@libddcutil_la_LIBADD = $(ZLIB_LIBS) \ @ENABLE_SHARED_LIB_COND_TRUE@ libcommon.la \ @ENABLE_SHARED_LIB_COND_TRUE@ libmain/libsharedlib.la \ @ENABLE_SHARED_LIB_COND_TRUE@ $(am__append_13) # Note -export-dynamic not required for failsim, don't need to append # libddcutil_la_LDFLAGS += -export-dynamic # doesn't prevent creation of .la # try disabling to create libddcutil.a - doesnt do it @ENABLE_SHARED_LIB_COND_TRUE@libddcutil_la_LDFLAGS = \ @ENABLE_SHARED_LIB_COND_TRUE@ -export-symbols-regex \ @ENABLE_SHARED_LIB_COND_TRUE@ '(^DDCA_|^ddc[ags]_[^_])' \ @ENABLE_SHARED_LIB_COND_TRUE@ -version-info \ @ENABLE_SHARED_LIB_COND_TRUE@ '@LT_CURRENT@:@LT_REVISION@:@LT_AGE@' \ @ENABLE_SHARED_LIB_COND_TRUE@ -pie $(am__append_12) \ @ENABLE_SHARED_LIB_COND_TRUE@ --disable-static all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libapp.la: $(libapp_la_OBJECTS) $(libapp_la_DEPENDENCIES) $(EXTRA_libapp_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libapp_la_OBJECTS) $(libapp_la_LIBADD) $(LIBS) libcommon.la: $(libcommon_la_OBJECTS) $(libcommon_la_DEPENDENCIES) $(EXTRA_libcommon_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libcommon_la_OBJECTS) $(libcommon_la_LIBADD) $(LIBS) libddcutil.la: $(libddcutil_la_OBJECTS) $(libddcutil_la_DEPENDENCIES) $(EXTRA_libddcutil_la_DEPENDENCIES) $(AM_V_CCLD)$(libddcutil_la_LINK) $(am_libddcutil_la_rpath) $(libddcutil_la_OBJECTS) $(libddcutil_la_LIBADD) $(LIBS) ddcutil$(EXEEXT): $(ddcutil_OBJECTS) $(ddcutil_DEPENDENCIES) $(EXTRA_ddcutil_DEPENDENCIES) @rm -f ddcutil$(EXEEXT) $(AM_V_CCLD)$(ddcutil_LINK) $(ddcutil_OBJECTS) $(ddcutil_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am check: check-recursive all-am: Makefile $(PROGRAMS) $(LTLIBRARIES) $(HEADERS) all-local install-binPROGRAMS: install-libLTLIBRARIES installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(MOSTLYCLEANFILES)" || rm -f $(MOSTLYCLEANFILES) clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-binPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool clean-local clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-local distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-data-local install-includeHEADERS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-binPROGRAMS install-exec-local \ install-libLTLIBRARIES @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-exec-hook install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-includeHEADERS \ uninstall-libLTLIBRARIES uninstall-local .MAKE: $(am__recursive_targets) install-am install-data-am \ install-exec-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am all-local \ check check-am clean clean-binPROGRAMS clean-generic \ clean-libLTLIBRARIES clean-libtool clean-local \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am dist-hook \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-local distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-binPROGRAMS install-data install-data-am \ install-data-hook install-data-local install-dvi \ install-dvi-am install-exec install-exec-am install-exec-hook \ install-exec-local install-html install-html-am \ install-includeHEADERS install-info install-info-am \ install-libLTLIBRARIES install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool mostlyclean-local pdf \ pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-includeHEADERS \ uninstall-libLTLIBRARIES uninstall-local .PRECIOUS: Makefile # todo: factor out swig # todo: fails if swig/.libs doesn't exist # rm -rf swig/ddc_swig_wrap.c swig/ddc_swig.py swig/ddc_swig.pyc # Plo files in deps directories are automatically included in generated Makefiles for some reason # test -z `find . -name ".deps" -type d` || rm -rf `find . -name ".deps" -type d` # For conditionally included files, e.g. those in usb_util, make clean does not delete # the .lo files. Hence the instructions here to delete all of them # Fails: test: too many arguments: # test -z `find . -name "*lo" -type f` || rm `find . -name "*lo" -type f` # distclean-local => clean-local => mostlyclean->local mostlyclean-local: @echo "(src/Makefile) mostlyclean-local" clean-local: @echo "(src/Makefile) clean-local" find . -name "*plist" -type d -exec ls -ld {} \; rm -rf `find . -name "*plist" -type d` find . -name ".libs" -type d -exec ls -ld {} \; test -z `find . -name "*expand" -type f` || rm `find . -name "*expand" -type f` find . -name "*.lo" -type f -exec rm -fv {} \; find . -name "*.o" -type f -exec rm -fv {} \; find . -name ".deps" -type d -exec ls -ld {} \; find . -path "*/.deps/*" -exec ls -l {} \; distclean-local: @echo "(src/Makefile) distclean-local" find . -name ".libs" -type d -exec ls -ld {} \; rm -rf `find . -name "*plist" -type d` maintainerclean-local: @echo "(src/Makefile) maintainerclean-local" # Notes: # 1) Without -prune option, the following line fails because list of file is archived internally, get file not found errors after remove # find $(top_distdir) -name ".deps" -exec rm -rf {} \; # 2) Piping to xargs fails if there are no files, which occurs if "make dist" is invoked without anything having been built. # find $(top_distdir) -name ".deps" | xargs rm # 3) Why explicit copy of .h files? # 4) find statements in src/usb_util/Makefile.am find nothing, but those here work. why? dist-hook: @echo "(src/Makefile) Executing hook dist-hook. top_distdir=$(top_distdir) distdir=$(distdir).." find . -type f | grep \.h$ | xargs -i cp --parents "{}" $(distdir) find $(distdir) -name ".deps" -type d -prune -exec rm -rfv {} \; find $(distdir) -name ".libs" -type d -prune -exec rm -rfv {} \; find $(distdir) -name "*.lo" -exec rm -v {} \; find $(distdir) -name "*.o" -exec rm -v {} \; rm -rfv $(distdir)/swig/pyenv rm -rfv $(distdir)/swig/__pycache__ rm -fv ${distdir}/public/ddcutil_macros.h find ${distdir} -name adl_archived -type d -prune -exec rm -rfv {} \; find ${distdir} -name "*old" -type d -prune -exec rm -rfv {} \; find ${distdir} -name "*new" -type d -prune -exec rm -rfv {} \; @ASAN_COND_TRUE@ # -fsanitize=address required for both compile and link, what about other -f options? @ASAN_COND_TRUE@ # does this go here or as and environment variable at runtime? @ASAN_COND_TRUE@ # for -fsanitize-address-use-after-scope export AM_CFLAGS_STD @ASAN_COND_TRUE@ # needed? @ASAN_COND_TRUE@@ENABLE_SHARED_LIB_COND_TRUE@ # needed? @ASAN_COND_TRUE@@ENABLE_SHARED_LIB_COND_TRUE@ # doesn't work: @ASAN_COND_TRUE@@ENABLE_SHARED_LIB_COND_TRUE@ # libddcutil_la_LDFLAGS += -static-libasan all-local: @echo "(src/Makefile) all-local" rm -fv base/build_details.h # debug-install-hook: # ls -ld $(DESTDIR)$(libdir) # ls -l $(DESTDIR)$(libdir)/*la # @echo " pythondir = $(pythondir)" # @echo " pyexecdir = $(pyexecdir)" # @echo $(DESTDIR)$(libdir) install-exec-local: @echo "(src/Makefile) Executing install-exec-local ..." @echo "(src/Makefile) install-exec-local done" install-exec-hook: @echo "(src/Makefile) Executing install-exec-hook ..." rm -f $(DESTDIR)$(libdir)/libddcutil.la # rm -f $(DESTDIR)$(libdir)/libddcutil.a # @if [ -f $(DESTDIR)$(libdir)/libddcutil.la ] ; then \ # echo "(src/Makefile) install-exec-hook: Stripping dependency_libs from libddcutil.la" ; \ # sed -i "/dependency_libs/ s/'.*'/''/" $(DESTDIR)$(libdir)/libddcutil.la ; \ # fi @INSTALL_LIB_ONLY_COND_TRUE@ rm -f $(DESTDIR)${bindir}/ddcutil @INSTALL_LIB_ONLY_COND_TRUE@ rm -f ${DESTDIR}${libdir}/libddcutil.so # objdump -p $(DESTDIR)$(libdir)/libddcutil.so | sed -n -e's/^[[:space:]]*SONAME[[:space:]]*//p' | sed -r -e's/([0-9])\.so\./\1-/; s/\.so(\.|$)//; y/_/-/; s/(.*)/\L&/' @echo "(src/Makefile) Completed install-exec-hook" install-data-local: @echo "(src/Makefile) Executing install-data-local ..." @echo "(src/Makefile) install-data-local done" install-data-hook: @echo "(src/Makefile) Executing install-data-hook ..." @INSTALL_LIB_ONLY_COND_TRUE@ rm -f ${DESTDIR}${includedir}/ddcutil_macros.h @INSTALL_LIB_ONLY_COND_TRUE@ rm -f ${DESTDIR}${includedir}/ddcutil_status_codes.h @INSTALL_LIB_ONLY_COND_TRUE@ rm -f ${DESTDIR}${includedir}/ddcutil_types.h @INSTALL_LIB_ONLY_COND_TRUE@ rm -f ${DESTDIR}${includedir}/ddcutil_c_api.h @echo "(src/Makefile) install-data-hook done" uninstall-local: @echo "(src/Makefile:uninstall-local) Executing..." rm -f $(DESTDIR)$(libdir)/libddcutil* # Rename from all-local-disabled to "all-local" for development all-local-disabled: @echo "" @echo "(src/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/bsd/0000755000175000001440000000000014754576333010260 5ddcutil-2.2.0/src/bsd/i2c-dev.h0000644000175000001440000000513714754576332011607 /* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* i2c-dev.h - i2c-bus driver, char device interface Copyright (C) 1995-97 Simon G. Vogl Copyright (C) 1998-99 Frodo Looijaard This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _LINUX_I2C_DEV_H #define _LINUX_I2C_DEV_H #include "linux_types.h" // private copy of Linux /* /dev/i2c-X ioctl commands. The ioctl's parameter is always an * unsigned long, except for: * - I2C_FUNCS, takes pointer to an unsigned long * - I2C_RDWR, takes pointer to struct i2c_rdwr_ioctl_data * - I2C_SMBUS, takes pointer to struct i2c_smbus_ioctl_data */ #define I2C_RETRIES 0x0701 /* number of times a device address should be polled when not acknowledging */ #define I2C_TIMEOUT 0x0702 /* set timeout in units of 10 ms */ /* NOTE: Slave address is 7 or 10 bits, but 10-bit addresses * are NOT supported! (due to code brokenness) */ #define I2C_SLAVE 0x0703 /* Use this slave address */ #define I2C_SLAVE_FORCE 0x0706 /* Use this slave address, even if it is already in use by a driver! */ #define I2C_TENBIT 0x0704 /* 0 for 7 bit addrs, != 0 for 10 bit */ #define I2C_FUNCS 0x0705 /* Get the adapter functionality mask */ #define I2C_RDWR 0x0707 /* Combined R/W transfer (one STOP only) */ #define I2C_PEC 0x0708 /* != 0 to use PEC with SMBus */ #define I2C_SMBUS 0x0720 /* SMBus transfer */ /* This is the structure as used in the I2C_SMBUS ioctl call */ struct i2c_smbus_ioctl_data { __u8 read_write; __u8 command; __u32 size; union i2c_smbus_data *data; }; /* This is the structure as used in the I2C_RDWR ioctl call */ struct i2c_rdwr_ioctl_data { struct i2c_msg *msgs; /* pointers to i2c_msgs */ __u32 nmsgs; /* number of i2c_msgs */ }; #define I2C_RDWR_IOCTL_MAX_MSGS 42 /* Originally defined with a typo, keep it for compatibility */ #define I2C_RDRW_IOCTL_MAX_MSGS I2C_RDWR_IOCTL_MAX_MSGS #endif /* _LINUX_I2C_DEV_H */ ddcutil-2.2.0/src/bsd/i2c.h0000644000175000001440000001601314754576332011026 /* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* ------------------------------------------------------------------------- */ /* */ /* i2c.h - definitions for the i2c-bus interface */ /* */ /* ------------------------------------------------------------------------- */ /* Copyright (C) 1995-2000 Simon G. Vogl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* ------------------------------------------------------------------------- */ /* With some changes from Kyösti Mälkki and Frodo Looijaard */ #ifndef _LINUX_I2C_H #define _LINUX_I2C_H #include "linux_types.h" // private version of Linux /** * struct i2c_msg - an I2C transaction segment beginning with START * @addr: Slave address, either seven or ten bits. When this is a ten * bit address, I2C_M_TEN must be set in @flags and the adapter * must support I2C_FUNC_10BIT_ADDR. * @flags: I2C_M_RD is handled by all adapters. No other flags may be * provided unless the adapter exported the relevant I2C_FUNC_* * flags through i2c_check_functionality(). * @len: Number of data bytes in @buf being read from or written to the * I2C slave address. For read transactions where I2C_M_RECV_LEN * is set, the caller guarantees that this buffer can hold up to * 32 bytes in addition to the initial length byte sent by the * slave (plus, if used, the SMBus PEC); and this value will be * incremented by the number of block data bytes received. * @buf: The buffer into which data is read, or from which it's written. * * An i2c_msg is the low level representation of one segment of an I2C * transaction. It is visible to drivers in the @i2c_transfer() procedure, * to userspace from i2c-dev, and to I2C adapter drivers through the * @i2c_adapter.@master_xfer() method. * * Except when I2C "protocol mangling" is used, all I2C adapters implement * the standard rules for I2C transactions. Each transaction begins with a * START. That is followed by the slave address, and a bit encoding read * versus write. Then follow all the data bytes, possibly including a byte * with SMBus PEC. The transfer terminates with a NAK, or when all those * bytes have been transferred and ACKed. If this is the last message in a * group, it is followed by a STOP. Otherwise it is followed by the next * @i2c_msg transaction segment, beginning with a (repeated) START. * * Alternatively, when the adapter supports I2C_FUNC_PROTOCOL_MANGLING then * passing certain @flags may have changed those standard protocol behaviors. * Those flags are only for use with broken/nonconforming slaves, and with * adapters which are known to support the specific mangling options they * need (one or more of IGNORE_NAK, NO_RD_ACK, NOSTART, and REV_DIR_ADDR). */ struct i2c_msg { __u16 addr; /* slave address */ __u16 flags; #define I2C_M_RD 0x0001 /* read data, from slave to master */ /* I2C_M_RD is guaranteed to be 0x0001! */ #define I2C_M_TEN 0x0010 /* this is a ten bit chip address */ #define I2C_M_DMA_SAFE 0x0200 /* the buffer of this message is DMA safe */ /* makes only sense in kernelspace */ /* userspace buffers are copied anyway */ #define I2C_M_RECV_LEN 0x0400 /* length will be first received byte */ #define I2C_M_NO_RD_ACK 0x0800 /* if I2C_FUNC_PROTOCOL_MANGLING */ #define I2C_M_IGNORE_NAK 0x1000 /* if I2C_FUNC_PROTOCOL_MANGLING */ #define I2C_M_REV_DIR_ADDR 0x2000 /* if I2C_FUNC_PROTOCOL_MANGLING */ #define I2C_M_NOSTART 0x4000 /* if I2C_FUNC_NOSTART */ #define I2C_M_STOP 0x8000 /* if I2C_FUNC_PROTOCOL_MANGLING */ __u16 len; /* msg length */ __u8 *buf; /* pointer to msg data */ }; /* To determine what functionality is present */ #define I2C_FUNC_I2C 0x00000001 #define I2C_FUNC_10BIT_ADDR 0x00000002 #define I2C_FUNC_PROTOCOL_MANGLING 0x00000004 /* I2C_M_IGNORE_NAK etc. */ #define I2C_FUNC_SMBUS_PEC 0x00000008 #define I2C_FUNC_NOSTART 0x00000010 /* I2C_M_NOSTART */ #define I2C_FUNC_SLAVE 0x00000020 #define I2C_FUNC_SMBUS_BLOCK_PROC_CALL 0x00008000 /* SMBus 2.0 */ #define I2C_FUNC_SMBUS_QUICK 0x00010000 #define I2C_FUNC_SMBUS_READ_BYTE 0x00020000 #define I2C_FUNC_SMBUS_WRITE_BYTE 0x00040000 #define I2C_FUNC_SMBUS_READ_BYTE_DATA 0x00080000 #define I2C_FUNC_SMBUS_WRITE_BYTE_DATA 0x00100000 #define I2C_FUNC_SMBUS_READ_WORD_DATA 0x00200000 #define I2C_FUNC_SMBUS_WRITE_WORD_DATA 0x00400000 #define I2C_FUNC_SMBUS_PROC_CALL 0x00800000 #define I2C_FUNC_SMBUS_READ_BLOCK_DATA 0x01000000 #define I2C_FUNC_SMBUS_WRITE_BLOCK_DATA 0x02000000 #define I2C_FUNC_SMBUS_READ_I2C_BLOCK 0x04000000 /* I2C-like block xfer */ #define I2C_FUNC_SMBUS_WRITE_I2C_BLOCK 0x08000000 /* w/ 1-byte reg. addr. */ #define I2C_FUNC_SMBUS_HOST_NOTIFY 0x10000000 #define I2C_FUNC_SMBUS_BYTE (I2C_FUNC_SMBUS_READ_BYTE | \ I2C_FUNC_SMBUS_WRITE_BYTE) #define I2C_FUNC_SMBUS_BYTE_DATA (I2C_FUNC_SMBUS_READ_BYTE_DATA | \ I2C_FUNC_SMBUS_WRITE_BYTE_DATA) #define I2C_FUNC_SMBUS_WORD_DATA (I2C_FUNC_SMBUS_READ_WORD_DATA | \ I2C_FUNC_SMBUS_WRITE_WORD_DATA) #define I2C_FUNC_SMBUS_BLOCK_DATA (I2C_FUNC_SMBUS_READ_BLOCK_DATA | \ I2C_FUNC_SMBUS_WRITE_BLOCK_DATA) #define I2C_FUNC_SMBUS_I2C_BLOCK (I2C_FUNC_SMBUS_READ_I2C_BLOCK | \ I2C_FUNC_SMBUS_WRITE_I2C_BLOCK) #define I2C_FUNC_SMBUS_EMUL (I2C_FUNC_SMBUS_QUICK | \ I2C_FUNC_SMBUS_BYTE | \ I2C_FUNC_SMBUS_BYTE_DATA | \ I2C_FUNC_SMBUS_WORD_DATA | \ I2C_FUNC_SMBUS_PROC_CALL | \ I2C_FUNC_SMBUS_WRITE_BLOCK_DATA | \ I2C_FUNC_SMBUS_I2C_BLOCK | \ I2C_FUNC_SMBUS_PEC) /* * Data for SMBus Messages */ #define I2C_SMBUS_BLOCK_MAX 32 /* As specified in SMBus standard */ union i2c_smbus_data { __u8 byte; __u16 word; __u8 block[I2C_SMBUS_BLOCK_MAX + 2]; /* block[0] is used for length */ /* and one more for user-space compatibility */ }; /* i2c_smbus_xfer read or write markers */ #define I2C_SMBUS_READ 1 #define I2C_SMBUS_WRITE 0 /* SMBus transaction types (size parameter in the above functions) Note: these no longer correspond to the (arbitrary) PIIX4 internal codes! */ #define I2C_SMBUS_QUICK 0 #define I2C_SMBUS_BYTE 1 #define I2C_SMBUS_BYTE_DATA 2 #define I2C_SMBUS_WORD_DATA 3 #define I2C_SMBUS_PROC_CALL 4 #define I2C_SMBUS_BLOCK_DATA 5 #define I2C_SMBUS_I2C_BLOCK_BROKEN 6 #define I2C_SMBUS_BLOCK_PROC_CALL 7 /* SMBus 2.0 */ #define I2C_SMBUS_I2C_BLOCK_DATA 8 #endif /* _LINUX_I2C_H */ ddcutil-2.2.0/src/bsd/linux_types.h0000644000175000001440000000070014754576332012730 /** \f linux_types.h * * Integer type definitions needed by private copies of * i2c.h, i2c-dev.h. Used if TARGET_BSD */ // Copyright (C) 2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef LINUX_TYPES_H_ #define LINUX_TYPES_H_ #include #include // n.b. BSD version typedef uint8_t __u8; typedef uint16_t __u16; typedef uint32_t __u32; #endif /* LINUX_TYPES_H_ */ ddcutil-2.2.0/src/private/0000777000175000001440000000000014754576332011165 5ddcutil-2.2.0/src/app_ddcutil/0000775000175000001440000000000014754576332012001 5ddcutil-2.2.0/src/app_ddcutil/Makefile.am0000644000175000001440000000142614634376340013750 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public if USE_LIBDRM_COND AM_CPPFLAGS += \ $(LIBDRM_CFLAGS) endif AM_CFLAGS = -Wall if WARNINGS_ARE_ERRORS_COND AM_CFLAGS += -Werror endif # AM_CFLAGS += -Wpedantic if ENABLE_CALLGRAPH_COND AM_CFLAGS += -fdump-rtl-expand endif CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libappddcutil.la libappddcutil_la_SOURCES = \ main.c \ app_capabilities.c \ app_dumpload.c \ app_dynamic_features.c \ app_experimental.c \ app_getvcp.c \ app_probe.c \ app_ddcutil_services.c \ app_setvcp.c \ app_vcpinfo.c \ app_watch.c if INCLUDE_TESTCASES_COND libappddcutil_la_SOURCES += app_testcases.c endif if ENABLE_ENVCMDS_COND libappddcutil_la_SOURCES += \ app_interrogate.c endif ddcutil-2.2.0/src/app_ddcutil/Makefile.in0000664000175000001440000005655414754576155014010 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_LIBDRM_COND_TRUE@am__append_1 = \ @USE_LIBDRM_COND_TRUE@ $(LIBDRM_CFLAGS) @WARNINGS_ARE_ERRORS_COND_TRUE@am__append_2 = -Werror # AM_CFLAGS += -Wpedantic @ENABLE_CALLGRAPH_COND_TRUE@am__append_3 = -fdump-rtl-expand @INCLUDE_TESTCASES_COND_TRUE@am__append_4 = app_testcases.c @ENABLE_ENVCMDS_COND_TRUE@am__append_5 = \ @ENABLE_ENVCMDS_COND_TRUE@app_interrogate.c subdir = src/app_ddcutil ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libappddcutil_la_LIBADD = am__libappddcutil_la_SOURCES_DIST = main.c app_capabilities.c \ app_dumpload.c app_dynamic_features.c app_experimental.c \ app_getvcp.c app_probe.c app_ddcutil_services.c app_setvcp.c \ app_vcpinfo.c app_watch.c app_testcases.c app_interrogate.c @INCLUDE_TESTCASES_COND_TRUE@am__objects_1 = app_testcases.lo @ENABLE_ENVCMDS_COND_TRUE@am__objects_2 = app_interrogate.lo am_libappddcutil_la_OBJECTS = main.lo app_capabilities.lo \ app_dumpload.lo app_dynamic_features.lo app_experimental.lo \ app_getvcp.lo app_probe.lo app_ddcutil_services.lo \ app_setvcp.lo app_vcpinfo.lo app_watch.lo $(am__objects_1) \ $(am__objects_2) libappddcutil_la_OBJECTS = $(am_libappddcutil_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/app_capabilities.Plo \ ./$(DEPDIR)/app_ddcutil_services.Plo \ ./$(DEPDIR)/app_dumpload.Plo \ ./$(DEPDIR)/app_dynamic_features.Plo \ ./$(DEPDIR)/app_experimental.Plo ./$(DEPDIR)/app_getvcp.Plo \ ./$(DEPDIR)/app_interrogate.Plo ./$(DEPDIR)/app_probe.Plo \ ./$(DEPDIR)/app_setvcp.Plo ./$(DEPDIR)/app_testcases.Plo \ ./$(DEPDIR)/app_vcpinfo.Plo ./$(DEPDIR)/app_watch.Plo \ ./$(DEPDIR)/main.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libappddcutil_la_SOURCES) DIST_SOURCES = $(am__libappddcutil_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = $(GLIB_CFLAGS) -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public $(am__append_1) AM_CFLAGS = -Wall $(am__append_2) $(am__append_3) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libappddcutil.la libappddcutil_la_SOURCES = main.c app_capabilities.c app_dumpload.c \ app_dynamic_features.c app_experimental.c app_getvcp.c \ app_probe.c app_ddcutil_services.c app_setvcp.c app_vcpinfo.c \ app_watch.c $(am__append_4) $(am__append_5) all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/app_ddcutil/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/app_ddcutil/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libappddcutil.la: $(libappddcutil_la_OBJECTS) $(libappddcutil_la_DEPENDENCIES) $(EXTRA_libappddcutil_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libappddcutil_la_OBJECTS) $(libappddcutil_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_capabilities.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_ddcutil_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_dumpload.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_dynamic_features.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_experimental.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_getvcp.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_interrogate.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_probe.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_setvcp.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_testcases.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_vcpinfo.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_watch.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/app_capabilities.Plo -rm -f ./$(DEPDIR)/app_ddcutil_services.Plo -rm -f ./$(DEPDIR)/app_dumpload.Plo -rm -f ./$(DEPDIR)/app_dynamic_features.Plo -rm -f ./$(DEPDIR)/app_experimental.Plo -rm -f ./$(DEPDIR)/app_getvcp.Plo -rm -f ./$(DEPDIR)/app_interrogate.Plo -rm -f ./$(DEPDIR)/app_probe.Plo -rm -f ./$(DEPDIR)/app_setvcp.Plo -rm -f ./$(DEPDIR)/app_testcases.Plo -rm -f ./$(DEPDIR)/app_vcpinfo.Plo -rm -f ./$(DEPDIR)/app_watch.Plo -rm -f ./$(DEPDIR)/main.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/app_capabilities.Plo -rm -f ./$(DEPDIR)/app_ddcutil_services.Plo -rm -f ./$(DEPDIR)/app_dumpload.Plo -rm -f ./$(DEPDIR)/app_dynamic_features.Plo -rm -f ./$(DEPDIR)/app_experimental.Plo -rm -f ./$(DEPDIR)/app_getvcp.Plo -rm -f ./$(DEPDIR)/app_interrogate.Plo -rm -f ./$(DEPDIR)/app_probe.Plo -rm -f ./$(DEPDIR)/app_setvcp.Plo -rm -f ./$(DEPDIR)/app_testcases.Plo -rm -f ./$(DEPDIR)/app_vcpinfo.Plo -rm -f ./$(DEPDIR)/app_watch.Plo -rm -f ./$(DEPDIR)/main.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/app_ddcutil/main.c0000644000175000001440000013365214754153540013011 /** @file main.c * * ddcutil standalone application mainline */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "util/data_structures.h" #include "util/ddcutil_config_file.h" #include "util/debug_util.h" #include "util/error_info.h" #include "util/failsim.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #ifdef USE_LIBDRM #include "util/libdrm_util.h" #endif #include "util/linux_util.h" #include "util/regex_util.h" #include "util/report_util.h" #include "util/simple_ini_file.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/traced_function_stack.h" #include "util/xdg_util.h" /** \endcond */ #include "public/ddcutil_types.h" #include "base/build_info.h" #include "base/build_timestamp.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/ddc_packets.h" #include "base/display_retry_data.h" #include "base/displays.h" #include "base/dsa2.h" #include "base/linux_errno.h" #include "base/monitor_model_key.h" #include "base/parms.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/status_code_mgt.h" #include "base/tuned_sleep.h" #include "vcp/parse_capabilities.h" #include "vcp/persistent_capabilities.h" #include "vcp/vcp_feature_codes.h" #include "dynvcp/dyn_feature_files.h" #include "dynvcp/dyn_parsed_capabilities.h" #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_sys_drm_connector.h" // #include "sysfs/i2c_sysfs_i2c_info.h" #include "sysfs/sysfs_top.h" #include "sysfs/sysfs_base.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_strategy_dispatcher.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #endif #include "ddc/ddc_common_init.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_display_ref_reports.h" #include "ddc/ddc_display_selection.h" #include "ddc/ddc_initial_checks.h" #include "ddc/ddc_multi_part_io.h" #include "ddc/ddc_output.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_read_capabilities.h" #include "ddc/ddc_save_current_settings.h" #include "ddc/ddc_serialize.h" #include "ddc/ddc_services.h" #include "ddc/ddc_try_data.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" #include "dw/dw_main.h" #include "dw/dw_services.h" #include "cmdline/cmd_parser_aux.h" // for parse_feature_id_or_subset(), should it be elsewhere? #include "cmdline/cmd_parser.h" #include "cmdline/parsed_cmd.h" #include "test/testcases.h" #include "app_ddcutil/app_capabilities.h" #include "app_ddcutil/app_dynamic_features.h" #include "app_ddcutil/app_dumpload.h" #include "app_ddcutil/app_experimental.h" #include "app_ddcutil/app_interrogate.h" #include "app_ddcutil/app_probe.h" #include "app_ddcutil/app_getvcp.h" #include "app_ddcutil/app_ddcutil_services.h" #include "app_ddcutil/app_setvcp.h" #include "app_ddcutil/app_vcpinfo.h" #include "app_ddcutil/app_watch.h" #ifdef INCLUDE_TESTCASES #include "app_ddcutil/app_testcases.h" #endif #ifdef ENABLE_ENVCMDS #include "app_sysenv/app_sysenv_services.h" #include "app_sysenv/query_sysenv.h" #ifdef ENABLE_USB #include "app_sysenv/query_sysenv_usb.h" #endif #endif // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_TOP; static void add_local_rtti_functions(); // // Report core settings and command line options // static void report_performance_options(int depth) { int d1 = depth+1; rpt_label(depth, "Performance and Retry Options:"); rpt_vstring(d1, "Deferred sleep enabled: %s", sbool( is_deferred_sleep_enabled() ) ); rpt_vstring(d1, "Dynamic sleep algorithm enabled: %s", sbool(dsa2_is_enabled())); if (dsa2_is_enabled()) rpt_vstring(d1, "Minimum dynamic sleep multiplier: %7.2f", dsa2_get_minimum_multiplier()); rpt_vstring(d1, "Default sleep multiplier factor: %7.2f", pdd_get_default_sleep_multiplier_factor() ); rpt_nl(); } static void report_optional_features(Parsed_Cmd * parsed_cmd, int depth) { rpt_vstring( depth, "%.*s%-*s%s", 0, "", 28, "Force I2C slave address:", sbool(i2c_forceable_slave_addr_flag)); rpt_vstring( depth, "%.*s%-*s%s", 0, "", 28, "User defined features:", (enable_dynamic_features) ? "enabled" : "disabled" ); // "Enable user defined features" is too long a title rpt_vstring( depth, "%.*s%-*s%s", 0, "", 28, "Mock feature values:", (enable_mock_data) ? "enabled" : "disabled" ); rpt_nl(); } static void report_all_options(Parsed_Cmd * parsed_cmd, char * config_fn, char * default_options, int depth) { bool debug = false; DBGMSF(debug, "Executing..."); bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); show_ddcutil_version(); if (streq(BUILD_DATE, "Not set")) fprintf(stdout, "Build timestamp: Not set\n"); else fprintf(stdout, "Build timestamp: %s at %s\n", BUILD_DATE, BUILD_TIME); rpt_vstring(depth, "%.*s%-*s%s", 0, "", 28, "Configuration file:", (config_fn) ? config_fn : "(none)"); if (config_fn) rpt_vstring(depth, "%.*s%-*s%s", 0, "", 28, "Configuration file options:", default_options); // report_build_options(depth); show_reporting(); // uses fout() report_optional_features(parsed_cmd, depth); report_tracing(depth); rpt_nl(); report_performance_options(depth); report_experimental_options(parsed_cmd, depth); report_build_options(depth); rpt_set_ornamentation_enabled(saved_prefix_report_output); DBGMSF(debug, "Done"); } // // Initialization functions called only once but factored out of main() to clarify mainline // #ifdef UNUSED #ifdef TARGET_LINUX static bool validate_environment_using_libkmod() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); bool ok = false; if (is_module_loaded_using_sysfs("i2c_dev")) { // only finds loadable modules, not those built into kernel ok = true; } else { int module_status = module_status_using_libkmod("i2c-dev"); if (module_status == 0) { // MODULE_STATUS_NOT_FOUND ok = false; fprintf(stderr, "Module i2c-dev is not loaded and not built into the kernel.\n"); } else if (module_status == KERNEL_MODULE_BUILTIN) { // 1 ok = true; } else if (module_status == KERNEL_MODULE_LOADABLE_FILE) { // int rc = is_module_loaded_using_libkmod("i2c_dev"); if (rc == 0) { fprintf(stderr, "Loadable module i2c-dev exists but is not loaded.\n"); ok = false; } else if (rc == 1) { ok = true; } else { assert(rc < 0); fprintf(stderr, "ddcutil cannot determine if loadable module i2c-dev is loaded.\n"); ok = true; // make this just a warning, we'll fail later if not in kernel fprintf(stderr, "Execution may fail.\n"); } } else { assert(module_status < 0); fprintf(stderr, "ddcutil cannot determine if module i2c-dev is loaded or built into the kernel.\n"); ok = true; // make this just a warning, we'll fail later if not in kernel fprintf(stderr, "Execution may fail.\n"); } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, ok, ""); return ok; } #endif #endif static bool validate_environment() { bool debug = false; DBGMSF(debug, "Starting"); bool ok; ok = dev_i2c_devices_exist(); if (!ok) fprintf(stderr, "No /dev/i2c devices exist.\n"); #ifdef OLD #ifdef TARGET_LINUX if (is_module_loaded_using_sysfs("i2c_dev")) { ok = true; } else { ok = validate_environment_using_libkmod(); } #else ok = true; #endif #endif if (!ok) { fprintf(stderr, "ddcutil requires module i2c-dev.\n"); // DBGMSF(debug, "Forcing ok = true"); // ok = true; // make it just a warning in case we're wrong } DBGMSF(debug, "Done. Returning: %s", sbool(ok)); return ok; } /** For each /dev/i2c device that possibly can be used for DDC/CI communication, * check that it is readable and writable. * * @return number of possibly usable devices */ STATIC int verify_i2c_access() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); Bit_Set_256 buses_without_devices = EMPTY_BIT_SET_256; Bit_Set_256 inaccessible_devices = EMPTY_BIT_SET_256; int buses_ct = 0; int buses_without_devices_ct = 0; int inaccessible_devices_ct = 0; // Bit_Set_256 buses = get_possible_ddc_ci_bus_numbers_using_sysfs_i2c_info(); //sysfs bus numbers, not dev-i2c Bit_Set_256 buses = i2c_detect_attached_buses_as_bitset(); buses_ct = bs256_count(buses); DBGTRC(debug, TRACE_GROUP, "/sys/bus/i2c/devices to check: %s", bs256_to_string_decimal_t(buses, "i2c-", ", ")); if (buses_ct == 0) { fprintf(stderr, "No /sys/bus/i2c buses that might be used for DDC/CI communication found.\n"); fprintf(stderr, "No display adapters with i2c buses appear to exist.\n"); } else { Bit_Set_256_Iterator iter = bs256_iter_new(buses); int busno; while ( (busno = bs256_iter_next(iter)) >= 0) { char fnbuf[20]; // oversize to avoid -Wformat-truncation error snprintf(fnbuf, sizeof(fnbuf), "/dev/i2c-%d", busno); if ( access(fnbuf, R_OK|W_OK) < 0 ) { int errsv = errno; // EACCESS if lack permissions, ENOENT if file doesn't exist if (errsv == ENOENT) { buses_without_devices = bs256_insert(buses_without_devices, busno); fprintf(stderr, "Device %s does not exist. Error = %s\n", fnbuf, linux_errno_desc(errsv)); } else { inaccessible_devices = bs256_insert(inaccessible_devices, busno); fprintf(stderr, "Device %s is not readable and writable. Error = %s\n", fnbuf, linux_errno_desc(errsv) ); include_open_failures_reported(busno); } } } bs256_iter_free(iter); buses_without_devices_ct = bs256_count(buses_without_devices); inaccessible_devices_ct = bs256_count(inaccessible_devices); if (buses_without_devices_ct > 0) { fprintf(stderr, "/sys/bus/i2c buses without /dev/i2c-N devices: %s\n", bs256_to_string_decimal_t(buses_without_devices, "/sys/bus/i2c/devices/i2c-", " ") ); fprintf(stderr, "Driver i2c_dev must be loaded or builtin\n"); fprintf(stderr, "See https://www.ddcutil.com/kernel_module\n"); } if (inaccessible_devices_ct > 0) { fprintf(stderr, "Devices possibly used for DDC/CI communication cannot be opened: %s\n", bs256_to_string_decimal_t(inaccessible_devices, "/dev/i2c-", " ")); fprintf(stderr, "See https://www.ddcutil.com/i2c_permissions\n"); } } int result = buses_ct - (buses_without_devices_ct + inaccessible_devices_ct); DBGTRC_DONE(debug, TRACE_GROUP, "Returning %d. Total potential buses: %d, buses without devices: %d, inaccessible devices: %d", result, buses_ct, buses_without_devices_ct, inaccessible_devices_ct); return result; } /** Verify that a single /dev/i2c device is readable and writable. * * @param busno * @return 1 if the device exists and is usable, 0 if not */ int verify_i2c_access_for_single_bus(int busno) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); int result = 0; if (!i2c_device_exists(busno)) { fprintf(stderr, "Bus /dev/i2c-%d does not exist.\n", busno); } else if (sysfs_is_ignorable_i2c_device(busno)) { fprintf(stderr, "Bus /dev/i2c-%d cannot be used for DDC/CI communication.\n", busno); } else { char fnbuf[20]; // oversize to avoid -Wformat-truncation error snprintf(fnbuf, sizeof(fnbuf), "/dev/i2c-%d", busno); if ( access(fnbuf, R_OK|W_OK) < 0 ) { int errsv = errno; // EACCESS if lack permissions, ENOENT if file doesn't exist if (errsv == ENOENT) { fprintf(stderr, "Device %s does not exist. Error = %s\n", fnbuf, linux_errno_desc(errsv)); } else { fprintf(stderr, "Device %s is not readable and writable. Error = %s\n", fnbuf, linux_errno_desc(errsv) ); include_open_failures_reported(busno); } } else result = 1; } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %d.", result); return result; } /** Master initialization function * * \param parsed_cmd parsed command line * \return ok if successful, false if error */ STATIC bool master_initializer(Parsed_Cmd * parsed_cmd) { bool debug = false; DBGF(debug, "Starting ..."); bool ok = false; Error_Info * submaster_errs = submaster_initializer(parsed_cmd); // shared with libddcutil if (submaster_errs) { errinfo_report_details(submaster_errs, 0); ERRINFO_FREE(submaster_errs); goto bye; } #ifdef ENABLE_ENVCMDS if (parsed_cmd->cmd_id != CMDID_ENVIRONMENT) { // will be reported by the environment command if (!validate_environment()) goto bye; } #else if (!validate_environment()) goto bye; #endif ok = true; bye: DBGF(debug, "Done"); return ok; } STATIC void ensure_vcp_version_set(Display_Handle * dh) { bool debug = false; DBGMSF(debug, "Starting. dh=%s", dh_repr(dh)); DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); if (vspec.major < 2 && get_output_level() >= DDCA_OL_NORMAL) { f0printf(stdout, "VCP (aka MCCS) version for display is undetected or less than 2.0. " "Interpretation may not be accurate.\n"); } DBGMSF(debug, "Done"); } typedef enum { DISPLAY_ID_REQUIRED, DISPLAY_ID_USE_DEFAULT, DISPLAY_ID_OPTIONAL } Displayid_Requirement; const char * displayid_requirement_name(Displayid_Requirement id) { char * result = NULL; switch (id) { case DISPLAY_ID_REQUIRED: result = "DISPLAY_ID_REQUIRED"; break; case DISPLAY_ID_USE_DEFAULT: result = "DISPLAY_ID_USE_DEFAULT"; break; case DISPLAY_ID_OPTIONAL: result = "DISPLAY_ID_OPTIONAL"; break; } return result; } /** Returns a display reference for the display specified on the command line, * or, if a display is not optional for the command, a reference to the * default display (--display 1). * * \param parsed_cmd parsed command line * \param displayid_required how to handle no display specified on command line * \param dref_loc where to return display reference * \retval DDCRC_OK * \retval DDCRC_INVALID_DISPLAY */ Status_Errno_DDC find_dref( Parsed_Cmd * parsed_cmd, Displayid_Requirement displayid_required, Display_Ref ** dref_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "did: %s, displayid_required: %s", did_repr(parsed_cmd->pdid), displayid_requirement_name(displayid_required)); FILE * outf = fout(); Status_Errno_DDC final_result = DDCRC_OK; Display_Ref * dref = NULL; Display_Identifier * did_work = parsed_cmd->pdid; if (did_work && did_work->id_type == DISP_ID_BUSNO) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Special handling for explicit --busno"); int busno = did_work->busno; // is this really a monitor? I2C_Bus_Info * businfo = i2c_detect_single_bus(busno); if (businfo) { if (businfo->edid) { dref = create_bus_display_ref(busno); dref->dispno = DISPNO_INVALID; // or should it be DISPNO_NOT_SET? dref->pedid = copy_parsed_edid(businfo->edid); dref->mmid = mmk_new( dref->pedid->mfg_id, dref->pedid->model_name, dref->pedid->product_code); // dref->driver_name = get_i2c_device_sysfs_driver(busno); // DBGMSG("driver_name = %p -> %s", dref->driver_name, dref->driver_name); dref->drm_connector = g_strdup(businfo->drm_connector_name); dref->drm_connector_id = businfo->drm_connector_id; // dref->pedid = i2c_get_parsed_edid_by_busno(did_work->busno); dref->detail = businfo; dref->flags |= DREF_DDC_IS_MONITOR_CHECKED; dref->flags |= DREF_DDC_IS_MONITOR; dref->flags |= DREF_TRANSIENT; Error_Info * err = ddc_initial_checks_by_dref(dref, false); if (err) { f0printf(outf, "DDC communication failed for monitor on bus /dev/i2c-%d\n", busno); free_display_ref(dref); // i2c_free_bus_info(businfo); // double free dref = NULL; ERRINFO_FREE_WITH_REPORT(err, debug); final_result = DDCRC_INVALID_DISPLAY; } else { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Synthetic Display_Ref"); final_result = DDCRC_OK; } if (dref && (dref->flags&DREF_DPMS_SUSPEND_STANDBY_OFF)) { // should go nowhere, but just in case: f0printf(outf, "Monitor on bus /dev/i2c-%d is in a DPMS sleep mode. Expect DDC errors.", busno); } } // has edid else { // no EDID found f0printf(fout(), "No monitor detected on bus /dev/i2c-%d\n", busno); // i2c_free_bus_info(businfo); // double free final_result = DDCRC_INVALID_DISPLAY; } } // businfo allocated else { f0printf(fout(), "Bus /dev/i2c-%d not found\n", busno); final_result = DDCRC_INVALID_DISPLAY; } } // DISP_ID_BUSNO else { if (!did_work && displayid_required == DISPLAY_ID_OPTIONAL) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "No monitor specified, none required for command"); dref = NULL; final_result = DDCRC_OK; } else { bool temporary_did_work = false; if (!did_work) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "No monitor specified, treat as --display 1"); did_work = create_dispno_display_identifier(1); // default monitor temporary_did_work = true; } // assert(did_work); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Detecting displays..."); ddc_ensure_displays_detected(); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "display detection complete"); dref = get_display_ref_for_display_identifier(did_work, CALLOPT_NONE); if (temporary_did_work) free_display_identifier(did_work); if (!dref) f0printf(ferr(), "Display not found\n"); final_result = (dref) ? DDCRC_OK : DDCRC_INVALID_DISPLAY; } } // !DISP_ID_BUSNO *dref_loc = dref; DBGTRC_RET_DDCRC(debug, TRACE_GROUP, final_result, "*dref_loc = %p -> %s", *dref_loc, dref_repr_t(*dref_loc) ); return final_result; } /** Execute commands that either require a display or for which a display is optional. * If a display is required, it has been opened and its display handle is passed * as an argument. * * \param parsed_cmd parsed command line * \param dh display handle, if NULL no display was specified on the * command line and the command does not require a display * \retval EXIT_SUCCESS * \retval EXIT_FAILURE */ int execute_cmd_with_optional_display_handle( Parsed_Cmd * parsed_cmd, Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh = %p -> %s", dh, dh_repr(dh)); int main_rc = EXIT_SUCCESS; if (dh) { if (!vcp_version_eq(parsed_cmd->mccs_vspec, DDCA_VSPEC_UNKNOWN)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Forcing mccs_vspec=%d.%d", parsed_cmd->mccs_vspec.major, parsed_cmd->mccs_vspec.minor); dh->dref->vcp_version_cmdline = parsed_cmd->mccs_vspec; } } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s", cmdid_name(parsed_cmd->cmd_id)); switch(parsed_cmd->cmd_id) { case CMDID_LOADVCP: { // loadvcp will search monitors to find the one matching the // identifiers in the record ddc_ensure_displays_detected(); Status_Errno_DDC ddcrc = app_loadvcp_by_file(parsed_cmd->args[0], dh); main_rc = (ddcrc == 0) ? EXIT_SUCCESS : EXIT_FAILURE; break; } case CMDID_CAPABILITIES: { assert(dh); if (app_check_dynamic_features(dh->dref)) { ensure_vcp_version_set(dh); DDCA_Status ddcrc = app_capabilities(dh); main_rc = (ddcrc==0) ? EXIT_SUCCESS : EXIT_FAILURE; } else main_rc = EXIT_FAILURE; break; } case CMDID_GETVCP: { assert(dh); if (app_check_dynamic_features(dh->dref)) { ensure_vcp_version_set(dh); Public_Status_Code psc = app_show_feature_set_values_by_dh(dh, parsed_cmd); main_rc = (psc==0) ? EXIT_SUCCESS : EXIT_FAILURE; } else main_rc = EXIT_FAILURE; } break; case CMDID_SETVCP: { assert(dh); if (app_check_dynamic_features(dh->dref)) { // ensure_vcp_version_set(dh); int rc = app_setvcp(parsed_cmd, dh); main_rc = (rc == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } else main_rc = EXIT_FAILURE; } break; case CMDID_SAVE_SETTINGS: assert(dh); if (parsed_cmd->argct != 0) { f0printf(fout(), "SCS command takes no arguments\n"); main_rc = EXIT_FAILURE; } else if (dh->dref->io_path.io_mode == DDCA_IO_USB) { f0printf(fout(), "SCS command is not supported for USB devices\n"); main_rc = EXIT_FAILURE; } else { main_rc = EXIT_SUCCESS; Error_Info * ddc_excp = ddc_save_current_settings(dh); if (ddc_excp) { f0printf(fout(), "Save current settings failed. rc=%s\n", psc_desc(ddc_excp->status_code)); if (ddc_excp->status_code == DDCRC_RETRIES) f0printf(fout(), " Try errors: %s", errinfo_causes_string(ddc_excp) ); errinfo_report(ddc_excp, 0); // ** ALTERNATIVE **/ errinfo_free(ddc_excp); // ERRINFO_FREE_WITH_REPORT(ddc_excp, report_exceptions); main_rc = EXIT_FAILURE; } } break; case CMDID_DUMPVCP: { assert(dh); // MCCS vspec can affect whether a feature is NC or TABLE if (app_check_dynamic_features(dh->dref)) { ensure_vcp_version_set(dh); Public_Status_Code psc = app_dumpvcp_as_file(dh, (parsed_cmd->argct > 0) ? parsed_cmd->args[0] : NULL ); main_rc = (psc==0) ? EXIT_SUCCESS : EXIT_FAILURE; } else main_rc = EXIT_FAILURE; break; } case CMDID_READCHANGES: { assert(dh); if (app_check_dynamic_features(dh->dref)) { ensure_vcp_version_set(dh); app_read_changes_forever(dh, parsed_cmd->flags & CMD_FLAG_X52_NO_FIFO); // only returns if fatal error main_rc = EXIT_FAILURE; } else main_rc = EXIT_FAILURE; break; } case CMDID_PROBE: { assert(dh); if (app_check_dynamic_features(dh->dref)) { ensure_vcp_version_set(dh); app_probe_display_by_dh(dh); main_rc = EXIT_SUCCESS; } else main_rc = EXIT_FAILURE; break; } default: main_rc = EXIT_FAILURE; break; } // switch DBGTRC_DONE(debug, TRACE_GROUP, "Returning %s(%d)", (main_rc == 0) ? "EXIT_SUCCESS" : "EXIT_FAILURE", main_rc); return main_rc; } DDCA_Syslog_Level preparse_syslog_level(int argc, char** argv) { bool debug = false; DDCA_Syslog_Level result = DDCA_SYSLOG_NOT_SET; char * syslog_arg = NULL; int syslog_pos = ntsa_find(argv, "--syslog"); if (syslog_pos >= 0 && syslog_pos < (argc-1)) syslog_arg = argv[syslog_pos+1]; else { syslog_pos = ntsa_findx(argv, "--syslog=", str_starts_with); if (syslog_pos >= 0) syslog_arg = argv[syslog_pos] + strlen("--syslog"); } if (syslog_arg) { DBGMSF(debug, "Parsing initial log level: |%s|", syslog_arg); GPtrArray *sink = g_ptr_array_new(); g_ptr_array_set_free_func(sink, g_free); DDCA_Syslog_Level parsed_level; bool ok_level = parse_syslog_level(syslog_arg, &parsed_level, sink); g_ptr_array_free(sink, true); if (ok_level) result = parsed_level; } DBGMSF(debug, "Returning: %s", syslog_level_name(result)); return result; } /** Terminates watch displays thread in case of CTRL-C etc. then * terminates execution. */ void interrupt_handler(int sig) { bool debug = false; if (debug) printf("\nHandling interrupt\n"); // signal(sig, SIG_IGN); DDCA_Display_Event_Class event_classes = DDCA_EVENT_CLASS_ALL; dw_stop_watch_displays(false, &event_classes); if (debug) { printf("ddc_stop_watch_displays() returned\n"); printf("Calling exit()\n"); } exit(0); } // // Mainline // /** **ddcutil** program mainline. * * @param argc number of command line arguments * @param argv pointer to array of argument strings * * @retval EXIT_SUCCESS normal exit * @retval EXIT_FAILURE an error occurred */ int main(int argc, char *argv[]) { bool main_debug = false; char * s = getenv("DDCUTIL_DEBUG_MAIN"); if (s && strlen(s) > 0) main_debug = true; int main_rc = EXIT_FAILURE; bool start_time_reported = false; bool explicit_syslog_level = false; syslog_level = DEFAULT_DDCUTIL_SYSLOG_LEVEL; bool syslog_opened = false; bool preparse_verbose = false; bool skip_config = false; Parsed_Cmd * parsed_cmd = NULL; bool traced_function_stack_initialized = false; time_t program_start_time = time(NULL); char * program_start_time_s = asctime(localtime(&program_start_time)); if (program_start_time_s[strlen(program_start_time_s)-1] == 0x0a) program_start_time_s[strlen(program_start_time_s)-1] = 0; add_local_rtti_functions(); // add entries for this file init_base_services(); // so tracing related modules are initialized init_ddc_services(); // initializes i2c, usb, ddc, vcp, dynvcp init_dw_services(); // initializes subdir dw init_app_ddcutil_services(); #ifdef ENABLE_ENVCMDS init_app_sysenv_services(); #endif DBGF(main_debug, "init_base_services() complete, ol = %s", output_level_name(get_output_level()) ); // dbgrpt_rtti_func_name_table(3); char ** new_argv = NULL; int new_argc = 9; char * untokenized_cmd_prefix = NULL; char * configure_fn = NULL; DDCA_Syslog_Level preparsed_level = preparse_syslog_level(argc, argv); if (preparsed_level != DDCA_SYSLOG_NOT_SET) { DBGF(main_debug, "Setting syslog_level = %s from preparse_syslog_level()", syslog_level_name(preparsed_level)); syslog_level = preparsed_level; explicit_syslog_level = true; } DBGF(main_debug, "syslog_level=%s, explicit_syslog_level=%s", syslog_level_name(syslog_level), sbool(explicit_syslog_level)); preparse_verbose = ntsa_find(argv, "--verbose") >= 0 || ntsa_find(argv, "-v") >= 0; skip_config = (ntsa_find(argv, "--noconfig") >= 0); if (skip_config) { // DBGMSG("Skipping config file"); new_argv = ntsa_copy(argv, true); new_argc = argc; } else { GPtrArray * config_file_errs = g_ptr_array_new_with_free_func(g_free); int apply_config_rc = apply_config_file( "ddcutil", // use this section of config file argc, argv, &new_argc, &new_argv, &untokenized_cmd_prefix, &configure_fn, config_file_errs); DBGF(main_debug, "apply_config_file() returned %s", psc_desc(apply_config_rc)); DBGF(main_debug, "syslog_level=%s, explicit_syslog_level=%s", syslog_level_name(syslog_level), SBOOL(explicit_syslog_level)); if (config_file_errs->len > 0) { // Special handling for config file errors. // Open system log early. if (syslog_level > DDCA_SYSLOG_NEVER) { openlog("ddcutil", // prepended to every log message LOG_CONS | // write to system console if error sending to system logger LOG_PID, // include caller's process id LOG_USER); // generic user program, syslogger can use to determine how to handle syslog_opened = true; DBGF(main_debug, "openlog() executed for config file errors, explicit syslog level"); } // Write error msgs to stderr and (if opened) the system log f0printf(ferr(), "Error(s) reading ddcutil configuration from file %s:\n", configure_fn); if (syslog_opened) syslog(LOG_ERR, "Error(s) reading ddcutil configuration from file %s:\n", configure_fn); for (int ndx = 0; ndx < config_file_errs->len; ndx++) { char * s = g_strdup_printf(" %s\n", (char *) g_ptr_array_index(config_file_errs, ndx)); f0printf(ferr(), s); if (syslog_opened) syslog(LOG_ERR, "%s", s); free(s); } } g_ptr_array_free(config_file_errs, true); if (apply_config_rc < 0) goto bye; if (preparse_verbose) { if (untokenized_cmd_prefix && strlen(untokenized_cmd_prefix) > 0) { fprintf(fout(), "Applying ddcutil options from %s: %s\n", configure_fn, untokenized_cmd_prefix); if (syslog_opened) syslog(LOG_INFO, "Applying ddcutil options from %s: %s\n", configure_fn, untokenized_cmd_prefix); } } } assert(new_argc == ntsa_length(new_argv)); if (main_debug) { DBG("new_argc = %d, new_argv:", new_argc); for (int ndx=0; new_argv[ndx]; ndx++) { DBG(" %s", new_argv[ndx]); } } preparsed_level = preparse_syslog_level(new_argc, new_argv); if (preparsed_level != DDCA_SYSLOG_NOT_SET) { DBGF(main_debug, "Setting syslog_level = %s from preparse_syslog_level()", syslog_level_name(preparsed_level)); syslog_level = preparsed_level; explicit_syslog_level = true; } DBGF(main_debug, "Before parse_command(): syslog_level=%s, explicit_syslog_level=%s", syslog_level_name(syslog_level), SBOOL(explicit_syslog_level)); GPtrArray * parser_errmsgs = g_ptr_array_new_with_free_func(g_free); parsed_cmd = parse_command(new_argc, new_argv, MODE_DDCUTIL, parser_errmsgs); DBGF(main_debug, "parse_command() returned %p", parsed_cmd); ntsa_free(new_argv, true); DBGF(main_debug, "After parse_command(): syslog_level=%s, explicit_syslog_level=%s", syslog_level_name(syslog_level), SBOOL(explicit_syslog_level)); if (parser_errmsgs->len > 0) { // Special handling for parser error messages. // Open system log early. if (syslog_level > DDCA_SYSLOG_NEVER) { openlog("ddcutil", // prepended to every log message LOG_CONS | // write to system console if error sending to system logger LOG_PID, // include caller's process id LOG_USER); // generic user program, syslogger can use to determine how to handle syslog_opened = true; DBGF(main_debug, "openlog() executed for parser errors"); } // Write error msgs to stderr and (if opened) the system log // f0printf(ferr(), "Command error(s):\n"); // if (syslog_opened) // syslog(LOG_ERR, "Error(s) in ddcutil command:\n"); for (int ndx = 0; ndx < parser_errmsgs->len; ndx++) { char * s = g_strdup_printf(" %s\n", (char *) g_ptr_array_index(parser_errmsgs, ndx)); f0printf(ferr(), s); if (syslog_opened) syslog(LOG_ERR, "%s", s); free(s); } DBGF(main_debug, "Done writing msgs"); } g_ptr_array_free(parser_errmsgs, true); if (!parsed_cmd) goto bye; // main_rc == EXIT_FAILURE if (parsed_cmd->cmd_id == CMDID_CHKUSBMON) { // prevent io parsed_cmd->flags &= ~(CMD_FLAG_DSA2 | CMD_FLAG_ENABLE_CACHED_CAPABILITIES | CMD_FLAG_ENABLE_CACHED_DISPLAYS); } Error_Info * errs = init_tracing(parsed_cmd); if (errs) { for (int ndx = 0; ndx < errs->cause_ct; ndx++) { Error_Info * cur = errs->causes[ndx]; fprintf(stderr, "%s\n", cur->detail); if (syslog_opened) syslog(LOG_ERR, "%s\n", cur->detail); } ERRINFO_FREE(errs); goto bye; } if (preparse_verbose) parsed_cmd->output_level = DDCA_OL_VERBOSE; DBGF(main_debug,"parsed_cmd->syslog_level =%d=%s, syslog_level=%d=%s, explicit_syslog_level=%s", parsed_cmd->syslog_level, syslog_level_name(parsed_cmd->syslog_level), syslog_level, syslog_level_name(syslog_level), sbool(explicit_syslog_level)); if (explicit_syslog_level) parsed_cmd->syslog_level = syslog_level; if (parsed_cmd->syslog_level == DDCA_SYSLOG_NEVER && syslog_opened) { // oops DBGF(main_debug, "parsed_cmd=>syslog_level == DDCA_SYSLOG_NEVER, calling closelog()"); closelog(); syslog_opened = false; } else if (parsed_cmd->syslog_level > DDCA_SYSLOG_NEVER ) { // global openlog("ddcutil", // prepended to every log message LOG_CONS | // write to system console if error sending to system logger LOG_PID, // include caller's process id LOG_USER); // generic user program, syslogger can use to determine how to handle syslog_opened = true; DBGF(main_debug, "Normal openlog() executed for parsed_cmd->syslog_level "); } // tracing is sufficiently initialized, can report start time start_time_reported = parsed_cmd->traced_groups || parsed_cmd->traced_files || IS_TRACING() || main_debug; DBGF(main_debug, "start_time_reported = %s", SBOOL(start_time_reported)); DBGF(start_time_reported, "Starting %s execution, %s", parser_mode_name(parsed_cmd->parser_mode), program_start_time_s); SYSLOG2(DDCA_SYSLOG_NOTICE, "Starting. ddcutil version %s", get_full_ddcutil_version()); if (parsed_cmd->flags & CMD_FLAG_ENABLE_TRACED_FUNCTION_STACK) { push_traced_function(__func__); traced_function_stack_initialized = true; } if (preparse_verbose) { if (untokenized_cmd_prefix && strlen(untokenized_cmd_prefix) > 0) { SYSLOG2(DDCA_SYSLOG_NOTICE,"Applying ddcutil options from %s: %s", configure_fn, untokenized_cmd_prefix); } } #ifdef UNUSED #ifdef USE_X11 if (!(parsed_cmd->flags&CMD_FLAG_F12)) { dpms_check_x11_asleep(); if (dpms_state & DPMS_STATE_X11_ASLEEP) { // DBGMSF(true, "DPMS sleep mode is active. Terminating execution."); MSG_W_SYSLOG(DDCA_SYSLOG_NOTICE, "DPMS sleep mode is active. Terminating execution"); goto bye; } } #endif #endif if (!master_initializer(parsed_cmd)) goto bye; if (parsed_cmd->cmd_id == CMDID_NOOP) { rpt_vstring(0, "Executing options only"); rpt_nl(); } if (parsed_cmd->flags&CMD_FLAG_SHOW_SETTINGS) report_all_options(parsed_cmd, configure_fn, untokenized_cmd_prefix, 0); // xdg_tests(); // for development if (parsed_cmd->flags2 & CMD_FLAG2_F2) { consolidated_i2c_sysfs_report(0); if (use_drm_connector_states) report_drm_connector_states(0); // rpt_label(0, "*** Tests Done ***"); // rpt_nl(); } Call_Options callopts = CALLOPT_NONE; i2c_forceable_slave_addr_flag = parsed_cmd->flags & CMD_FLAG_FORCE_SLAVE_ADDR; #ifdef ENABLE_USB usb_ignore_hiddevs(parsed_cmd->ignored_hiddevs); Vid_Pid_Value * values = (parsed_cmd->ignored_usb_vid_pid_ct == 0) ? NULL : parsed_cmd->ignored_usb_vid_pids; usb_ignore_vid_pid_values(parsed_cmd->ignored_usb_vid_pid_ct, values); #endif main_rc = EXIT_SUCCESS; // from now on assume success; // DBGTRC_NOPREFIX(main_debug, TRACE_GROUP, "Initialization complete, process commands"); DBGF(main_debug, "Initialization complete, process commands"); if (parsed_cmd->cmd_id == CMDID_LISTVCP) { // vestigial app_listvcp(stdout); main_rc = EXIT_SUCCESS; } else if (parsed_cmd->cmd_id == CMDID_VCPINFO) { bool vcpinfo_ok = app_vcpinfo(parsed_cmd); main_rc = (vcpinfo_ok) ? EXIT_SUCCESS : EXIT_FAILURE; } else if (parsed_cmd->cmd_id == CMDID_LIST_RTTI) { report_rtti_func_name_table(0, "Functions traceable by name:"); main_rc = EXIT_SUCCESS; } // else if (parsed_cmd->cmd_id == CMDID_DISCARD_CACHE) { // i2c_discard_caches(parsed_cmd->discarded_cache_types); // } else if (parsed_cmd->cmd_id == CMDID_NOOP) { // rpt_vstring(0, "Executing options only"); // already reported main_rc = EXIT_SUCCESS; } else if (parsed_cmd->cmd_id == CMDID_C1) { bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); rpt_label(0, "Executing temporarily defined command C1: watch for display connection/disconnection"); if (!all_video_adapters_implement_drm) { DBGMSG("Requires DRM capable video drivers."); main_rc = EXIT_FAILURE; } else { // Catch CTRL-C to terminate watch thread, then exit: signal(SIGINT, interrupt_handler); publish_all_display_refs = true; ddc_ensure_displays_detected(); Error_Info * erec = dw_start_watch_displays(DDCA_EVENT_CLASS_DISPLAY_CONNECTION); if (erec) { ERRINFO_FREE_WITH_REPORT(erec, true); main_rc = EXIT_FAILURE; } else { rpt_label(0,"Watching for 10 hours"); sleep(10*60*60); rpt_label(0,"Terminating execution after 10 hours"); dw_stop_watch_displays(true, NULL); main_rc = EXIT_SUCCESS; } } rpt_set_ornamentation_enabled(saved_prefix_report_output); } else if (parsed_cmd->cmd_id == CMDID_C2 || parsed_cmd->cmd_id == CMDID_C3 || parsed_cmd->cmd_id == CMDID_C4) { bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); Cmd_Desc * desc = get_command(parsed_cmd->cmd_id); rpt_vstring(0,"Unrecognized command: %s", desc->cmd_name); main_rc = EXIT_FAILURE; rpt_set_ornamentation_enabled(saved_prefix_report_output); } #ifdef INCLUDE_TESTCASES else if (parsed_cmd->cmd_id == CMDID_LISTTESTS) { show_test_cases(); main_rc = EXIT_SUCCESS; } #endif // start of commands that actually access monitors else if (parsed_cmd->cmd_id == CMDID_DETECT) { DBGTRC_NOPREFIX(main_debug, TRACE_GROUP, "Detecting displays..."); bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); verify_i2c_access(); if ( parsed_cmd->flags2 & CMD_FLAG2_F4) { test_display_detection_variants(); } else { // normal case ddc_ensure_displays_detected(); ddc_report_displays(/*include_invalid_displays=*/ true, 0); } rpt_set_ornamentation_enabled(saved_prefix_report_output); DBGTRC_NOPREFIX(main_debug, TRACE_GROUP, "Display detection complete"); main_rc = EXIT_SUCCESS; } #ifdef INCLUDE_TESTCASES else if (parsed_cmd->cmd_id == CMDID_TESTCASE) { bool ok = app_testcases(parsed_cmd); main_rc = (ok) ? EXIT_SUCCESS : EXIT_FAILURE; } #endif #ifdef ENABLE_ENVCMDS else if (parsed_cmd->cmd_id == CMDID_ENVIRONMENT) { DBGTRC_NOPREFIX(main_debug, TRACE_GROUP, "Processing command ENVIRONMENT..."); dup2(1,2); // redirect stderr to stdout bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); if (parsed_cmd->output_level >= DDCA_OL_VERBOSE) force_envcmd_settings(parsed_cmd); query_sysenv(parsed_cmd->flags & CMD_FLAG_QUICK); rpt_set_ornamentation_enabled(saved_prefix_report_output); main_rc = EXIT_SUCCESS; } else if (parsed_cmd->cmd_id == CMDID_USBENV) { #ifdef ENABLE_USB DBGTRC_NOPREFIX(main_debug, TRACE_GROUP, "Processing command USBENV..."); dup2(1,2); // redirect stderr to stdout bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); query_usbenv(); rpt_set_ornamentation_enabled(saved_prefix_report_output); main_rc = EXIT_SUCCESS; #else f0printf(fout(), "ddcutil was not built with support for USB connected monitors\n"); main_rc = EXIT_FAILURE; #endif } #endif else if (parsed_cmd->cmd_id == CMDID_CHKUSBMON) { #ifdef ENABLE_USB // DBGMSG("Processing command chkusbmon...\n"); DBGTRC_NOPREFIX(main_debug, TRACE_GROUP, "Processing command CHKUSBMON..."); bool is_monitor = (parsed_cmd->flags&CMD_FLAG_ENABLE_USB) && check_usb_monitor( parsed_cmd->args[0] ); main_rc = (is_monitor) ? EXIT_SUCCESS : EXIT_FAILURE; #else main_rc = EXIT_FAILURE; #endif } #ifdef ENABLE_ENVCMDS else if (parsed_cmd->cmd_id == CMDID_INTERROGATE) { app_interrogate(parsed_cmd); main_rc = EXIT_SUCCESS; } #endif // *** Commands that may require Display Identifier *** else { Status_Errno_DDC rc = 0; int useful_bus_ct = 0; Display_Ref * dref = NULL; if (parsed_cmd->pdid && parsed_cmd->pdid->id_type == DISP_ID_BUSNO) { useful_bus_ct = verify_i2c_access_for_single_bus(parsed_cmd->pdid->busno); } else { useful_bus_ct = verify_i2c_access(); } if (useful_bus_ct == 0) { main_rc = EXIT_FAILURE; } else { rc = find_dref(parsed_cmd, (parsed_cmd->cmd_id == CMDID_LOADVCP) ? DISPLAY_ID_OPTIONAL : DISPLAY_ID_REQUIRED, &dref); if (rc != DDCRC_OK) { main_rc = EXIT_FAILURE; } else { Display_Handle * dh = NULL; if (dref) { DBGMSF(main_debug, "mainline - display detection complete, about to call ddc_open_display() for dref" ); Error_Info* err = ddc_open_display(dref, callopts, &dh); ASSERT_IFF( !err, dh); if (!dh) { f0printf(ferr(), "Error opening %s: %s\n", dref_repr_t(dref), psc_name(err->status_code)); errinfo_free(err); main_rc = EXIT_FAILURE; } } // dref if (main_rc == EXIT_SUCCESS) { main_rc = execute_cmd_with_optional_display_handle(parsed_cmd, dh); } if (dh) { Error_Info * err = ddc_close_display(dh); if (err) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "%s: %s", err->detail, psc_desc(err->status_code)); errinfo_free(err); } } } if (dref && (dref->flags & DREF_TRANSIENT)) free_display_ref(dref); } } DBGTRC(main_debug, DDCA_TRC_TOP, "After command processing"); if (parsed_cmd->stats_types != DDCA_STATS_NONE && ( ddc_displays_already_detected() || (parsed_cmd->pdid && parsed_cmd->pdid->id_type == DISP_ID_BUSNO) ) #ifdef ENABLE_ENVCMDS && parsed_cmd->cmd_id != CMDID_INTERROGATE #endif ) { ddc_report_stats_main( parsed_cmd->stats_types, parsed_cmd->flags & CMD_FLAG_VERBOSE_STATS, parsed_cmd->flags & CMD_FLAG_INTERNAL_STATS, parsed_cmd->flags & CMD_FLAG_STATS_TO_SYSLOG, 0); // report_timestamp_history(); // debugging function } bye: DBGTRC(main_debug, DDCA_TRC_TOP, "at label bye"); free(untokenized_cmd_prefix); free(configure_fn); free_regex_hash_table(); if (parsed_cmd && parsed_cmd->cmd_id != CMDID_CHKUSBMON && parsed_cmd->cmd_id != CMDID_DISCARD_CACHE) { if (dsa2_is_enabled()) dsa2_save_persistent_stats(); if (display_caching_enabled) ddc_store_displays_cache(); } if (parsed_cmd) free_parsed_cmd(parsed_cmd); if (traced_function_stack_initialized) DBGTRC_DONE(main_debug, TRACE_GROUP, "main_rc=%d", main_rc); else DBGTRC_DONE_WO_TRACED_FUNCTION_STACK(main_debug, TRACE_GROUP, "main_rc=%d", main_rc); time_t end_time = time(NULL); char * end_time_s = asctime(localtime(&end_time)); if (end_time_s[strlen(end_time_s)-1] == 0x0a) end_time_s[strlen(end_time_s)-1] = 0; DBGMSF(start_time_reported, "ddcutil execution complete, %s", end_time_s); DBGMSF(main_debug, "syslog_opened=%s", sbool(syslog_opened)); if (syslog_opened) { SYSLOG2(DDCA_SYSLOG_NOTICE, "Terminating. Returning %d", main_rc); DBGF(main_debug, "Calling closelog()..."); closelog(); } // ddc_stop_watch_displays(true,NULL); terminate_ddc_services(); terminate_base_services(); // free_all_traced_function_stacks(); free_current_traced_function_stack(); return main_rc; } static void add_local_rtti_functions() { RTTI_ADD_FUNC(main); RTTI_ADD_FUNC(execute_cmd_with_optional_display_handle); RTTI_ADD_FUNC(find_dref); RTTI_ADD_FUNC(verify_i2c_access); RTTI_ADD_FUNC(verify_i2c_access_for_single_bus); #ifdef UNUSED #ifdef TARGET_LINUX RTTI_ADD_FUNC(validate_environment_using_libkmod); #endif #endif } ddcutil-2.2.0/src/app_ddcutil/app_capabilities.c0000644000175000001440000001043614441414365015346 /** @file app_capabilities.c * * Implement the CAPABILITIES command */ // Copyright (C) 2020-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include "util/data_structures.h" #include "util/error_info.h" #include "util/report_util.h" #include "util/string_util.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/displays.h" #include "base/rtti.h" /** \endcond */ #include "dynvcp/dyn_parsed_capabilities.h" #include "ddc/ddc_read_capabilities.h" #include "app_ddcutil/app_capabilities.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_TOP; /** Gets the capabilities string for a display. * * The value is cached as this is an expensive operation. * * @param dh display handle * @param caps_loc location at which to return pointer to capabilities string. * @return status code * * The returned pointer points to a string that is part of the * display handle. It should NOT be freed by the caller. */ DDCA_Status app_get_capabilities_string(Display_Handle * dh, char ** capabilities_string_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); FILE * ferr = stderr; Error_Info * ddc_excp = NULL; *capabilities_string_loc = NULL; ddc_excp = ddc_get_capabilities_string(dh, capabilities_string_loc); DDCA_Status psc = ERRINFO_STATUS(ddc_excp); if (ddc_excp) { switch(psc) { case DDCRC_REPORTED_UNSUPPORTED: // should not happen case DDCRC_DETERMINED_UNSUPPORTED: f0printf(ferr, "Unsupported request\n"); break; case DDCRC_RETRIES: f0printf(ferr, "Unable to get capabilities for monitor on %s. Maximum DDC retries exceeded.\n", dh_repr(dh)); break; default: f0printf(ferr, "(%s) !!! Unable to get capabilities for monitor on %s\n", __func__, dh_repr(dh)); DBGMSG("Unexpected status code: %s", psc_desc(psc)); } ERRINFO_FREE_WITH_REPORT(ddc_excp, debug || IS_TRACING() || report_freed_exceptions); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, "*capabilities_string_loc -> %s", *capabilities_string_loc); ASSERT_IFF(*capabilities_string_loc, psc==0); return psc; } /** Reports a #Parsed_Capabilities record, respecting dynamic feature definitions * * @param dh display handle * @param pcap #Parsed_Capabilities to report */ void app_show_parsed_capabilities(Display_Handle * dh, Parsed_Capabilities * pcap) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); assert(pcap); if ( dh->dref->io_path.io_mode == DDCA_IO_USB ) pcap->raw_value_synthesized = true; dyn_report_parsed_capabilities(pcap, dh, /* Display_Ref* */ NULL, 0); DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Implements the CAPABILITIES command. * * @param dh #Display_Handle * @return status code */ DDCA_Status app_capabilities(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); char * capabilities_string; DDCA_Status ddcrc; FILE * fout = stdout; ddcrc = app_get_capabilities_string(dh, &capabilities_string); if (ddcrc == 0) { DDCA_Output_Level ol = get_output_level(); if (ol == DDCA_OL_TERSE) { f0printf(fout, "%s capabilities string: %s\n", (dh->dref->io_path.io_mode == DDCA_IO_USB) ? "Synthesized unparsed" : "Unparsed", capabilities_string); } else { // pcaps is always set, but may be damaged if there was a parsing error Parsed_Capabilities * pcaps = parse_capabilities_string(capabilities_string); app_show_parsed_capabilities(dh, pcaps); free_parsed_capabilities(pcaps); } } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, ""); return ddcrc; } void init_app_capabilities() { RTTI_ADD_FUNC(app_get_capabilities_string); RTTI_ADD_FUNC(app_show_parsed_capabilities); RTTI_ADD_FUNC(app_capabilities); } ddcutil-2.2.0/src/app_ddcutil/app_dumpload.c0000644000175000001440000002063514572333721014525 /** @file app_dumpload.c * * Implement commands DUMPVCP and LOADVCP */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #ifdef TARGET_BSD // what goes here? #else #include // PATH_MAX, NAME_MAX #endif #include #include #include #include #include #include #include "util/error_info.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/report_util.h" #include "util/xdg_util.h" /** \endcond */ #include "base/core.h" #include "base/rtti.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_dumpload.h" #include "app_ddcutil/app_dumpload.h" static const char TRACE_GROUP = DDCA_TRC_TOP; // Filename creation /** Uses the identifiers in an EDID and a timestamp to create a VCP filename. * * @param edid pointer to parsed edid * @param time_millis timestamp to use * @param buf buffer in which to return filename * @param bufsz buffer size */ static void create_simple_vcp_fn_by_edid( Parsed_Edid * edid, time_t time_millis, char * buf, int bufsz) { assert(edid); assert(buf && bufsz > 80); char timestamp_text[30]; format_timestamp(time_millis, timestamp_text, 30); g_snprintf(buf, bufsz, "%s-%s-%s.vcp", edid->model_name, edid->serial_ascii, timestamp_text ); str_replace_char(buf, ' ', '_'); // convert blanks to underscores } /** Creates a VCP filename from a #Display_Handle and a timestamp. * * @param dh display handle * @param time_millis timestamp to use * @param buf buffer in which to return filename * @param bufsz buffer size */ static void create_simple_vcp_fn_by_dh( Display_Handle * dh, time_t time_millis, char * buf, int bufsz) { Parsed_Edid * edid = dh->dref->pedid; assert(edid); create_simple_vcp_fn_by_edid(edid, time_millis, buf, bufsz); } /** Executes the DUMPVCP command, writing the output to a file. * * @param dh display handle * @param filename name of file to write to, * if NULL, the file name is generated * @return status code * * If the file name is generated, it is in the ddcutil subdirectory of the * user's XDG home data directory, normally $HOME/.local/share/ddcutil/ */ Status_Errno_DDC app_dumpvcp_as_file(Display_Handle * dh, const char * filename) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, filename=%p->%s", dh_repr(dh), filename, filename); char * actual_filename = NULL; FILE * fout = stdout; FILE * ferr = stderr; Dumpload_Data * data = NULL; Status_Errno_DDC ddcrc = dumpvcp_as_dumpload_data(dh, &data); if (ddcrc == 0) { GPtrArray * strings = convert_dumpload_data_to_string_array(data); FILE * output_fp = NULL; if (filename) { output_fp = fopen(filename, "w+"); if (!output_fp) { ddcrc = -errno; f0printf(ferr, "Unable to open %s for writing: %s\n", filename, strerror(errno)); } actual_filename = g_strdup(filename); } else { char simple_fn_buf[NAME_MAX+1]; time_t time_millis = data->timestamp_millis; create_simple_vcp_fn_by_dh( dh, time_millis, simple_fn_buf, sizeof(simple_fn_buf)); actual_filename = xdg_data_home_file("ddcutil",simple_fn_buf); // control with MsgLevel? f0printf(fout, "Writing file: %s\n", actual_filename); ddcrc = fopen_mkdir(actual_filename, "w+", ferr, &output_fp); ASSERT_IFF(output_fp, ddcrc == 0); if (ddcrc != 0) { f0printf(ferr, "Unable to create '%s', %s\n", actual_filename, strerror(-ddcrc)); } } free_dumpload_data(data); if (output_fp) { int ct = strings->len; int ndx; for (ndx=0; ndxstatus_code == DDCRC_BAD_DATA) { f0printf(ferr, "Invalid data in file %s:\n", fn); for (int ndx = 0; ndx < err->cause_ct; ndx++) { f0printf(ferr, " %s\n", err->causes[ndx]->detail); } } else { // should never occur // errinfo report goes to fout, so send initial msg there as well f0printf(fout(), "Unexpected error reading data:\n"); errinfo_report(err, 1); } } errinfo_free(err); g_ptr_array_free(g_line_array, true); } DBGMSF(debug, "Returning: %p ", data ); return data; } /** Apply the VCP settings stored in a file to the monitor * indicated in that file. * * @param fn file name * @param dh handle for open display * @return status code */ Status_Errno_DDC app_loadvcp_by_file(const char * fn, Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fn=%s, dh=%p %s", fn, dh, (dh) ? dh_repr(dh):""); FILE * fout = stdout; DDCA_Output_Level output_level = get_output_level(); bool verbose = (output_level >= DDCA_OL_VERBOSE); Status_Errno_DDC ddcrc = 0; Error_Info * ddc_excp = NULL; Dumpload_Data * pdata = read_vcp_file(fn); if (!pdata) { // Redundant, read_vcp_file() issues message: // f0printf(ferr, "Unable to load VCP data from file: %s\n", fn); } else { if (verbose || debug) { f0printf(fout, "Loading VCP settings for monitor \"%s\", sn \"%s\" from file: %s\n", pdata->model, pdata->serial_ascii, fn); if (debug) { rpt_push_output_dest(fout); dbgrpt_dumpload_data(pdata, 0); rpt_pop_output_dest(); } } ddc_excp = loadvcp_by_dumpload_data(pdata, dh); if (ddc_excp) { ddcrc = ddc_excp->status_code; f0printf(ferr(), "%s\n", ddc_excp->detail); errinfo_free(ddc_excp); } free_dumpload_data(pdata); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, ""); return ddcrc; } #ifdef UNUSED bool app_loadvcp(const char * fn, Display_Identifier * pdid) { bool debug = false; DBGMSF(debug, "Starting. fn = |%s|, pdid = %s", fn, did_repr(pdid)); bool loadvcp_ok = true; Display_Handle * dh = NULL; Display_Ref * dref = NULL; if (pdid) { dref = get_display_ref_for_display_identifier(pdid, CALLOPT_ERR_MSG); if (!dref) loadvcp_ok = false; else { ddc_open_display(dref, CALLOPT_ERR_MSG, &dh); // rc == 0 iff dh if (!dh) loadvcp_ok = false; } } if (loadvcp_ok) loadvcp_ok = app_loadvcp_by_file(fn, dh); // if we opened the display, close it if (dh) ddc_close_display(dh); if (dref) free_display_ref(dref); DBGMSF(debug, "Done. Returning %s", sbool(loadvcp_ok)); return loadvcp_ok; } #endif void init_app_dumpload() { RTTI_ADD_FUNC(app_dumpvcp_as_file); RTTI_ADD_FUNC(app_loadvcp_by_file); } ddcutil-2.2.0/src/app_ddcutil/app_dynamic_features.c0000644000175000001440000000376514754153540016250 /** @file app_dynamic_features.c */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include "ddcutil_types.h" #include "ddcutil_status_codes.h" #include "util/error_info.h" #include "util/string_util.h" /** \endcond */ #include "base/core.h" #include "base/dynamic_features.h" #include "base/monitor_model_key.h" #include "base/rtti.h" #include "dynvcp/dyn_feature_files.h" #include "app_dynamic_features.h" /** Wraps call to #dfr_check_by_dref(), writing error messages * for errors reported. * * \param dref display reference * \return false if errors occurred, true otherwise */ bool app_check_dynamic_features(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_TOP|DDCA_TRC_UDF, "dref=%s, enable_dynamic_features=%s", dref_repr_t(dref), sbool(enable_dynamic_features)); bool result = true; if (!enable_dynamic_features) // global variable goto bye; Error_Info * errs = dfr_check_by_dref(dref); DDCA_Output_Level ol = get_output_level(); if (errs) { if (errs->status_code == DDCRC_NOT_FOUND) { if (ol >= DDCA_OL_VERBOSE) { f0printf(fout(), "%s\n", errs->detail); } } else { // errinfo_report(errs, 1); f0printf(fout(), "%s\n", errs->detail); for (int ndx = 0; ndx < errs->cause_ct; ndx++) { f0printf(fout(), " %s\n", errs->causes[ndx]->detail); } result = false; } errinfo_free(errs); } else { // dbgrpt_dynamic_features_rec(dfr, 1); if (ol >= DDCA_OL_VERBOSE) { f0printf(fout(), "Processed feature definition file: %s\n", dref->dfr->filename); } } bye: DBGTRC_RET_BOOL(debug, DDCA_TRC_UDF, result, ""); return result; } void init_app_dynamic_features() { RTTI_ADD_FUNC(app_check_dynamic_features); } ddcutil-2.2.0/src/app_ddcutil/app_experimental.c0000644000175000001440000002773714754153540015430 /** @file app_experimental.c */ // Copyright (C) 2021-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include "util/report_util.h" #include "util/string_util.h" #include "util/timestamp.h" #include "base/parms.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_edid.h" #include "i2c/i2c_strategy_dispatcher.h" #include "ddc/ddc_display_ref_reports.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_packet_io.h" #include "dw/dw_common.h" #include "dw/dw_main.h" #include "app_experimental.h" #define REPORT_FLAG_OPTION(_flagno, _action) \ rpt_vstring(depth+1, "Utility option --f"#_flagno" %s %s", \ (parsed_cmd->flags2 & CMD_FLAG2_F##_flagno ) ? "enabled: " : "disabled:", _action) void report_experimental_options(Parsed_Cmd * parsed_cmd, int depth) { bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); #ifdef UNUSED char buf0[80]; g_snprintf(buf0, 80, "Use non-default watch mode (default = %s)", ddc_watch_mode_name(ddc_watch_mode)); #endif char buf5[80]; g_snprintf(buf5, 80, "Use non-default value for EDID read uses I2C layer (default=%s)", SBOOL(DEFAULT_EDID_READ_USES_I2C_LAYER)); rpt_label(depth, "Experimental Options:"); REPORT_FLAG_OPTION(1, "Suppress SE_POST_READ"); REPORT_FLAG_OPTION(2, "Experimental sysfs analysis"); // was Filter phantom displays REPORT_FLAG_OPTION(3, "DDC Null Message never indicates invalid feature"); REPORT_FLAG_OPTION(4, "Read strategy tests"); REPORT_FLAG_OPTION(5, buf5); REPORT_FLAG_OPTION(6, "Use DRM connector states"); REPORT_FLAG_OPTION(7, "Disable phantom display detection"); REPORT_FLAG_OPTION(8, "Redirect report output to syslog"); // REPORT_FLAG_OPTION(9, buf0); REPORT_FLAG_OPTION(9, "Message to syslog only"); REPORT_FLAG_OPTION(10, "Extended sleep for DDC Null Msg"); REPORT_FLAG_OPTION(11, "Explore monitor state tests"); REPORT_FLAG_OPTION(12, "Disable DRM services"); REPORT_FLAG_OPTION(13, "Use all_displays_drm_using_drm_api()"); REPORT_FLAG_OPTION(14, "Debug flock"); #ifdef GET_EDID_USING_SYSFS REPORT_FLAG_OPTION(15, "Verify sysfs EDID reads"); #else REPORT_FLAG_OPTION(15, "Unused"); #endif // REPORT_FLAG_OPTION(16, "Simple report /sys/class/drm"); REPORT_FLAG_OPTION(16, "Tag output messages"); REPORT_FLAG_OPTION(17, "Do not use sysfs connector_id"); REPORT_FLAG_OPTION(18, "Always report UDEV events"); REPORT_FLAG_OPTION(19, "Stabilize added buses with edid"); REPORT_FLAG_OPTION(20, "DO NOT use x37 detection state hash"); REPORT_FLAG_OPTION(21, "Force sysfs unreliable"); REPORT_FLAG_OPTION(22, "Force sysfs reliable"); REPORT_FLAG_OPTION(23, "Set global primitive_sysfs"); REPORT_FLAG_OPTION(24, "Write detect to status if nvidia driver"); REPORT_FLAG_OPTION(25, "Unused"); REPORT_FLAG_OPTION(26, "Traced function stack errors are fatal"); REPORT_FLAG_OPTION(27, "Unused"); REPORT_FLAG_OPTION(28, "Unused"); REPORT_FLAG_OPTION(29, "Unused"); REPORT_FLAG_OPTION(30, "Unused"); REPORT_FLAG_OPTION(31, "Unused"); REPORT_FLAG_OPTION(32, "Unused"); rpt_vstring(depth+1, "Utility option --i1: Extra millisec to wait after apparent display disconnect (default = %d)", DEFAULT_INITIAL_STABILIZATION_MILLISEC); rpt_vstring(depth+1, "Utility option --i2: NULL Response Hack Millis"); rpt_vstring(depth+1, "Utility option --i3: flock_poll_millisec (default = %d)", DEFAULT_FLOCK_POLL_MILLISEC); rpt_vstring(depth+1, "Utility option --i4: flock_max_wait_millisec (default = %d", DEFAULT_FLOCK_MAX_WAIT_MILLISEC); rpt_vstring(depth+1, "Utility option --i5: Max retries for setvcp verification failure"); rpt_vstring(depth+1, "Utility option --i6: Unused"); rpt_vstring(depth+1, "Utility option --i7 Stabilization poll millisec (default=%d)", DEFAULT_STABILIZATION_POLL_MILLISEC); rpt_vstring(depth+1, "Utility option --i8: Display watch udev loop millisec (default = %d)", DEFAULT_UDEV_WATCH_LOOP_MILLISEC); // rpt_vstring(depth+1, "Utility option --i9: Display watch non-udev polling loop millisec (default=%d)", DEFAULT_POLL_WATCH_LOOP_MILLISEC); // rpt_vstring(depth+1, "Utility option --i10: Display watch xevent polling loop millisec (default=%d)", DEFAULT_XEVENT_WATCH_LOOP_MILLISEC); rpt_vstring(depth+1, "Utility option --i9: Unused"); rpt_vstring(depth+1, "Utility option --i10: Unused"); rpt_vstring(depth+1, "Utility option --i11: Unused"); rpt_vstring(depth+1, "Utility option --i12: Unused"); rpt_vstring(depth+1, "Utility option --i13: Unused"); rpt_vstring(depth+1, "Utility option --i14: Unused"); rpt_vstring(depth+1, "Utility option --i15: Unused"); rpt_vstring(depth+1, "Utility option --i16: Unused"); rpt_vstring(depth+1, "Utility option --s1: Unused"); rpt_vstring(depth+1, "Utility option --s2: Unused"); rpt_vstring(depth+1, "Utility option --s3: Unused"); rpt_vstring(depth+1, "Utility option --s4: Unused"); rpt_vstring(depth+1, "Utility option --fl1: Unused"); rpt_vstring(depth+1, "Utility option --fl2: Unused"); rpt_nl(); rpt_set_ornamentation_enabled(saved_prefix_report_output); } #undef REPORT_FLAG_OPTION // // Test display detection variants // typedef enum { _DYNAMIC = 0, _128 = 128, _256 = 256 } Edid_Read_Size_Option; static char * read_size_name(int n) { char * result = NULL; switch (n) { case 0: result = "dynamic"; break; case 128: result = "128"; break; case 256: result = "256"; break; default: result = "INVALID"; break; } return result; } /** Tests for display detection variants. * * Controlled by utility option --f4 */ void test_display_detection_variants() { typedef enum { _FALSE, _TRUE, _DNA } Bytewise_Option; typedef struct { I2C_IO_Strategy_Id i2c_io_strategy_id; bool edid_uses_i2c_layer; Bytewise_Option edid_read_bytewise; // applies when edid_uses_i2c_layer == FALSE Bytewise_Option i2c_read_bytewise; // applies when edid_uses_i2c_layer == TRUE bool write_before_read; Edid_Read_Size_Option edid_read_size; } Choice_Entry; typedef struct { int valid_display_ct; uint64_t elapsed_nanos; } Choice_Results; char * choice_name[] = {"false", "true", "DNA"}; // char * read_size_name[] = {"dynamic", "128", "256"}; Choice_Entry choices[] = // use I2c edid i2c write EDID Read // i2c_io_strategy layer bytewise bytewise b4 read Size // ================ ====== ======== ======= ======= ======== { {I2C_IO_STRATEGY_IOCTL, _DNA, _FALSE, _DNA, _FALSE, _128}, {I2C_IO_STRATEGY_IOCTL, _DNA, _FALSE, _DNA, _FALSE, _256}, {I2C_IO_STRATEGY_IOCTL, _DNA, _FALSE, _DNA, _FALSE, _DYNAMIC}, {I2C_IO_STRATEGY_IOCTL, _DNA, _FALSE, _DNA, _TRUE, _128}, {I2C_IO_STRATEGY_IOCTL, _DNA, _FALSE, _DNA, _TRUE, _256}, {I2C_IO_STRATEGY_IOCTL, _DNA, _FALSE, _DNA, _TRUE, _DYNAMIC}, {I2C_IO_STRATEGY_IOCTL, _DNA, _TRUE, _DNA, _FALSE, _128}, {I2C_IO_STRATEGY_IOCTL, _DNA, _TRUE, _DNA, _FALSE, _256}, {I2C_IO_STRATEGY_IOCTL, _DNA, _TRUE, _DNA, _FALSE, _DYNAMIC}, {I2C_IO_STRATEGY_IOCTL, _DNA, _TRUE, _DNA, _TRUE, _128}, {I2C_IO_STRATEGY_IOCTL, _DNA, _TRUE, _DNA, _TRUE, _256}, {I2C_IO_STRATEGY_IOCTL, _DNA, _TRUE, _DNA, _TRUE, _DYNAMIC}, }; int choice_ct = ARRAY_SIZE(choices); Choice_Results results[ARRAY_SIZE(choices)]; int d = 1; for (int ndx=0; ndx IO STRATEGY %d:", ndx+1); char * s = (cur.i2c_io_strategy_id == I2C_IO_STRATEGY_IOCTL) ? "IOCTL" : "FILEIO"; rpt_vstring(d, "i2c_io_strategy: %s", s); rpt_vstring(d, "EDID read uses I2C layer: %s", (cur.edid_uses_i2c_layer) ? "I2C Layer" : "Directly"); // SBOOL(cur.edid_uses_i2c_layer)); // rpt_vstring(d, "i2c_read_bytewise: %s", choice_name[cur.i2c_read_bytewise]); rpt_vstring(d, "EDID read bytewise: %s", choice_name[cur.edid_read_bytewise]); rpt_vstring(d, "write before read: %s", SBOOL(cur.write_before_read)); rpt_vstring(d, "EDID read size: %s", read_size_name(cur.edid_read_size)); DDC_Read_Bytewise = false; // cur.i2c_read_bytewise; EDID_Read_Bytewise = cur.edid_read_bytewise; EDID_Read_Size = cur.edid_read_size; assert(EDID_Read_Size == 128 || EDID_Read_Size == 256 || EDID_Read_Size == 0); // discard existing detected monitors ddc_discard_detected_displays(); uint64_t start_time = cur_realtime_nanosec(); ddc_ensure_displays_detected(); int valid_ct = ddc_get_display_count(/*include_invalid_displays*/ false); uint64_t end_time = cur_realtime_nanosec(); cur_result->elapsed_nanos = end_time-start_time; rpt_vstring(d, "Valid displays: %d", valid_ct); cur_result->valid_display_ct = valid_ct; rpt_vstring(d, "Elapsed time: %s seconds", formatted_time_t(end_time - start_time)); rpt_nl(); // will include any USB or ADL displays, but that's ok ddc_report_displays(/*include_invalid_displays=*/ true, 0); } rpt_label( d, "SUMMARY"); rpt_nl(); // will be wrong for our purposes if same monitor appears on 2 i2c buses // int total_displays = get_sysfs_drm_edid_count(); // ddc_discard_detected_displays(); // ddc_ensure_displays_detected(); // to perform normal detection // int total_displays = get_display_count(/*include_invalid_displays*/ true); // rpt_vstring(d, "Total Displays (per /sys/class/drm): %d", total_displays); rpt_nl(); rpt_vstring(d, " I2C IO EDID EDID Read Write EDID Read Valid Seconds"); rpt_vstring(d, " Strategy Method Bytewise b4 Read Size Displays "); rpt_vstring(d, " ======= ======== ========= ======= ========= ======== ======="); for (int ndx = 0; ndx < choice_ct; ndx++) { Choice_Entry cur = choices[ndx]; Choice_Results* cur_result = &results[ndx]; rpt_vstring(d, "%2d %-7s %-9s %-7s %-5s %-7s %3d %s", ndx+1, (cur.i2c_io_strategy_id == I2C_IO_STRATEGY_IOCTL) ? "IOCTL" : "FILEIO", (cur.edid_uses_i2c_layer) ? "I2C Layer" : "Directly", // choice_name[cur.i2c_read_bytewise], choice_name[cur.edid_read_bytewise], SBOOL(cur.write_before_read), read_size_name(cur.edid_read_size), cur_result->valid_display_ct, formatted_time_t(cur_result->elapsed_nanos)); } rpt_nl(); #ifdef DO_NOT_DISTRIBUTE rpt_label(d, "Failures"); rpt_nl(); for (int ndx = 0; ndx < choice_ct; ndx++) { Choice_Entry cur = choices[ndx]; Choice_Results* cur_result = &results[ndx]; if (cur_result->valid_display_ct < 3) rpt_vstring(d, "%2d %-7s %-9s %-7s %-5s %-7s %3d %s", ndx+1, (cur.i2c_io_strategy_id == I2C_IO_STRATEGY_FILEIO) ? "FILEIO" : "IOCTL", (cur.edid_uses_i2c_layer) ? "I2C Layer" : "Directly", // choice_name[cur.i2c_read_bytewise], choice_name[cur.edid_read_bytewise], SBOOL(cur.write_before_read), read_size_name(cur.edid_read_size), cur_result->valid_display_ct, formatted_time_t(cur_result->elapsed_nanos)); } #endif } ddcutil-2.2.0/src/app_ddcutil/app_getvcp.c0000644000175000001440000002135214754153540014206 /** @file app_getvcp.c * Implement command GETVCP */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "app_ddcutil/app_getvcp.h" #include "config.h" /** \cond */ #include #include #include #include "util/data_structures.h" #include "util/error_info.h" #include "util/string_util.h" #include "util/report_util.h" #ifdef ENABLE_USB #include "usb_util/hiddev_reports.h" #include "usb_util/hiddev_util.h" #endif /** \endcond */ #include "base/core.h" #include "base/ddc_errno.h" #include "base/rtti.h" #include "cmdline/parsed_cmd.h" #include "vcp/vcp_feature_codes.h" #include "dynvcp/dyn_feature_codes.h" #include "ddc/ddc_output.h" #include "ddc/ddc_vcp_version.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_TOP; /** Shows a single VCP value specified by its #Display_Feature_Metadata * * @param dh handle of open display * @param meta feature metadata * @return status code 0 = normal * DDCRC_INVALID_OPERATION - feature is deprecated or write-only * from get_formatted_value_for_feature_table_entry() */ DDCA_Status app_show_single_vcp_value_by_dfm( Display_Handle * dh, Display_Feature_Metadata * dfm) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Getting feature 0x%02x for %s", dfm->feature_code, dh_repr(dh) ); DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); DDCA_Status ddcrc = 0; DDCA_Vcp_Feature_Code feature_id = dfm->feature_code; if (!(dfm->version_feature_flags & DDCA_READABLE)) { char * feature_name = dfm->feature_name; DDCA_Feature_Flags vflags = dfm->version_feature_flags; // should get vcp version from metadata if (vflags & DDCA_DEPRECATED) printf("Feature %02x (%s) is deprecated in MCCS %d.%d\n", feature_id, feature_name, vspec.major, vspec.minor); else printf("Feature %02x (%s) is not readable\n", feature_id, feature_name); ddcrc = DDCRC_INVALID_OPERATION; } if (ddcrc == 0) { char * formatted_value = NULL; ddcrc = ddc_get_formatted_value_for_dfm( dh, dfm, false, /* suppress_unsupported */ true, /* prefix_value_with_feature_code */ &formatted_value, stdout); /* msg_fh */ if (formatted_value) { printf("%s\n", formatted_value); free(formatted_value); } } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, ""); return ddcrc; } /** Shows a single VCP value specified by its feature code * * @param dh handle of open display * @param feature_id feature code * @param force generate default metadata if unknown feature id * @return 0 - success * DDCRC_UNKNOWN_FEATURE unrecognized feature id and **force** not specified * from #app_show_single_vcp_value_by_dfm() * * Looks up the #Display_Feature_Metadata record for the feature id and calls * #app_show_single_vcp_value_by_dfm() to display the value. * Generates a dummy #Display_Feature_Metadata record for features in the * reserved manufacturer range (xE0..xFF). * if #force is specified, also generates a dummy metadata record for * unrecognized features. */ Status_Errno_DDC app_show_single_vcp_value_by_feature_id( Display_Handle * dh, DDCA_Vcp_Feature_Code feature_id, bool force) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Getting feature 0x%02x for %s, force=%s", feature_id, dh_repr(dh), sbool(force) ); Status_Errno_DDC psc = 0; Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dh( feature_id, dh, true, // check_udf force || feature_id >= 0xe0); // with_default if (!dfm) { printf("Unrecognized VCP feature code: x%02X\n", feature_id); psc = DDCRC_UNKNOWN_FEATURE; } else { psc = app_show_single_vcp_value_by_dfm(dh, dfm); dfm_free(dfm); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, ""); return psc; } /** Shows the VCP values for all features in a VCP feature subset. * * @param dh display handle * @param subset_id feature subset * @param flags option flags * @param features_seen if non-null, collect list of features found * @return from #show_vcp_values() */ Status_Errno_DDC app_show_vcp_subset_values_by_dh( Display_Handle * dh, VCP_Feature_Subset subset_id, Feature_Set_Flags flags, Bit_Set_256 * features_seen) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, subset_id=%s, flags=%s, features_seen=%p", dh_repr(dh), feature_subset_name(subset_id), feature_set_flag_names_t(flags), features_seen ); GPtrArray * collector = NULL; Status_Errno_DDC psc = ddc_show_vcp_values(dh, subset_id, collector, flags, features_seen); if (features_seen) DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, "features_seen=%s", bs256_to_string_t(*features_seen, "x", ", ") ); else DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, ""); return psc; } /** Shows the VCP values for all features indicated by a #Feature_Set_Ref * * @param dh display handle * @param fsref feature set reference * @param flags option flags * @return status code from #app_show_single_vcp_value_by_feature_id_new_dfm() or * #app_show_subset_values_by_dh() */ Status_Errno_DDC app_show_feature_set_values_by_dh( Display_Handle * dh, Parsed_Cmd * parsed_cmd) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh: %s. fsref: %s, flags: %s", dh_repr(dh), fsref_repr_t(parsed_cmd->fref), feature_set_flag_names_t(parsed_cmd->flags)); if (debug || IS_TRACING()) dbgrpt_feature_set_ref(parsed_cmd->fref,1); if (parsed_cmd->flags & CMD_FLAG_EXPLICIT_I2C_SOURCE_ADDR) alt_source_addr = parsed_cmd->explicit_i2c_source_addr; Feature_Set_Ref * fsref = parsed_cmd->fref; // DBGMSG("parsed_cmd->flags: 0x%04x", parsed_cmd->flags); Feature_Set_Flags flags = 0x00; if (parsed_cmd->flags & CMD_FLAG_SHOW_UNSUPPORTED) flags |= FSF_SHOW_UNSUPPORTED; // if (parsed_cmd->flags & CMD_FLAG_FORCE) // flags |= FSF_FORCE; // unused for getvcp, 11/18/2023 if (parsed_cmd->flags & CMD_FLAG_NOTABLE) flags |= FSF_NOTABLE; if (parsed_cmd->flags & CMD_FLAG_RW_ONLY) flags |= FSF_RW_ONLY; if (parsed_cmd->flags & CMD_FLAG_RO_ONLY) flags |= FSF_RO_ONLY; if (parsed_cmd->flags & CMD_FLAG_ENABLE_UDF) flags |= FSF_CHECK_UDF; // this is nonsense, getvcp on a WO feature should be caught by parser if (parsed_cmd->flags & CMD_FLAG_WO_ONLY) { // flags |= FSF_WO_ONLY; DBGMSG("Invalid: GETVCP for WO features"); assert(false); } // char * s0 = feature_set_flag_names(flags); // DBGMSG("flags: 0x%04x - %s", flags, s0); // free(s0); Status_Errno_DDC psc = 0; #ifdef OLD if (fsref->subset == VCP_SUBSET_SINGLE_FEATURE) { psc = app_show_single_vcp_value_by_feature_id( dh, fsref->specific_feature, true); } else if (fsref->subset == VCP_SUBSET_MULTI_FEATURES) { #endif if (fsref->subset == VCP_SUBSET_SINGLE_FEATURE || fsref->subset == VCP_SUBSET_MULTI_FEATURES) { int feature_ct = bs256_count(fsref->features); DBGMSF(debug, "VCP_SUBSET_MULTI_FEATURES, feature_ct=%d", feature_ct); psc = 0; Bit_Set_256_Iterator iter = bs256_iter_new(fsref->features); int bitno = bs256_iter_next(iter); while (bitno >= 0) { DBGMSF(debug, "bitno=0x%02x", bitno); int rc = app_show_single_vcp_value_by_feature_id( dh, bitno, true); if (rc < 0) psc = rc; bitno = bs256_iter_next(iter); } bs256_iter_free(iter); } else { psc = app_show_vcp_subset_values_by_dh( dh, fsref->subset, flags, NULL); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, ""); return psc; } void init_app_getvcp() { RTTI_ADD_FUNC(app_show_feature_set_values_by_dh); RTTI_ADD_FUNC(app_show_vcp_subset_values_by_dh); RTTI_ADD_FUNC(app_show_single_vcp_value_by_feature_id); RTTI_ADD_FUNC(app_show_single_vcp_value_by_dfm); } ddcutil-2.2.0/src/app_ddcutil/app_probe.c0000644000175000001440000002410414754153540014023 /** @file app_probe.c * Implement PROBE command */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "public/ddcutil_types.h" #include "util/error_info.h" #include "util/report_util.h" #include "base/core.h" #include "base/displays.h" #include "base/rtti.h" #include "vcp/parse_capabilities.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_output.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_read_capabilities.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" #include "dynvcp/dyn_feature_codes.h" #include "app_ddcutil/app_getvcp.h" #include "app_ddcutil/app_capabilities.h" #include "app_ddcutil/app_probe.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_TOP; /** Probe a display specified by its #Display_Handle. * Output is written to stdout. * * @param dh display handle */ void app_probe_display_by_dh(Display_Handle * dh) { FILE * fout = stdout; bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); Error_Info * ddc_excp = NULL; Parsed_Edid * pedid = dh->dref->pedid; f0printf(fout, "\nEDID version: %d.%d", pedid->edid_version_major, pedid->edid_version_minor); f0printf(fout, "\nMfg id: %s, model: %s, sn: %s\n", pedid->mfg_id, pedid->model_name, pedid->serial_ascii); f0printf(fout, "Product code: %u, binary serial number %"PRIu32" (0x%08x)\n", pedid->product_code, pedid->serial_binary, pedid->serial_binary); Dref_Flags flags = dh->dref->flags; char interpreted[200]; #define FLAG_NAME(_flag) (flags & _flag) ? #_flag : "" g_snprintf(interpreted, 200, "%s%s%s%s", FLAG_NAME(DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED), FLAG_NAME(DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED), FLAG_NAME(DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED), FLAG_NAME(DREF_DDC_DOES_NOT_INDICATE_UNSUPPORTED) ); f0printf(fout, "\nHow display reports unsupported feature: %s\n", interpreted); #undef FLAG_NAME f0printf(fout, "\nCapabilities for display on %s\n", dref_short_name_t(dh->dref)); DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); // not needed, message causes confusing messages if get_vcp_version fails but get_capabilities succeeds // if (vspec.major < 2) { // printf("VCP (aka MCCS) version for display is less than 2.0. Output may not be accurate.\n"); // } DDCA_Output_Level saved_ol = set_output_level(DDCA_OL_VERBOSE); // affects this thread only char * capabilities_string = NULL; Parsed_Capabilities * pcaps = NULL; DDCA_Status ddcrc = app_get_capabilities_string(dh, &capabilities_string); if (ddcrc == 0) { // pcaps is always set, but may be damaged if there was a parsing error pcaps = parse_capabilities_string(capabilities_string); app_show_parsed_capabilities(dh, pcaps); // how to pass this information down into app_show_vcp_subset_values_by_dh()? bool table_reads_possible = parsed_capabilities_supports_table_commands(pcaps); f0printf(fout, "\nMay support table reads: %s\n", sbool(table_reads_possible)); } set_output_level(saved_ol); // *** VCP Feature Scan *** // printf("\n\nScanning all VCP feature codes for display %d\n", dispno); f0printf(fout, "\nScanning all VCP feature codes for display %s\n", dh_repr(dh) ); Bit_Set_256 features_seen = EMPTY_BIT_SET_256; app_show_vcp_subset_values_by_dh( dh, VCP_SUBSET_SCAN, FSF_SHOW_UNSUPPORTED, &features_seen); if (pcaps) { f0printf(fout, "\n\nComparing declared capabilities to observed features...\n"); Bit_Set_256 features_declared = get_parsed_capabilities_feature_ids(pcaps, /*readable_only=*/true); #ifdef OLD char * s0 = bbf_to_string(features_declared); f0printf(fout, "\nReadable features declared in capabilities string: %s\n", s0); free(s0); #endif f0printf(fout, "\nReadable features declared in capabilities string: %s\n", bs256_to_string_t(features_declared, "x", ", ")); Bit_Set_256 caps_not_seen = bs256_and_not(features_declared, features_seen); Bit_Set_256 seen_not_caps = bs256_and_not(features_seen, features_declared); f0printf(fout, "\nMCCS (VCP) version reported by capabilities: %s\n", format_vspec(pcaps->parsed_mccs_version)); f0printf(fout, "MCCS (VCP) version reported by feature 0xDf: %s\n", format_vspec(vspec)); if (!vcp_version_eq(pcaps->parsed_mccs_version, vspec)) f0printf(fout, "Versions do not match!!!\n"); if (bs256_count(caps_not_seen) > 0) { f0printf(fout, "\nFeatures declared as readable capabilities but not found by scanning:\n"); for (int code = 0; code < 256; code++) { if (bs256_contains(caps_not_seen, code)) { VCP_Feature_Table_Entry * vfte = vcp_find_feature_by_hexid_w_default(code); Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dh(code, dh, /*check_udf=*/true, /*with_default=*/true); char * feature_name = get_version_sensitive_feature_name(vfte, pcaps->parsed_mccs_version); if (!streq(feature_name, dfm->feature_name)) { rpt_vstring(1, "VCP_Feature_Table_Entry feature name: %s", feature_name); rpt_vstring(1, "Display_Feature_Metadata feature name: %s", dfm->feature_name); f0printf(fout, " Feature x%02x - %s, (alt.) %s\n", code, feature_name, dfm->feature_name); } else { // assert( streq(feature_name, dfm->external_metadata->feature_name)); f0printf(fout, " Feature x%02x - %s\n", code, feature_name); } if (vfte->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { free_synthetic_vcp_entry(vfte); } dfm_free(dfm); } } } else f0printf(fout, "\nAll readable features declared in capabilities were found by scanning.\n"); if (bs256_count(seen_not_caps) > 0) { f0printf(fout, "\nFeatures found by scanning but not declared as capabilities:\n"); for (int code = 0; code < 256; code++) { if (bs256_contains(seen_not_caps, code)) { VCP_Feature_Table_Entry * vfte = vcp_find_feature_by_hexid_w_default(code); Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dh(code, dh, /*check_udf=*/ true, /*with_default=*/ true); char * feature_name = get_version_sensitive_feature_name(vfte, vspec); f0printf(fout, " Feature x%02x - %s\n", code, feature_name); if (!streq(feature_name, dfm->feature_name)) { rpt_vstring(1, "VCP_Feature_Table_Entry feature name: %s", feature_name); rpt_vstring(1, "Internal_Feature_Metadata feature name: %s", dfm->feature_name); } // assert( streq(feature_name, ifm->external_metadata->feature_name)); if (vfte->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { free_synthetic_vcp_entry(vfte); } dfm_free(dfm); } } } else f0printf(fout, "\nAll features found by scanning were declared in capabilities.\n"); free_parsed_capabilities(pcaps); } else { f0printf(fout, "\n\nUnable to read or parse capabilities.\n"); f0printf(fout, "Skipping comparison of declared capabilities to observed features\n"); } puts(""); DDCA_Any_Vcp_Value * valrec; int color_temp_increment = 0; int color_temp_units = 0; // get VCP 0B - color temperature increment ddc_excp = ddc_get_vcp_value(dh,0x0b, DDCA_NON_TABLE_VCP_VALUE, &valrec); if (!ddc_excp) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Value returned for feature x0b: %s", summarize_single_vcp_value(valrec) ); color_temp_increment = valrec->val.c_nc.sl; free_single_vcp_value(valrec); // get x0c - color temperature request ddc_excp = ddc_get_vcp_value(dh, 0x0c, DDCA_NON_TABLE_VCP_VALUE, &valrec); if (!ddc_excp) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Value returned for feature x0c: %s", summarize_single_vcp_value(valrec) ); color_temp_units = valrec->val.c_nc.sl; int color_temp = 3000 + color_temp_units * color_temp_increment; f0printf(fout, "Color temperature increment (x0b) = %d degrees Kelvin\n", color_temp_increment); f0printf(fout, "Color temperature request (x0c) = %d\n", color_temp_units); f0printf(fout, "Requested color temperature = (3000 deg Kelvin) + %d * (%d degrees Kelvin)" " = %d degrees Kelvin\n", color_temp_units, color_temp_increment, color_temp); free_single_vcp_value(valrec); } } if (ddc_excp) { f0printf(fout, "Unable to calculate color temperature from VCP features x0B and x0C\n"); ERRINFO_FREE_WITH_REPORT(ddc_excp, debug || report_freed_exceptions); } app_show_single_vcp_value_by_feature_id(dh, 0x14, true); rpt_set_ornamentation_enabled(saved_prefix_report_output); DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Probe a display specified by a #Display_Ref. * Output is written to stdout. * * @param dref display reference */ void app_probe_display_by_dref(Display_Ref * dref) { FILE * fout = stdout; Display_Handle * dh = NULL; Error_Info * err = ddc_open_display(dref, CALLOPT_NONE, &dh); if (err) { f0printf(fout, "Error opening display %s: %s", dref_short_name_t(dref), psc_desc(err->status_code) ); errinfo_free(err); err = NULL; } else { app_probe_display_by_dh(dh); ddc_close_display_wo_return(dh); } } void init_app_probe() { RTTI_ADD_FUNC(app_probe_display_by_dh); } ddcutil-2.2.0/src/app_ddcutil/app_ddcutil_services.c0000644000175000001440000000150414572333721016245 /** @file app_ddcutil_services.c * Initialize files in directory app_ddcutil */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include "app_capabilities.h" #include "app_dumpload.h" #include "app_dynamic_features.h" #include "app_getvcp.h" #ifdef ENABLE_ENVCMDS #include "app_interrogate.h" #endif #include "app_probe.h" #include "app_setvcp.h" #include "app_vcpinfo.h" #include "app_watch.h" #include "app_vcpinfo.h" void init_app_ddcutil_services() { init_app_capabilities(); init_app_dumpload(); init_app_dynamic_features(); init_app_getvcp(); #ifdef ENABLE_ENVCMDS init_app_interrogate(); #endif init_app_probe(); init_app_setvcp(); init_app_vcpinfo(); init_app_watch(); // main initialized by local init call } ddcutil-2.2.0/src/app_ddcutil/app_setvcp.c0000644000175000001440000001747514754153540014235 /** @file app_setvcp.c * * Implement the SETVCP command */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include /** \endcond */ #include "public/ddcutil_types.h" #include "util/error_info.h" #include "util/string_util.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/ddc_packets.h" #include "base/feature_metadata.h" #include "base/rtti.h" #include "cmdline/parsed_cmd.h" #include "ddc/ddc_vcp.h" #include "ddc/ddc_packet_io.h" // for alt_source_addr #include "dynvcp/dyn_feature_codes.h" #include "app_setvcp.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_TOP; /** Converts a VCP feature value from string form to internal form. * Error messages are written to stderr. * * @param string_value * @param parsed_value location where to return result * * @return true if conversion successful, false if not */ bool parse_vcp_value( char * string_value, int * parsed_value_loc) { assert(string_value); bool debug = false; DBGMSF(debug, "Starting. string_value = |%s|", string_value); FILE * errf = ferr(); // at app level will always be stderr char * canonical = canonicalize_possible_hex_value(string_value); bool ok = str_to_int(canonical, parsed_value_loc, 0); free(canonical); if (!ok) { f0printf(errf, "Not a number: \"%s\"\n", string_value); ok = false; } else if (*parsed_value_loc < 0 || *parsed_value_loc > 65535) { f0printf(errf, "Number must be in range 0..65535: %d\n", *parsed_value_loc); ok = false; } DBGMSF(debug, "Done. *parsed_value_loc=%d, returning: %s", *parsed_value_loc, SBOOL(ok)); return ok; } /** Parses the arguments passed for a single feature and sets the new value. * * @param dh display handle * @param feature feature code * @param value_type indicates if a relative value * @param new_value new feature value (as string) * @param force attempt to set feature even if feature code unrecognized * @return #Error_Info if error */ Error_Info * app_set_vcp_value( Display_Handle * dh, Byte feature_code, Setvcp_Value_Type value_type, char * new_value, bool force) { assert(new_value && strlen(new_value) > 0); bool debug = false; DBGTRC_STARTING(debug,TRACE_GROUP, "feature=0x%02x, new_value=%s, value_type=%s, force=%s", feature_code, new_value, setvcp_value_type_name(value_type), sbool(force)); DDCA_Status ddcrc = 0; Error_Info * ddc_excp = NULL; int itemp; Display_Feature_Metadata * dfm = NULL; bool good_value = false; DDCA_Any_Vcp_Value vrec; dfm = dyn_get_feature_metadata_by_dh(feature_code,dh, /*check_udf=*/ true, (force || feature_code >= 0xe0) ); if (!dfm) { ddc_excp = ERRINFO_NEW(DDCRC_UNKNOWN_FEATURE, "Unrecognized VCP feature code: 0x%02x", feature_code); goto bye; } if (!(dfm->version_feature_flags & DDCA_WRITABLE)) { ddc_excp = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "Feature 0x%02x (%s) is not writable", feature_code, dfm->feature_name); goto bye; } if (dfm->version_feature_flags & DDCA_TABLE) { if (value_type != VALUE_TYPE_ABSOLUTE) { ddc_excp = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "Relative VCP values valid only for Continuous VCP features"); goto bye; } Byte * value_bytes; int bytect = hhs_to_byte_array(new_value, &value_bytes); if (bytect < 0) { // bad hex string ddc_excp = ERRINFO_NEW(DDCRC_ARG, "Invalid hex value"); goto bye; } vrec.opcode = feature_code; vrec.value_type = DDCA_TABLE_VCP_VALUE; vrec.val.t.bytect = bytect; vrec.val.t.bytes = value_bytes; } else { // the usual non-table case good_value = parse_vcp_value(new_value, &itemp); if (!good_value) { // what is better status code? ddc_excp = ERRINFO_NEW(DDCRC_ARG, "Invalid VCP value: %s", new_value); goto bye; } if (value_type != VALUE_TYPE_ABSOLUTE) { if ( !(dfm->version_feature_flags & DDCA_CONT) ) { ddc_excp = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "Relative VCP values valid only for Continuous VCP features"); goto bye; } // Handle relative values Parsed_Nontable_Vcp_Response * parsed_response; ddc_excp = ddc_get_nontable_vcp_value( dh, feature_code, &parsed_response); if (ddc_excp) { ddcrc = ERRINFO_STATUS(ddc_excp); ddc_excp = errinfo_new_with_cause(ddcrc, ddc_excp, __func__, "Getting value failed for feature %02x, rc=%s", feature_code, psc_desc(ddcrc)); goto bye; } if ( value_type == VALUE_TYPE_RELATIVE_PLUS) { itemp = RESPONSE_CUR_VALUE(parsed_response) + itemp; if (itemp > RESPONSE_MAX_VALUE(parsed_response)) itemp = RESPONSE_MAX_VALUE(parsed_response); } else { assert( value_type == VALUE_TYPE_RELATIVE_MINUS); itemp = RESPONSE_CUR_VALUE(parsed_response) - itemp; if (itemp < 0) itemp = 0; } free(parsed_response); } vrec.opcode = feature_code; vrec.value_type = DDCA_NON_TABLE_VCP_VALUE; vrec.val.c_nc.sh = (itemp >> 8) & 0xff; vrec.val.c_nc.sl = itemp & 0xff; } ddc_excp = ddc_set_verified_vcp_value_with_retry(dh, &vrec, NULL); if (ddc_excp) { ddcrc = ERRINFO_STATUS(ddc_excp); if (ddcrc == DDCRC_VERIFY) ddc_excp = errinfo_new_with_cause(ddcrc, ddc_excp, __func__, "Verification failed for feature %02x", feature_code); else ddc_excp = errinfo_new_with_cause(ddcrc, ddc_excp, __func__, "Setting value failed for feature x%02X, rc=%s", feature_code, psc_desc(ddcrc)); } bye: dfm_free(dfm); // handles dfm == NULL DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } /** Execute command SETVCP * * @param parsed_cmd parsed command * @param dh display handle * @return status code */ Status_Errno_DDC app_setvcp(Parsed_Cmd * parsed_cmd, Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); Error_Info * ddc_excp = NULL; Status_Errno_DDC ddcrc = 0; for (int ndx = 0; ndx < parsed_cmd->setvcp_values->len; ndx++) { Parsed_Setvcp_Args * cur = &g_array_index(parsed_cmd->setvcp_values, Parsed_Setvcp_Args, ndx); if (parsed_cmd->flags & CMD_FLAG_EXPLICIT_I2C_SOURCE_ADDR) alt_source_addr = parsed_cmd->explicit_i2c_source_addr; ddc_excp = app_set_vcp_value( dh, cur->feature_code, cur->feature_value_type, cur->feature_value, parsed_cmd->flags & CMD_FLAG_FORCE_UNRECOGNIZED_VCP_CODE); if (ddc_excp) { f0printf(ferr(), "%s\n", ddc_excp->detail); if (ddc_excp->status_code == DDCRC_RETRIES) f0printf(ferr(), " Try errors: %s\n", errinfo_causes_string(ddc_excp)); ddcrc = ERRINFO_STATUS(ddc_excp); BASE_ERRINFO_FREE_WITH_REPORT(ddc_excp, IS_DBGTRC(debug,TRACE_GROUP)); break; } } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc,""); return ddcrc; } void init_app_setvcp() { RTTI_ADD_FUNC(app_setvcp); RTTI_ADD_FUNC(app_set_vcp_value); } ddcutil-2.2.0/src/app_ddcutil/app_vcpinfo.c0000644000175000001440000003227114754153540014364 /** @file app_vcpinfo.c * * Implement VCPINFO and (deprecated) LISTVCP commands */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include #include "public/ddcutil_types.h" #include "util/report_util.h" #include "base/core.h" #include "base/rtti.h" #include "base/vcp_version.h" #include "dynvcp/dyn_feature_set.h" #include "dynvcp/vcp_feature_set.h" #include "vcp/vcp_feature_codes.h" #include "app_vcpinfo.h" /** Creates humanly readable interpretation of VCP feature flags. * The result is returned in a buffer supplied by the caller. * * @param flags version specific feature flags * @param buf pointer to buffer * @param buflen buffer size * @return buf */ static char * vcp_interpret_version_feature_flags( DDCA_Version_Feature_Flags flags, char* buf, int buflen) { // DBGMSG("flags: 0x%04x", flags); char * rwmsg = ""; if (flags & DDCA_RO) rwmsg = "ReadOnly "; else if (flags & DDCA_WO) rwmsg = "WriteOnly"; else if (flags & DDCA_RW) rwmsg = "ReadWrite"; char * typemsg = NULL; // NEED TO ALSO HANDLE TABLE TYPE if (flags & DDCA_CONT) typemsg = "Continuous"; else if (flags & DDCA_NC) typemsg = "Non-continuous"; else if (flags & DDCA_NORMAL_TABLE) typemsg = "Table"; // else if (flags & VCP_TYPE_V2NC_V3T) // typemsg = "V2:NC, V3:Table"; else if (flags & DDCA_DEPRECATED) typemsg = "Deprecated"; else typemsg = "Type not set"; // TODO: determine if varying interpretation by analyzing entry // need function has_version_specific_features(entry) char * vermsg = ""; // if (flags & VCP_FUNC_VER) // if (has_version_specific_features(entry)) // vermsg = " (Version specific interpretation)"; snprintf(buf, buflen, "%s %s%s", rwmsg, typemsg, vermsg); return buf; } /** Mainline for deprecated command LISTVCP * * @param fh where to write output */ void app_listvcp(FILE * fh) { fprintf(fh, "Recognized VCP feature codes:\n"); char buf[200]; char buf2[234]; // TODO make listvcp respect display to get version? int ct = vcp_get_feature_code_count(); for (int ndx = 0; ndx < ct ; ndx++) { VCP_Feature_Table_Entry * entry = vcp_get_feature_table_entry(ndx); // DBGMSG("code=0x%02x, flags: 0x%04x", entry.code, entry.flags); DDCA_MCCS_Version_Spec vspec = get_highest_non_deprecated_version(entry); DDCA_Version_Feature_Flags vflags = get_version_specific_feature_flags(entry, vspec); vcp_interpret_version_feature_flags(vflags, buf, sizeof(buf)); char * vermsg = ""; if (has_version_specific_features(entry)) vermsg = " (Version specific interpretation)"; snprintf(buf2, sizeof(buf2), "%s%s", buf, vermsg); fprintf(fh, " %02x - %-40s %s\n", entry->code, get_non_version_specific_feature_name(entry), // vcp_interpret_feature_flags(entry.flags, buf, 200) // *** TODO: HOW TO HANDLE THIS w/o version? buf2 ); } } /** Returns a byte of flags indicating those MCCS versions for which the * specified VCP feature is defined. * * @param pentry pointer to VCP_Feature_Table_Entry for VCP feature * @return byte of flags * * @remark * Move back to vcp_feature_codes.c? */ static Byte valid_versions( VCP_Feature_Table_Entry * pentry) { Byte result = 0x00; if (pentry->v20_flags) result |= MCCS_SPEC_V20; if (pentry->v21_flags) { if ( !(pentry->v21_flags & DDCA_DEPRECATED) ) result |= MCCS_SPEC_V21; } else { if (result & MCCS_SPEC_V20) result |= MCCS_SPEC_V21; } if (pentry->v30_flags) { if ( !(pentry->v30_flags & DDCA_DEPRECATED) ) result |= MCCS_SPEC_V30; } else { if (result & MCCS_SPEC_V21) result |= MCCS_SPEC_V30; } if (pentry->v22_flags) { if ( !(pentry->v22_flags & DDCA_DEPRECATED) ) result |= MCCS_SPEC_V22; } else { if (result & MCCS_SPEC_V21) result |= MCCS_SPEC_V22; } return result; } /** Given a byte of flags indicating MCCS versions, return a string containing a * comma delimited list of MCCS version names. * * @param valid_version_flags * @param version_name_buf buffer in which to return string * @param bufsz buffer size * @return version_name_buf * * Note: MCCS 1.0 is not reported */ static char * valid_version_names_r( Byte valid_version_flags, char * version_name_buf, int bufsz) { assert(bufsz >= (4*5)); // max 4 version names, 5 chars/name *version_name_buf = '\0'; if (valid_version_flags & MCCS_SPEC_V20) strcpy(version_name_buf, "2.0"); if (valid_version_flags & MCCS_SPEC_V21) { if (strlen(version_name_buf) > 0) strcat(version_name_buf, ", "); strcat(version_name_buf, "2.1"); } if (valid_version_flags & MCCS_SPEC_V30) { if (strlen(version_name_buf) > 0) strcat(version_name_buf, ", "); strcat(version_name_buf, "3.0"); } if (valid_version_flags & MCCS_SPEC_V22) { if (strlen(version_name_buf) > 0) strcat(version_name_buf, ", "); strcat(version_name_buf, "2.2"); } return version_name_buf; } static void report_sl_values( DDCA_Feature_Value_Entry * sl_values, int depth) { while (sl_values->value_name != NULL) { rpt_vstring(depth, "0x%02x: %s", sl_values->value_code, sl_values->value_name); sl_values++; } } static char * interpret_ddca_version_feature_flags_readwrite( DDCA_Version_Feature_Flags feature_flags) { char * result = NULL; if (feature_flags & DDCA_RW) result = "Read Write"; else if (feature_flags & DDCA_RO) result = "Read Only"; else if (feature_flags & DDCA_WO) result = "Write Only"; else { PROGRAM_LOGIC_ERROR("No read/write bits set"); result = "PROGRAM LOGIC ERROR: No read/write bits set"; } return result; } static char * interpret_ddca_version_feature_flags_type( DDCA_Version_Feature_Flags feature_flags) { char * result = NULL; if (feature_flags & DDCA_STD_CONT) result = "Continuous (normal)"; else if (feature_flags & DDCA_COMPLEX_CONT) result = "Continuous (complex)"; else if (feature_flags & DDCA_SIMPLE_NC) result = "Non-Continuous (simple)"; else if (feature_flags & DDCA_EXTENDED_NC) result = "Non-Continuous (extended)"; else if (feature_flags & DDCA_COMPLEX_NC) result = "Non-Continuous (complex)"; else if (feature_flags & DDCA_NC_CONT) result = "Non-Continuous with continuous subrange"; else if (feature_flags & DDCA_WO_NC) result = "Non-Continuous (write-only)"; else if (feature_flags & DDCA_NORMAL_TABLE) result = "Table (normal)"; else if (feature_flags & DDCA_WO_TABLE) result = "Table (write-only)"; else { result = "PROGRAM LOGIC ERROR: No C/NC/T subtype bit set"; PROGRAM_LOGIC_ERROR("No C/NC/T subtype bit set"); } return result; } static char * interpret_feature_flags_r( DDCA_Version_Feature_Flags vflags, char * workbuf, int bufsz) { bool debug = false; DBGMSF(debug, "vflags=0x%04x", vflags); assert(bufsz >= 100); // bigger than we'll need *workbuf = '\0'; if (vflags & DDCA_DEPRECATED) { strcpy(workbuf, "Deprecated, "); } else { strcpy(workbuf, interpret_ddca_version_feature_flags_readwrite(vflags)); strcat(workbuf, ", "); strcat(workbuf, interpret_ddca_version_feature_flags_type(vflags)); char buf[80]; char * s = vcp_interpret_global_feature_flags(vflags, buf, 80); if (s && strlen(s) > 0) { strcat(workbuf, ", "); strcat(workbuf, s); } } return workbuf; } // report function specifically for use by report_vcp_feature_table_entry() static void report_feature_table_entry_flags( VCP_Feature_Table_Entry * pentry, DDCA_MCCS_Version_Spec vcp_version, int depth) { char workbuf[200]; DDCA_Version_Feature_Flags vflags = get_version_specific_feature_flags(pentry, vcp_version); if (vflags) { interpret_feature_flags_r(vflags, workbuf, sizeof(workbuf)); rpt_vstring(depth, "Attributes (v%d.%d): %s", vcp_version.major, vcp_version.minor, workbuf); } } /** Emits a report on a VCP_Feature_Table_Entry. This function is used by the * VCPINFO command. The report is written to the current report destination. * * @param pentry pointer to feature table entry * @param depth logical indentation depth * * @remark * More properly in vcp_feature_codes.c? */ void report_vcp_feature_table_entry( VCP_Feature_Table_Entry * pentry, int depth) { char workbuf[200]; int d1 = depth+1; DDCA_Output_Level output_level = get_output_level(); DDCA_MCCS_Version_Spec vspec = get_highest_non_deprecated_version(pentry); DDCA_Version_Feature_Flags vflags = get_version_specific_feature_flags(pentry, vspec); char * feature_name = get_non_version_specific_feature_name(pentry); rpt_vstring(depth, "VCP code %02X: %s", pentry->code, feature_name); if (!(pentry->vcp_global_flags & DDCA_SYNTHETIC)) { rpt_vstring(d1, "%s", pentry->desc); valid_version_names_r(valid_versions(pentry), workbuf, sizeof(workbuf)); rpt_vstring(d1, "MCCS versions: %s", workbuf); if (output_level >= DDCA_OL_VERBOSE) rpt_vstring(d1, "MCCS specification groups: %s", spec_group_names_r(pentry, workbuf, sizeof(workbuf))); char * subset_names = feature_subset_names(pentry->vcp_subsets); rpt_vstring(d1, "ddcutil feature subsets: %s", subset_names); free(subset_names); if (has_version_specific_features(pentry)) { // rpt_vstring(d1, "VERSION SPECIFIC FLAGS"); report_feature_table_entry_flags(pentry, DDCA_VSPEC_V20, d1); report_feature_table_entry_flags(pentry, DDCA_VSPEC_V21, d1); report_feature_table_entry_flags(pentry, DDCA_VSPEC_V30, d1); report_feature_table_entry_flags(pentry, DDCA_VSPEC_V22, d1); } else { interpret_feature_flags_r(vflags, workbuf, sizeof(workbuf)); rpt_vstring(d1, "Attributes: %s", workbuf); } if (pentry->default_sl_values && output_level >= DDCA_OL_VERBOSE) { rpt_vstring(d1, "Simple NC values:"); report_sl_values(pentry->default_sl_values, d1+1); } } } /** Mainline for VCPINFO command * * @param parsed_cmd parsed command line * @return false if no features shown, true otherwise */ bool app_vcpinfo(Parsed_Cmd * parsed_cmd) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_VCP | DDCA_TRC_TOP, "feature set: %s", fsref_repr_t(parsed_cmd->fref)); bool vcpinfo_ok = true; Feature_Set_Flags fsflags = 0; if (parsed_cmd->flags & CMD_FLAG_RW_ONLY) fsflags |= FSF_RW_ONLY; if (parsed_cmd->flags & CMD_FLAG_RO_ONLY) fsflags |= FSF_RO_ONLY; if (parsed_cmd->flags & CMD_FLAG_WO_ONLY) fsflags |= FSF_WO_ONLY; // if (parsed_cmd->flags & CMD_FLAG_ENABLE_UDF) // Do I want // fsflags |= FSF_CHECK_UDF; Dyn_Feature_Set * fset = create_dyn_feature_set_from_feature_set_ref( parsed_cmd->fref, parsed_cmd->mccs_vspec, fsflags); #ifdef OLD VCP_Feature_Set * fset = create_vcp_feature_set_from_feature_set_ref( parsed_cmd->fref, parsed_cmd->mccs_vspec, fsflags); #endif if (IS_DBGTRC(debug, (DDCA_TRC_TOP | DDCA_TRC_VCP)) ) dbgrpt_dyn_feature_set(fset, /*verbose=*/false, 2); if (!fset) { vcpinfo_ok = false; } else { bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); if ( get_output_level() <= DDCA_OL_TERSE) report_dyn_feature_set(fset, 0); else { #ifdef OLD int ct = get_vcp_feature_set_size(fset); for (int ndx = 0; ndx < ct; ndx++) { VCP_Feature_Table_Entry * pentry = get_vcp_feature_set_entry(fset, ndx); report_vcp_feature_table_entry(pentry, 0); } #endif int ct = dyn_get_feature_set_size(fset); int ndx = 0; for (;ndx < ct; ndx++) { Display_Feature_Metadata * dfm = g_ptr_array_index(fset->members_dfm, ndx); // VCP_Feature_Table_Entry * pentry = get_vcp_feature_set_entry(fset, ndx); VCP_Feature_Table_Entry * pentry = vcp_find_feature_by_hexid(dfm->feature_code); assert(pentry); // every possible feature code has a feature table entry report_vcp_feature_table_entry(pentry, 0); } } rpt_set_ornamentation_enabled(saved_prefix_report_output); // free_vcp_feature_set(fset); free_dyn_feature_set(fset); } DBGTRC_RET_BOOL(debug, DDCA_TRC_VCP|DDCA_TRC_TOP, vcpinfo_ok, ""); return vcpinfo_ok; } void init_app_vcpinfo() { RTTI_ADD_FUNC(app_vcpinfo); } ddcutil-2.2.0/src/app_ddcutil/app_watch.c0000644000175000001440000002520314754576332014033 /** @file app_watch.c * Implement the WATCH command */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include "util/error_info.h" #include "util/string_util.h" #include "util/report_util.h" /** \endcond */ #ifdef ENABLE_USB #include "usb_util/hiddev_reports.h" #include "usb_util/hiddev_util.h" #endif #include "base/core.h" #include "base/ddc_errno.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/vcp_version.h" #include "cmdline/parsed_cmd.h" #include "vcp/vcp_feature_codes.h" #include "dynvcp/dyn_feature_codes.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_output.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" #include "app_ddcutil/app_getvcp.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_TOP; // // Watch for changed VCP values // // Depending on monitor, writing 1 to feature x02 may throw the user // out of the on-stream display. Use carefully. static void reset_vcp_x02(Display_Handle * dh) { bool debug = false; Error_Info * ddc_excp = ddc_set_nontable_vcp_value(dh, 0x02, 0x01); if (ddc_excp) { DBGMSG("set_nontable_vcp_value_by_dh() returned %s", errinfo_summary(ddc_excp) ); errinfo_free(ddc_excp); } else DBGMSF(debug, "reset feature x02 (new control value) successful"); } /** Gets the ID of the next changed feature from VCP feature x52. If the feature * code is other than x00, reads and displays the value of that feature. * * \param dh #Display_Handle * \param p_changed_feature return feature id read from feature x52 * \return error reading feature x52 * * \remark * The return value reflects only x52 errors, not any errors reading * the feature id that is displayed */ static Error_Info * show_changed_feature(Display_Handle * dh, Byte * p_changed_feature) { bool debug = false; Parsed_Nontable_Vcp_Response * nontable_response_loc = NULL; Error_Info * result = NULL; Error_Info * x52_error = ddc_get_nontable_vcp_value(dh, 0x52, &nontable_response_loc); DBGMSF(debug, "ddc_get_nontable_vcp_value( x52 ) returned %s", errinfo_summary(x52_error)); if (x52_error) { if (x52_error->status_code == DDCRC_REPORTED_UNSUPPORTED || x52_error->status_code == DDCRC_DETERMINED_UNSUPPORTED) { // printf("Feature x02 (New Control Value) reports new control values exist, but feature x52 (Active Control) unsupported\n"); result = errinfo_new(x52_error->status_code, __func__, "Feature x02 (New Control Value) reports that changed VCP feature values exist, but feature x52 (Active Control) is unsupported"); errinfo_free(x52_error); } else { // DBGMSG("get_nontable_vcp_value() for VCP feature x52 returned %s", errinfo_summary(x52_error) ); result = errinfo_new_with_cause( x52_error->status_code, x52_error, __func__, "Error reading feature x02"); } } else { // getvcp x52 succeeded *p_changed_feature = nontable_response_loc->sl; free(nontable_response_loc); DBGMSF(debug, "getvcp(x52) returned value 0x%02x", *p_changed_feature); if (*p_changed_feature) app_show_single_vcp_value_by_feature_id(dh, *p_changed_feature, false); } return result; } /* Checks for VCP feature changes by: * - reading feature x02 to check if changes exist, * - querying feature x52 for the id of a changed feature * - reading and showing the value of the changed feature. * * If the VCP version is 2.1 or less a single feature is * read from x52. For VCP version 3.0 and 2.2, x52 is a * FIFO queue of changed features. * * Finally, 1 is written to feature x02 as a reset. * * \param dh #Display_Handle * \param force_no_fifo never treat feature x52 as a FIFO * \param changes_reported set true if any changes were detected * \return error report, NULL if none */ static Error_Info * app_read_changes(Display_Handle * dh, bool force_no_fifo, bool* changes_reported) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, force_no_fifo = %s", dh_repr(dh), SBOOL(force_no_fifo)); int MAX_CHANGES = 20; *changes_reported = false; /* Per the 3.0 and 2.2 specs, feature x52 is a FIFO to be read until value x00 indicates empty * What apparently happens on 2.1 (U3011) is that each time feature x02 is reset with value x01 * the subsequent read of feature x02 returns x02 (new control values exists) until the queue * of changes is flushed */ DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); // DBGMSF(debug, "VCP version: %d.%d", vspec.major, vspec.minor); // Read feature x02 to determine if any features have changed // xff: no user controls // x01: no new control values // x02: new control values exist Parsed_Nontable_Vcp_Response * p_nontable_response = NULL; Error_Info * result = NULL; Error_Info * x02_error = ddc_get_nontable_vcp_value(dh,0x02,&p_nontable_response); if (x02_error) { DBGMSG("get_nontable_vcp_value() for feature 0x02 returned error %s", errinfo_summary(x02_error) ); // errinfo_free(ddc_excp); result = errinfo_new_with_cause(x02_error->status_code, x02_error, __func__, "Error reading feature x02"); } else { Byte x02_value = p_nontable_response->sl; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "get_nontable_vcp_value() for feature 0x02 returned value 0x%02x", x02_value ); free(p_nontable_response); if (x02_value == 0xff) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "No user controls exist"); result = errinfo_new(DDCRC_DETERMINED_UNSUPPORTED, __func__, "Feature x02 (New Control Value) reports No User Controls"); } else if (x02_value == 0x01) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "No new control values found"); result = NULL; } else if (x02_value != 0x02){ DBGMSF(debug, "x02 value = 0x%02x", x02_value); result = errinfo_new(DDCRC_DETERMINED_UNSUPPORTED, __func__, "Feature x02 (New Control Value) reports unexpected value 0x%02", x02_value); } else { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "New control values exist. x02 value: 0x%02x", x02_value); Byte changed_feature_id; if ( vcp_version_le(vspec, DDCA_VSPEC_V21) || force_no_fifo) { Error_Info * x52_error = show_changed_feature(dh, &changed_feature_id); // MCCS spec requires that feature x02 be reset, otherwise it remains at x02 // and the same value is read again // But on some displays it also turns off the OSD: HPZ22i // For other displays it does not turn off the OSD, so the user can make // additional changes: Dell U3011 reset_vcp_x02(dh); result = x52_error; if (!x52_error) *changes_reported = true; } else { // x52 is a FIFO int ctr = 0; for (;ctr < MAX_CHANGES; ctr++) { Byte changed_feature_id = 0x00; Error_Info * x52_error = show_changed_feature(dh, &changed_feature_id); if (x52_error) { result = x52_error; goto bye; } *changes_reported = true; if (changed_feature_id == 0x00) { DBGMSG("No more changed features found"); reset_vcp_x02(dh); result = NULL; break; } } if (ctr == MAX_CHANGES) { DBGMSG("Reached loop guard value MAX_CHANGES (%d)", MAX_CHANGES); reset_vcp_x02(dh); result = NULL; } } } } bye: DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, ""); return result; } #ifdef ENABLE_USB static void app_read_changes_usb(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); // bool new_values_found = false; assert(dh->dref->io_path.io_mode == DDCA_IO_USB); int fd = dh->fd; int flaguref = HIDDEV_FLAG_UREF; struct hiddev_usage_ref uref; int rc = ioctl(fd, HIDIOCSFLAG, &flaguref); if (rc < 0) { REPORT_IOCTL_ERROR("HIDIOCSFLAG", errno); return; } ssize_t ct = read(fd, &uref, sizeof(uref)); if (ct < 0) { int errsv = errno; // report the error printf("(%s) read failed, errno=%d\n", __func__, errsv); } else if (ct > 0) { rpt_vstring(1, "Read new value:"); if (ct < sizeof(uref)) { rpt_vstring(1, "Short read"); } else { dbgrpt_hiddev_usage_ref(&uref, 1); rpt_vstring(1, "New value: 0x%04x (%d)", uref.value, uref.value); } } else { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "tick"); } } #endif /* Infinite loop watching for VCP feature changes reported by the display. * * \param dh #Display_Handle * \param force_no_fifo if true, do not regard feature x52 aa a FIFO queue, * even if VCP code is >= 2.2 * * Returns only if an error occurs, otherwise runs forever */ void app_read_changes_forever(Display_Handle * dh, bool force_no_fifo) { bool debug = false; printf("Watching for VCP feature changes on display %s\n", dh_repr(dh)); printf("Type ^C to exit...\n"); // show version here instead of in called function to declutter debug output: DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); DBGMSF(debug, "VCP version: %d.%d", vspec.major, vspec.minor); reset_vcp_x02(dh); while(true) { bool changes_reported = false; #ifdef ENABLE_USB if (dh->dref->io_path.io_mode == DDCA_IO_USB) app_read_changes_usb(dh); else #endif { Error_Info * erec = app_read_changes(dh, force_no_fifo, &changes_reported); if (erec) { if (debug) DBGMSG("Fatal error reading changes: %s", errinfo_summary(erec)); printf("%s\n", erec->detail); DDCA_Status rc = erec->status_code; errinfo_free(erec); if (rc == DDCRC_NULL_RESPONSE) { printf("Continuing WATCH execution\n"); } else { printf("Terminating WATCH\n"); return; } } } if (!changes_reported) sleep_millis( 2500); } } void init_app_watch() { RTTI_ADD_FUNC(app_read_changes); #ifdef USB RTTI_ADD_FUNC(app_read_changes_usb); #endif } ddcutil-2.2.0/src/app_ddcutil/app_testcases.c0000644000175000001440000000303414441414365014707 // app_testcases.c // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include "ddcutil_status_codes.h" #include "util/error_info.h" #include "base/core.h" #include "cmdline/parsed_cmd.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_vcp.h" #include "test/testcases.h" #include "app_ddcutil/app_testcases.h" bool app_testcases(Parsed_Cmd* parsed_cmd) { int testnum; bool ok = true; int ct = sscanf(parsed_cmd->args[0], "%d", &testnum); if (ct != 1) { f0printf(fout(), "Invalid test number: %s\n", parsed_cmd->args[0]); ok = false; } else { ddc_ensure_displays_detected(); ok = true; // Why is ddc_save_current_settings() call here? #ifdef OUT Error_Info * ddc_excp = ddc_save_current_settings(dh); if (ddc_excp) { f0printf(fout(), "Save current settings failed. rc=%s\n", psc_desc(ddc_excp->status_code)); if (ddc_excp->status_code == DDCRC_RETRIES) f0printf(fout(), " Try errors: %s", errinfo_causes_string(ddc_excp) ); errinfo_report(ddc_excp, 0); // ** ALTERNATIVE **/ errinfo_free(ddc_excp); // ERRINFO_FREE_WITH_REPORT(ddc_excp, report_exceptions); ok = false; } if (ok) { #endif if (!parsed_cmd->pdid) parsed_cmd->pdid = create_dispno_display_identifier(1); // default monitor ok = execute_testcase(testnum, parsed_cmd->pdid); #ifdef OUT } #endif } return ok; } ddcutil-2.2.0/src/app_ddcutil/app_interrogate.c0000644000175000001440000000704214754153540015241 /** @file app_interrogate.c * Implement the INTERROGATE command */ // Copyright (C) 2021-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "config.h" #include "public/ddcutil_types.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/parms.h" #include "base/rtti.h" #include "base/per_display_data.h" #include "cmdline/parsed_cmd.h" #include "vcp/persistent_capabilities.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_execute.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_services.h" #include "ddc/ddc_try_data.h" #include "app_sysenv/query_sysenv.h" #include "app_probe.h" #include "app_interrogate.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_TOP; #ifdef ENABLE_ENVCMDS static void reset_stats() { ddc_reset_stats_main(); } /** Execute the INTERROGATE command * * This convenience command executes the ENVIRONMENT, DETECT, and * for each detected display, the PROBE command. * * \param parsed_cmd parsed command line */ void app_interrogate(Parsed_Cmd * parsed_cmd) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); dup2(1,2); // redirect stderr to stdout // set_ferr(fout); // ensure that all messages are collected - made unnecessary by dup2() bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); force_envcmd_settings(parsed_cmd); f0printf(fout(), "This command will take a while to run...\n\n"); ddc_ensure_displays_detected(); // *** ??? DBGTRC_NOPREFIX(debug, TRACE_GROUP, "display detection complete"); // ENVIRONMENT command query_sysenv(parsed_cmd->flags & CMD_FLAG_QUICK); #ifdef ENABLE_USB // 7/2017: disable, USB attached monitors are rare, and this just // clutters the output f0printf(fout(), "\nSkipping USB environment exploration.\n"); f0printf(fout(), "Issue command \"ddcutil usbenvironment --verbose\" if there are any USB attached monitors.\n"); // query_usbenv(); #endif f0printf(fout(), "\nStatistics for environment exploration:\n"); ddc_report_stats_main(DDCA_STATS_ALL, parsed_cmd->flags & CMD_FLAG_VERBOSE_STATS, false, false, 0); reset_stats(); // PROBE command f0printf(fout(), "Setting output level normal. Table features will be skipped...\n"); set_output_level(DDCA_OL_NORMAL); // affects this thread only #ifdef TSD tsd_dsa_enable_globally(parsed_cmd->flags & CMD_FLAG_DSA); // should this apply to INTERROGATE? #endif GPtrArray * all_displays = ddc_get_all_display_refs(); for (int ndx=0; ndx < all_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); assert( memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); if (dref->dispno < 0) { f0printf(fout(), "\nSkipping invalid display on %s\n", dref_short_name_t(dref)); } else { f0printf(fout(), "\nProbing display %d\n", dref->dispno); app_probe_display_by_dref(dref); f0printf(fout(), "\nStatistics for probe of display %d:\n", dref->dispno); ddc_report_stats_main(DDCA_STATS_ALL, parsed_cmd->flags & CMD_FLAG_VERBOSE_STATS, false, false, 0); } reset_stats(); } f0printf(fout(), "\nDisplay scanning complete.\n"); rpt_set_ornamentation_enabled(saved_prefix_report_output); DBGTRC_DONE(debug, TRACE_GROUP, ""); } #endif void init_app_interrogate() { RTTI_ADD_FUNC(app_interrogate); } ddcutil-2.2.0/src/app_ddcutil/app_capabilities.h0000644000175000001440000000132314754576332015360 /** \file app_capabilities.h * * Implement the CAPABILITIES command */ // Copyright (C) 2020-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_CAPABILITIES_H_ #define APP_CAPABILITIES_H_ /** \cond */ #include "base/displays.h" /** \endcond */ #include "vcp/parse_capabilities.h" DDCA_Status app_get_capabilities_string( Display_Handle * dh, char ** capabilities_string_loc); void app_show_parsed_capabilities( Display_Handle * dh, Parsed_Capabilities * pcap); DDCA_Status app_capabilities( // implements the CAPABILITIES command Display_Handle * dh); void init_app_capabilities(); #endif /* APP_CAPABILITIES_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_dumpload.h0000644000175000001440000000102314754576332014531 /** @file app_dumpload.h * * Implement the DUMPVCP and LOADVCP commands */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_DUMPLOAD_H_ #define APP_DUMPLOAD_H_ #include #include Status_Errno_DDC app_loadvcp_by_file(const char * fn, Display_Handle * dh); Status_Errno_DDC app_dumpvcp_as_file(Display_Handle * dh, const char * optional_filename); void init_app_dumpload(); #endif /* APP_DUMPLOAD_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_getvcp.h0000644000175000001440000000172514754576332014225 /** @file app_getvcp.h * Implement the GETVCP command */ //Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_GETVCP_H_ #define APP_GETVCP_H_ #include "public/ddcutil_types.h" /** \cond */ #include /** \endcond */ #include "base/displays.h" #include "base/feature_set_ref.h" #include "base/status_code_mgt.h" #include "cmdline/parsed_cmd.h" Status_Errno_DDC app_show_single_vcp_value_by_feature_id( Display_Handle * dh, DDCA_Vcp_Feature_Code feature_id, bool force); Status_Errno_DDC app_show_vcp_subset_values_by_dh( Display_Handle * dh, VCP_Feature_Subset subset, Feature_Set_Flags flags, Bit_Set_256 * features_seen); Status_Errno_DDC app_show_feature_set_values_by_dh( Display_Handle * dh, Parsed_Cmd * parsed_cmd); void init_app_getvcp(); #endif /* APP_GETVCP_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_interrogate.h0000644000175000001440000000053014754576332015251 /** \file app_interrogate.h */ // Copyright (C) 2021-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_INTERROGATE_H_ #define APP_INTERROGATE_H_ #include "cmdline/parsed_cmd.h" void app_interrogate(Parsed_Cmd * parsed_cmd); void init_app_interrogate(); #endif /* APP_INTERROGATE_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_probe.h0000644000175000001440000000061314754576332014037 /** @file app_probe.h * Implement PROBE command */ // Copyright (C) 2020-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_PROBE_H_ #define APP_PROBE_H_ #include "base/displays.h" void app_probe_display_by_dref(Display_Ref * dref); void app_probe_display_by_dh(Display_Handle * dh); void init_app_probe(); #endif /* APP_PROBE_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_setvcp.h0000644000175000001440000000072114754576332014234 /** @file app_setvcp.h * * Implement the SETVCP command */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_SETVCP_H_ #define APP_SETVCP_H_ #include "cmdline/parsed_cmd.h" #include "base/displays.h" #include "base/status_code_mgt.h" Status_Errno_DDC app_setvcp( Parsed_Cmd * parsed_cmd, Display_Handle * dh); void init_app_setvcp(); #endif /* APP_SETVCP_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_testcases.h0000644000175000001440000000046614754576332014734 // app_testcases.h // Copyright (C) 2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_TESTCASES_H_ #define APP_TESTCASES_H_ #include #include "cmdline/parsed_cmd.h" bool app_testcases(Parsed_Cmd* parsed_cmd); #endif /* APP_TESTCASES_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_watch.h0000644000175000001440000000062314754576332014037 /** @file app_watch.h * Implement the WATCH command */ //Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_WATCH_H_ #define APP_WATCH_H_ #include "base/displays.h" void app_read_changes_forever( Display_Handle * dh, bool force_no_fifo); void init_app_watch(); #endif /* APP_WATCH_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_ddcutil_services.h0000644000175000001440000000046614754576332016271 /** @file app_services.h * Master initializer for app_ddcutil directory */ // Copyright (C) 2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_SERVICES_H_ #define APP_SERVICES_H_ void init_app_ddcutil_services(); #endif /* APP_DDCUTIL_SERVICES_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_vcpinfo.h0000644000175000001440000000070414754576332014375 /** @file app_vcpinfo.h * * Implement VCPINFO and (deprecated) LISTVCP commands */ // Copyright (C) 2020-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_VCPINFO_H_ #define APP_VCPINFO_H_ #include #include #include "cmdline/parsed_cmd.h" void app_listvcp(FILE * fh); bool app_vcpinfo(Parsed_Cmd * parsed_cmd); void init_app_vcpinfo(); #endif /* APP_VCPINFO_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_dynamic_features.h0000644000175000001440000000056214754576332016255 //* @file app_dynamic_features.h */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_DYNAMIC_FEATURES_H_ #define APP_DYNAMIC_FEATURES_H_ #include "base/displays.h" bool app_check_dynamic_features(Display_Ref * dref); void init_app_dynamic_features(); #endif /* APP_DYNAMIC_FEATURES_H_ */ ddcutil-2.2.0/src/app_ddcutil/app_experimental.h0000644000175000001440000000057714754576332015436 /** \file app_experimental.h */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef APP_EXPERIMENTAL_H_ #define APP_EXPERIMENTAL_H_ #include "cmdline/parsed_cmd.h" void report_experimental_options(Parsed_Cmd * parsed_cmd, int depth); void test_display_detection_variants(); #endif /* APP_EXPERIMENTAL_H_ */ ddcutil-2.2.0/src/app_sysenv/0000775000175000001440000000000014754576332011700 5ddcutil-2.2.0/src/app_sysenv/Makefile.am0000644000175000001440000000201214572333721013634 if ENABLE_ENVCMDS_COND AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public if USE_LIBDRM_COND AM_CPPFLAGS += \ $(LIBDRM_CFLAGS) endif AM_CFLAGS = -Wall if WARNINGS_ARE_ERRORS_COND AM_CFLAGS += -Werror endif # AM_CFLAGS += -Wpedantic if ENABLE_CALLGRAPH_COND AM_CFLAGS += -fdump-rtl-expand endif CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libappsysenv.la libappsysenv_la_SOURCES = \ app_sysenv_services.c \ query_sysenv.c \ query_sysenv_access.c \ query_sysenv_base.c \ query_sysenv_dmidecode.c \ query_sysenv_i2c.c \ query_sysenv_logs.c \ query_sysenv_modules.c \ query_sysenv_procfs.c \ query_sysenv_sysfs_common.c \ query_sysenv_original_sys_scans.c \ query_sysenv_detailed_bus_pci_devices.c \ query_sysenv_simplified_sys_bus_pci_devices.c \ query_sysenv_sysfs.c \ query_sysenv_xref.c if ENABLE_USB_COND libappsysenv_la_SOURCES += \ query_sysenv_usb.c endif if USE_LIBDRM_COND libappsysenv_la_SOURCES += \ query_sysenv_drm.c endif endif ddcutil-2.2.0/src/app_sysenv/Makefile.in0000664000175000001440000006556114754576155013705 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @ENABLE_ENVCMDS_COND_TRUE@@USE_LIBDRM_COND_TRUE@am__append_1 = \ @ENABLE_ENVCMDS_COND_TRUE@@USE_LIBDRM_COND_TRUE@ $(LIBDRM_CFLAGS) @ENABLE_ENVCMDS_COND_TRUE@@WARNINGS_ARE_ERRORS_COND_TRUE@am__append_2 = -Werror # AM_CFLAGS += -Wpedantic @ENABLE_CALLGRAPH_COND_TRUE@@ENABLE_ENVCMDS_COND_TRUE@am__append_3 = -fdump-rtl-expand @ENABLE_ENVCMDS_COND_TRUE@@ENABLE_USB_COND_TRUE@am__append_4 = \ @ENABLE_ENVCMDS_COND_TRUE@@ENABLE_USB_COND_TRUE@ query_sysenv_usb.c @ENABLE_ENVCMDS_COND_TRUE@@USE_LIBDRM_COND_TRUE@am__append_5 = \ @ENABLE_ENVCMDS_COND_TRUE@@USE_LIBDRM_COND_TRUE@ query_sysenv_drm.c subdir = src/app_sysenv ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libappsysenv_la_LIBADD = am__libappsysenv_la_SOURCES_DIST = app_sysenv_services.c \ query_sysenv.c query_sysenv_access.c query_sysenv_base.c \ query_sysenv_dmidecode.c query_sysenv_i2c.c \ query_sysenv_logs.c query_sysenv_modules.c \ query_sysenv_procfs.c query_sysenv_sysfs_common.c \ query_sysenv_original_sys_scans.c \ query_sysenv_detailed_bus_pci_devices.c \ query_sysenv_simplified_sys_bus_pci_devices.c \ query_sysenv_sysfs.c query_sysenv_xref.c query_sysenv_usb.c \ query_sysenv_drm.c @ENABLE_ENVCMDS_COND_TRUE@@ENABLE_USB_COND_TRUE@am__objects_1 = query_sysenv_usb.lo @ENABLE_ENVCMDS_COND_TRUE@@USE_LIBDRM_COND_TRUE@am__objects_2 = query_sysenv_drm.lo @ENABLE_ENVCMDS_COND_TRUE@am_libappsysenv_la_OBJECTS = \ @ENABLE_ENVCMDS_COND_TRUE@ app_sysenv_services.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_access.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_base.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_dmidecode.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_i2c.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_logs.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_modules.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_procfs.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_sysfs_common.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_original_sys_scans.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_detailed_bus_pci_devices.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_simplified_sys_bus_pci_devices.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_sysfs.lo \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_xref.lo \ @ENABLE_ENVCMDS_COND_TRUE@ $(am__objects_1) $(am__objects_2) libappsysenv_la_OBJECTS = $(am_libappsysenv_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = @ENABLE_ENVCMDS_COND_TRUE@am_libappsysenv_la_rpath = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/app_sysenv_services.Plo \ ./$(DEPDIR)/query_sysenv.Plo \ ./$(DEPDIR)/query_sysenv_access.Plo \ ./$(DEPDIR)/query_sysenv_base.Plo \ ./$(DEPDIR)/query_sysenv_detailed_bus_pci_devices.Plo \ ./$(DEPDIR)/query_sysenv_dmidecode.Plo \ ./$(DEPDIR)/query_sysenv_drm.Plo \ ./$(DEPDIR)/query_sysenv_i2c.Plo \ ./$(DEPDIR)/query_sysenv_logs.Plo \ ./$(DEPDIR)/query_sysenv_modules.Plo \ ./$(DEPDIR)/query_sysenv_original_sys_scans.Plo \ ./$(DEPDIR)/query_sysenv_procfs.Plo \ ./$(DEPDIR)/query_sysenv_simplified_sys_bus_pci_devices.Plo \ ./$(DEPDIR)/query_sysenv_sysfs.Plo \ ./$(DEPDIR)/query_sysenv_sysfs_common.Plo \ ./$(DEPDIR)/query_sysenv_usb.Plo \ ./$(DEPDIR)/query_sysenv_xref.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libappsysenv_la_SOURCES) DIST_SOURCES = $(am__libappsysenv_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ @ENABLE_ENVCMDS_COND_TRUE@AM_CPPFLAGS = $(GLIB_CFLAGS) \ @ENABLE_ENVCMDS_COND_TRUE@ -I$(top_srcdir)/src \ @ENABLE_ENVCMDS_COND_TRUE@ -I$(top_srcdir)/src/public \ @ENABLE_ENVCMDS_COND_TRUE@ $(am__append_1) @ENABLE_ENVCMDS_COND_TRUE@AM_CFLAGS = -Wall $(am__append_2) \ @ENABLE_ENVCMDS_COND_TRUE@ $(am__append_3) @ENABLE_ENVCMDS_COND_TRUE@CLEANFILES = \ @ENABLE_ENVCMDS_COND_TRUE@*expand # Intermediate Library @ENABLE_ENVCMDS_COND_TRUE@noinst_LTLIBRARIES = libappsysenv.la @ENABLE_ENVCMDS_COND_TRUE@libappsysenv_la_SOURCES = \ @ENABLE_ENVCMDS_COND_TRUE@ app_sysenv_services.c query_sysenv.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_access.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_base.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_dmidecode.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_i2c.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_logs.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_modules.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_procfs.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_sysfs_common.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_original_sys_scans.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_detailed_bus_pci_devices.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_simplified_sys_bus_pci_devices.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_sysfs.c \ @ENABLE_ENVCMDS_COND_TRUE@ query_sysenv_xref.c $(am__append_4) \ @ENABLE_ENVCMDS_COND_TRUE@ $(am__append_5) all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/app_sysenv/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/app_sysenv/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libappsysenv.la: $(libappsysenv_la_OBJECTS) $(libappsysenv_la_DEPENDENCIES) $(EXTRA_libappsysenv_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(am_libappsysenv_la_rpath) $(libappsysenv_la_OBJECTS) $(libappsysenv_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app_sysenv_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_access.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_base.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_detailed_bus_pci_devices.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_dmidecode.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_drm.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_i2c.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_logs.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_modules.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_original_sys_scans.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_procfs.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_simplified_sys_bus_pci_devices.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_sysfs.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_sysfs_common.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_usb.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/query_sysenv_xref.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/app_sysenv_services.Plo -rm -f ./$(DEPDIR)/query_sysenv.Plo -rm -f ./$(DEPDIR)/query_sysenv_access.Plo -rm -f ./$(DEPDIR)/query_sysenv_base.Plo -rm -f ./$(DEPDIR)/query_sysenv_detailed_bus_pci_devices.Plo -rm -f ./$(DEPDIR)/query_sysenv_dmidecode.Plo -rm -f ./$(DEPDIR)/query_sysenv_drm.Plo -rm -f ./$(DEPDIR)/query_sysenv_i2c.Plo -rm -f ./$(DEPDIR)/query_sysenv_logs.Plo -rm -f ./$(DEPDIR)/query_sysenv_modules.Plo -rm -f ./$(DEPDIR)/query_sysenv_original_sys_scans.Plo -rm -f ./$(DEPDIR)/query_sysenv_procfs.Plo -rm -f ./$(DEPDIR)/query_sysenv_simplified_sys_bus_pci_devices.Plo -rm -f ./$(DEPDIR)/query_sysenv_sysfs.Plo -rm -f ./$(DEPDIR)/query_sysenv_sysfs_common.Plo -rm -f ./$(DEPDIR)/query_sysenv_usb.Plo -rm -f ./$(DEPDIR)/query_sysenv_xref.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/app_sysenv_services.Plo -rm -f ./$(DEPDIR)/query_sysenv.Plo -rm -f ./$(DEPDIR)/query_sysenv_access.Plo -rm -f ./$(DEPDIR)/query_sysenv_base.Plo -rm -f ./$(DEPDIR)/query_sysenv_detailed_bus_pci_devices.Plo -rm -f ./$(DEPDIR)/query_sysenv_dmidecode.Plo -rm -f ./$(DEPDIR)/query_sysenv_drm.Plo -rm -f ./$(DEPDIR)/query_sysenv_i2c.Plo -rm -f ./$(DEPDIR)/query_sysenv_logs.Plo -rm -f ./$(DEPDIR)/query_sysenv_modules.Plo -rm -f ./$(DEPDIR)/query_sysenv_original_sys_scans.Plo -rm -f ./$(DEPDIR)/query_sysenv_procfs.Plo -rm -f ./$(DEPDIR)/query_sysenv_simplified_sys_bus_pci_devices.Plo -rm -f ./$(DEPDIR)/query_sysenv_sysfs.Plo -rm -f ./$(DEPDIR)/query_sysenv_sysfs_common.Plo -rm -f ./$(DEPDIR)/query_sysenv_usb.Plo -rm -f ./$(DEPDIR)/query_sysenv_xref.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/app_sysenv/app_sysenv_services.c0000644000175000001440000000060314572333721016042 // app_sysenv_services.c // Copyright (C) 2018 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "app_sysenv_services.h" #include "query_sysenv_detailed_bus_pci_devices.h" #include "query_sysenv_sysfs.h" void init_app_sysenv_services() { init_query_detailed_bus_pci_devices(); init_query_sysenv_sysfs(); init_query_sysenv(); } ddcutil-2.2.0/src/app_sysenv/query_sysenv.c0000644000175000001440000011112414754153540014526 /** @file query_sysenv.c * * Primary file for the ENVIRONMENT command */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later // #define SYSENV_QUICK_TEST_RUN 1 /** \cond */ #include "config.h" // #define _GNU_SOURCE 1 // for function group_member #include #include #include #include #include #ifdef USE_X11 #include #endif #include "util/data_structures.h" #include "util/edid.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/xdg_util.h" #ifdef PROBE_USING_SYSTEMD #include "util/systemd_util.h" #endif #ifdef USE_X11 #include "util/x11_util.h" #endif #ifdef ENABLE_UDEV #include "util/udev_i2c_util.h" #ifdef ENABLE_USB #include "util/udev_usb_util.h" #endif #endif /** \endcond */ #include "base/build_info.h" #include "base/core.h" #include "base/dsa2.h" #include "base/flock.h" #include "base/linux_errno.h" #include "base/parms.h" #include "base/rtti.h" #include "base/stats.h" #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_execute.h" // for i2c_forceable_slave_addr_flag #include "ddc/ddc_displays.h" // for ddc_ensure_displays_detected() #include "ddc/ddc_display_ref_reports.h" #include "ddc/ddc_serialize.h" #include "ddc/ddc_try_data.h" #include "dw/dw_udev.h" #include "vcp/persistent_capabilities.h" #include "query_sysenv_access.h" #include "query_sysenv_base.h" #include "query_sysenv_dmidecode.h" #include "query_sysenv_drm.h" #include "query_sysenv_i2c.h" #include "query_sysenv_logs.h" #include "query_sysenv_modules.h" #include "query_sysenv_procfs.h" #include "query_sysenv_sysfs.h" #include "query_sysenv_xref.h" #include "query_sysenv.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_ENV; /** Compile time and runtime checks of endianness. * * \param depth logical indentation depth */ static void report_endian(int depth) { int d1 = depth+1; rpt_title("Byte order checks:", depth); bool is_bigendian = (*(uint16_t *)"\0\xff" < 0x100); rpt_vstring(d1, "Is big endian (local test): %s", sbool(is_bigendian)); rpt_vstring(d1, "WORDS_BIGENDIAN macro (autoconf): " #ifdef WORDS_BIGENDIAN "defined" #else "not defined" #endif ); rpt_vstring(d1, "__BYTE_ORDER__ macro (gcc): " #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ "__ORDER_LITTLE_ENDIAN__" #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ "__ORDER_BIG_ENDIAN__" #elif __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ "__ORDER_PDP_ENDIAN__" #else "unexpected value" #endif ); #ifdef REDUNDANT __u32 i = 1; bool is_bigendian2 = ( (*(char*)&i) == 0 ); rpt_vstring(d1, "Is big endian (runtime test): %s", sbool(is_bigendian2)); #endif } // // Higher level functions // /** Reports basic system information * * \param accum pointer to struct in which information is returned */ static void query_base_env(Env_Accumulator * accum) { int d0 = 0; int d1 = d0+1; int d2 = d0+2; rpt_vstring(d0, "ddcutil version: %s", get_full_ddcutil_version()); rpt_nl(); sysenv_rpt_file_first_line("/proc/version", NULL, 0); char * expected_architectures[] = {"x86_64", "i386", "i686", "armv7l", "aarch64", "ppc64", NULL}; // n. alternative command "arch" not found on Arch Linux // uname -m machine hardware name // uname -p processor type (non-portable) // uname -i hardware platform (non-portable) accum->architecture = execute_shell_cmd_one_line_result("uname -m"); accum->distributor_id = execute_shell_cmd_one_line_result("lsb_release -s -i"); // e.g. Ubuntu, Raspbian char * release = execute_shell_cmd_one_line_result("lsb_release -s -r"); rpt_nl(); rpt_vstring(d0, "Architecture: %s", accum->architecture); rpt_vstring(d0, "Distributor id: %s", accum->distributor_id); rpt_vstring(d0, "Release: %s", release); if ( ntsa_find(expected_architectures, accum->architecture) >= 0) { rpt_vstring(d0, "Found a known architecture"); } else { rpt_vstring(d0, "Unexpected architecture %s. Please report.", accum->architecture); } accum->is_raspbian = accum->distributor_id && streq(accum->distributor_id, "Raspbian"); accum->is_arm = accum->architecture && ( str_starts_with(accum->architecture, "arm") || str_starts_with(accum->architecture, "aarch") ); free(release); #ifdef REDUNDANT rpt_nl(); rpt_vstring(0,"/etc/os-release..."); bool ok = execute_shell_cmd_rpt("grep PRETTY_NAME /etc/os-release", 1 /* depth */); if (!ok) rpt_vstring(1,"Unable to read PRETTY_NAME from /etc/os-release"); #endif rpt_nl(); sysenv_rpt_file_first_line("/proc/cmdline", NULL, d0); if (get_output_level() >= DDCA_OL_VERBOSE) { rpt_nl(); rpt_vstring(d0, "Compiler information:"); rpt_vstring(d1, "C standard: %ld", __STDC_VERSION__); #if defined(__GNUC__) rpt_vstring(d1, "gcc compatible compiler:"); rpt_vstring(d2, "Compiler version: %d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // not detecting clang (11/2018) #if defined(__clang__) rpt_vstring(d2, "Clang version: %s", __clang_version__); #endif #else rpt_vstring(d1, "Not a gcc compatible compiler"); #endif rpt_nl(); rpt_vstring(d0,"Processor information as reported by lscpu:"); bool ok = execute_shell_cmd_rpt("lscpu", 1); if (!ok) { // lscpu should always be there, but just in case: rpt_vstring(1, "Command lscpu not found"); rpt_nl(); rpt_title("Processor information from /proc/cpuinfo:", d0); // uniq because entries for each processor of a mulit-processor cpu execute_shell_cmd_rpt( "cat /proc/cpuinfo | grep vendor_id | uniq", d1); execute_shell_cmd_rpt( "cat /proc/cpuinfo | grep \"cpu family\" | uniq", d1); execute_shell_cmd_rpt( "cat /proc/cpuinfo | grep \"model[[:space:]][[:space:]]\" | uniq", d1); // "model" execute_shell_cmd_rpt( "cat /proc/cpuinfo | grep \"model name\" | uniq", d1); // "model name" } rpt_nl(); if (accum->is_arm) { rpt_vstring(d0, "Skipping dmidecode checks on architecture %s.", accum->architecture); } else { query_dmidecode(); } rpt_nl(); report_endian(d0); } } #ifdef OLD /* Checks for installed packages i2c-tools and libi2c-dev */ static void query_packages() { rpt_multiline(0, "ddcutil requiries package i2c-tools. Use both dpkg and rpm to look for it.", "While we're at it, check for package libi2c-dev which is used for building", "ddcutil.", NULL ); bool ok; // n. apt show produces warning msg that format of output may change. // better to use dpkg rpt_nl(); rpt_vstring(0,"Using dpkg to look for package i2c-tools..."); ok = execute_shell_cmd_rpt("dpkg --status i2c-tools", 1); if (!ok) rpt_vstring(0,"dpkg command not found"); else { execute_shell_cmd_rpt("dpkg --listfiles i2c-tools", 1); } rpt_nl(); rpt_vstring(0,"Using dpkg to look for package libi2c-dev..."); ok = execute_shell_cmd_rpt("dpkg --status libi2c-dev", 1); if (!ok) rpt_vstring(0,"dpkg command not found"); else { execute_shell_cmd_rpt("dpkg --listfiles libi2c-dev", 1); } rpt_nl(); rpt_vstring(0,"Using rpm to look for package i2c-tools..."); ok = execute_shell_cmd_rpt("rpm -q -l --scripts i2c-tools", 1); if (!ok) rpt_vstring(0,"rpm command not found"); } #endif static void execute_cmd(int depth, const char * cmd) { char * msgbuf = g_strdup_printf("Executing: %s", cmd); rpt_label(depth, msgbuf); free(msgbuf); // bool ok = execute_shell_cmd_rpt(cmd, depth+1); // if (!ok) // rpt_label(depth, "Command failed"); } /* Performs checks specific to the nvidia and fglrx proprietary video drivers. * * Arguments: * driver list list of loaded drivers * * Returns: nothing */ static void driver_specific_tests(struct driver_name_node * driver_list) { rpt_vstring(0,"Performing driver specific checks..."); bool found_driver_specific_checks = false; if (driver_name_list_find_prefix(driver_list, "nvidia")) { found_driver_specific_checks = true; rpt_nl(); rpt_vstring(0,"Checking for special settings for proprietary Nvidia driver "); rpt_vstring(0,"(Needed for some newer Nvidia cards)."); execute_shell_cmd_rpt("grep -iH i2c /etc/X11/xorg.conf /etc/X11/xorg.conf.d/*", 1); execute_cmd(1,"grep -iH nvidia modprobe.conf modprobe.d/*"); execute_cmd(1,"grep RegistryDwords /proc/driver/nvidia/params"); } if (driver_name_list_find_prefix(driver_list, "fglrx")) { found_driver_specific_checks = true; rpt_nl(); rpt_vstring(0,"Performing ADL specific checks..."); rpt_vstring(0,"WARNING: Using AMD proprietary video driver fglrx but ddcutil built without ADL support"); } if (!found_driver_specific_checks) rpt_vstring(0,"No driver specific checks apply."); } #ifdef USE_X11 // // Using X11 API // /* Reports EDIDs known to X11 * * Arguments: use_screen_resources_current * * Returns: nothing */ void query_x11_0(bool use_screen_resources_current) { GPtrArray* edid_recs = get_x11_edids(use_screen_resources_current); rpt_nl(); rpt_vstring(0,"EDIDs reported by X11 for connected xrandr outputs %susing XRRGetScreenResourcesCurrent", (use_screen_resources_current) ? "" : "NOT "); // DBGMSG("Got %d X11_Edid_Recs\n", edid_recs->len); int d1 = 1; int d2 = 2; for (int ndx=0; ndx < edid_recs->len; ndx++) { X11_Edid_Rec * prec = g_ptr_array_index(edid_recs, ndx); // printf(" Output name: %s -> %p\n", prec->output_name, prec->edid); // hex_dump(prec->edid, 128); rpt_vstring(d1, "xrandr output: %s", prec->output_name); Byte * edidbytes = prec->edidbytes; #ifdef SYSENV_TEST_IDENTICAL_EDIDS // for testing case of monitors with same EDID if (first_edid) { edidbytes = first_edid; DBGMSG("Forcing duplicate EDID"); } #endif rpt_label (d2, "Raw EDID:"); rpt_hex_dump(edidbytes, 128, 2); Parsed_Edid * parsed_edid = create_parsed_edid2(edidbytes, "X11"); if (parsed_edid) { report_parsed_edid_base( parsed_edid, true, // verbose false, // show_hex d2); // depth free_parsed_edid(parsed_edid); } else { rpt_label(d2, "Unable to parse EDID"); // printf(" Unparsable EDID for output name: %s -> %p\n", prec->output_name, prec->edidbytes); // hex_dump(prec->edidbytes, 128); } // Device_Id_Xref * xref = device_xref_get(prec->edidbytes); Device_Id_Xref * xref = device_xref_find_by_edid(edidbytes); if (xref) { xref->xrandr_name = strdup(prec->output_name); if (xref->ambiguous_edid) { rpt_vstring(d2, "Multiple displays have same EDID ...%s", xref->edid_tag); rpt_vstring(d2, "xrandr name in device cross reference table may be incorrect."); } } else { DBGMSG("EDID not found"); } rpt_nl(); } free_x11_edids(edid_recs); // Display * x11_disp = open_default_x11_display(); // GPtrArray * outputs = get_x11_connected_outputs(x11_disp); // close_x11_display(x11_disp); } void query_x11() { rpt_nl(); rpt_label(0, "*** Querying X11 ***"); rpt_nl(); rpt_vstring(0, "randr_version: %d.%d", RANDR_MAJOR, RANDR_MINOR); query_x11_0(false); query_x11_0(true); rpt_nl(); unsigned short power_level; unsigned char state; bool got_dpms = get_x11_dpms_info(&power_level, &state); rpt_vstring(0, "Extension DPMS is%s supported. get_x11_dpms_info() returned %s", (got_dpms) ? "" : " NOT", SBOOL(got_dpms)); rpt_nl(); } #endif static void query_using_shell_command(Byte_Value_Array i2c_device_numbers, const char * pattern, const char * command_name) { assert(i2c_device_numbers); int d0 = 0; int d1 = 1; rpt_vstring(d0,"Examining I2C buses using %s... ", command_name); sysenv_rpt_current_time(NULL, d1); if (bva_length(i2c_device_numbers) == 0) { rpt_vstring(d1, "No I2C buses found"); } else { for (int ndx=0; ndx< bva_length(i2c_device_numbers); ndx++) { int busno = bva_get(i2c_device_numbers, ndx); if (sysfs_is_ignorable_i2c_device(busno)) { rpt_nl(); rpt_vstring(d1, "Device /dev/i2c-%d is a SMBus or other ignorable device." " Skipping %s.", busno, command_name); } else { char cmd[200]; snprintf(cmd, 200, pattern, busno); // "udevadm info --attribute-walk --path=$(udevadm info --query=path --name=i2c-%d)", busno); rpt_nl(); rpt_vstring(d1,"Probing bus /dev/i2c-%d using command \"%s\"", busno, cmd); int rc = execute_shell_cmd_rpt(cmd, 2 /* depth */); // DBGMSG("execute_shell_cmd(\"%s\") returned %d", cmd, rc); if (rc != 1) { rpt_vstring(d1,"%s command unavailable", command_name); break; } } } } } #ifdef ENABLE_UDEV /** Queries UDEV for devices in subsystem "i2c-dev". * Also looks for devices with name attribute "DPMST" */ static void probe_i2c_devices_using_udev() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); char * subsys_name = "i2c-dev"; rpt_vstring(0,"*** Probe I2C devices using udev, susbsystem %s ***", subsys_name); sysenv_rpt_current_time(NULL, 1); // probe_udev_subsystem() is in udev_util.c, which is only linked in if ENABLE_USB // Detailed scan of I2C device information. TMI // probe_udev_subsystem(subsys_name, /*show_usb_parent=*/ false, 1); rpt_nl(); GPtrArray * summaries = get_i2c_devices_using_udev(); report_i2c_udev_device_summaries(summaries, "Summary of udev I2C devices",1); for (int ndx = 0; ndx < summaries->len; ndx++) { Udev_Device_Summary * summary = g_ptr_array_index(summaries, ndx); assert( memcmp(summary->marker, UDEV_DEVICE_SUMMARY_MARKER, 4) == 0); int busno = udev_i2c_device_summary_busno(summary); Device_Id_Xref * xref = device_xref_find_by_busno(busno); if (xref) { xref->udev_name = strdup(summary->sysattr_name); xref->udev_syspath = strdup(summary->devpath); xref->udev_busno = busno; } else { // DBGMSG("Device_Id_Xref not found for busno %d", busno); } } free_udev_device_summaries(summaries); // ok if summaries == NULL rpt_nl(); char * nameattr = "DPMST"; rpt_vstring(0,"Looking for udev devices with name attribute %s...", nameattr); summaries = find_devices_by_sysattr_name(nameattr); report_i2c_udev_device_summaries(summaries, "Summary of udev DPMST devices...",1); free_udev_device_summaries(summaries); // ok if summaries == NULL rpt_nl(); DBGTRC_DONE(debug, TRACE_GROUP, ""); } #endif void rpt_module_status(int depth, const char * module_name) { int module_status = module_status_by_modules_builtin_or_existence(module_name); switch( module_status) { case KERNEL_MODULE_NOT_FOUND: // 0 rpt_vstring(depth,"Kernel module %-16s not found", module_name); break; case KERNEL_MODULE_BUILTIN: // 1 rpt_vstring(depth,"Kernel module %-16s is builtin", module_name); break; case KERNEL_MODULE_LOADABLE_FILE: // 2 if (is_module_loaded_using_sysfs(module_name)) rpt_vstring(depth, "Kernel module %-16s is loaded", module_name); else rpt_vstring(depth, "Kernel module %-16s found but not loaded", module_name); break; default: rpt_vstring(depth, "Error %s from module_status_by_modules_builtin_or_existence() for %s", psc_desc(module_status), module_name); break; } } void query_loaded_modules() { rpt_vstring(0,"*** Checking if modules are loaded or builtin... ***"); char ** pmodule_names = get_known_video_driver_module_names(); char * curmodule; int ndx; for (ndx=0; (curmodule=pmodule_names[ndx]) != NULL; ndx++) { rpt_module_status(1, curmodule); } pmodule_names = get_other_driver_module_names(); for (ndx=0; (curmodule=pmodule_names[ndx]) != NULL; ndx++) { rpt_module_status(1, curmodule); } } static GPtrArray * get_path_application_files(const char * path, const char * application) { GPtrArray * fqfns = g_ptr_array_new_with_free_func(free); Null_Terminated_String_Array dirs = strsplit(path, ":"); char * dirname; for (int ndx = 0; (dirname=dirs[ndx]); ndx++) { char * appdir = (dirname[strlen(dirname)-1] == '/') ? g_strdup_printf("%s%s", dirname, application) : g_strdup_printf("%s/%s", dirname, application); DIR * d = opendir(appdir); if (d) { struct dirent *directory_entry; while ((directory_entry = readdir(d)) != NULL) { // printf("%s\n", directory_entry->d_name); if (directory_entry->d_type == DT_REG) { char * fq_name = g_strdup_printf("%s/%s", appdir, directory_entry->d_name); g_ptr_array_add(fqfns, fq_name); } } closedir(d); } free(appdir); } ntsa_free(dirs, true); return fqfns; } static void query_xdg_files(int depth) { int d1 = depth+1; int d2 = depth+2; int d3 = depth+3; rpt_label(depth, "*** XDG Directory Settings ***"); rpt_label(d1, "XDG Base Directory Environment Variables:"); rpt_vstring(d2, "$%-15s: %s", "XDG_DATA_HOME", getenv("XDG_DATA_HOME")); rpt_vstring(d2, "$%-15s: %s", "XDG_CONFIG_HOME", getenv("XDG_CONFIG_HOME")); rpt_vstring(d2, "$%-15s: %s", "XDG_STATE_HOME", getenv("XDG_STATE_HOME")); rpt_vstring(d2, "$%-15s: %s", "XDG_CACHE_HOME", getenv("XDG_CACHE_HOME")); rpt_vstring(d2, "$%-15s: %s", "XDG_DATA_DIRS", getenv("XDG_DATA_DIRS")); rpt_vstring(d2, "$%-15s: %s", "XDG_CONFIG_DIRS", getenv("XDG_CONFIG_DIRS")); rpt_nl(); rpt_label(depth, "XDG Utility Functions:"); char * s = NULL; s = xdg_data_home_dir(); rpt_vstring(d2, "xdg_data_home_dir(): %s", s); free(s); s = xdg_config_home_dir(); rpt_vstring(d2, "xdg_config_home_dir(): %s", s); free(s); s = xdg_cache_home_dir(); rpt_vstring(d2, "xdg_cache_home_dir(): %s", s); free(s); s = xdg_state_home_dir(); rpt_vstring(d2, "xdg_state_home_dir(): %s", s); free(s); s = xdg_data_path(); rpt_vstring(d2, "xdg_data_path(): %s", s); free(s); s = xdg_config_path(); rpt_vstring(d2, "xdg_config_path(): %s", s); free(s); rpt_nl(); rpt_label(depth, "*** ddcutil Configuration, Cache, and Data files ***"); char * config_fn = find_xdg_config_file("ddcutil", "ddcutilrc"); rpt_nl(); if (config_fn) { rpt_vstring(d1, "Found configuration file: %s", config_fn); rpt_file_contents(config_fn, /*verbose=*/ true, d2); free(config_fn); } else rpt_label(d1, "Configuration file ddcutilrc not found"); rpt_nl(); probe_cache_files(depth); #ifdef OLD char * cache_fn = find_xdg_cache_file("ddcutil", "capabilities"); if (cache_fn) { rpt_vstring(d1, "Found capabilities cache file: %s", cache_fn); rpt_file_contents(cache_fn, /*verbose=*/ true, d2); free(cache_fn); } else rpt_label(d1, "Capabilities cache file not found"); rpt_nl(); #endif rpt_label(d1, "Files on data path:"); char * data_path = xdg_data_path(); GPtrArray * data_files = get_path_application_files(data_path, "ddcutil"); for (int ndx = 0; ndx < data_files->len; ndx++) { char * fn = g_ptr_array_index(data_files, ndx); rpt_label(d2, fn); if (str_ends_with(fn, ".mccs")) { rpt_file_contents(fn, /*verbose=*/ true, d3); rpt_nl(); } } free(data_path); g_ptr_array_free(data_files, true); rpt_nl(); } /** Analyze collected environment information, Make suggestions. * * \param accum accumulated environment information * \param depth logical indentation depth */ void final_analysis(Env_Accumulator * accum, int depth) { int d1 = depth + 1; int d2 = depth + 2; int d3 = depth + 3; // for testing: // accum->dev_i2c_common_group_name = NULL; // accum->module_i2c_dev_loaded_or_builtin = false; // accum->cur_user_all_devi2c_rw = false; // accum->all_dev_i2c_is_group_rw = false; bool odd_groups = accum->dev_i2c_common_group_name && !streq(accum->dev_i2c_common_group_name, "root") && !streq(accum->dev_i2c_common_group_name, "i2c"); bool msg_issued = false; rpt_vstring(depth, "Configuration suggestions:"); if (odd_groups) { rpt_label (d1, "Issue:"); rpt_label (d2, "/dev/i2c-N devices have non-standard or varying group names."); rpt_label (d2, "Suggestions are incomplete."); rpt_nl(); msg_issued = true; } // TODO: Also compare dev_i2c_devices vs sys_bus_i2c_devices ? assert(accum->dev_i2c_device_numbers); // already set if (bva_length(accum->dev_i2c_device_numbers) == 0 && accum->module_i2c_dev_needed && !accum->i2c_dev_loaded_or_builtin) { rpt_label (d1, "Issue:"); rpt_label (d2, "No /dev/i2c-N devices found."); rpt_vstring(d2, "%sI2C devices exist in /sys/bus/i2c", (accum->sysfs_i2c_devices_exist) ? "" : "No "); rpt_label (d2, "Module dev-i2c is required."); rpt_label (d2, "Module dev-i2c is not loaded"); rpt_label (d1, "Suggestion:"); rpt_label (d2, "Manually load module i2c-dev using the command:"); rpt_label (d3, "sudo modprobe i2c-dev"); rpt_label (d2, "If this solves the problem, put an entry in directory /etc/modules-load.d"); rpt_label (d2, "that will cause i2c-dev to be loaded. Type \"man modules-load.d\" for details"); rpt_nl(); msg_issued = true; } else { if (accum->cur_user_all_devi2c_rw) { // n. will be true if no /dev/i2c-N devices exist rpt_label(d1, "Current user has RW access to all /dev/i2c-N devices."); rpt_label(d1, "Skipping further group and permission checks."); rpt_nl(); msg_issued = true; } else { if (accum->cur_user_any_devi2c_rw) { rpt_label (d1, "Issue:"); rpt_multiline(d2, "Current user has RW access to some but not all /dev/i2c-N devices.", "If there is RW access to at least the /dev/i2c-N devices for connected monitors,", "this is not a problem.", "Remaining suggestions assume RW access is still to be established.", "", NULL ); msg_issued = true; } if (!accum->group_i2c_exists) { rpt_label (d1, "Issue:"); rpt_label (d2, "Group i2c does not exist."); rpt_label (d1, "Suggestion:"); rpt_label (d2, "Create group i2c. To create group i2c, use command:"); rpt_label (d3, "sudo groupadd --system i2c"); rpt_label (d2, "Assign /dev/i2c-N devices to group i2c by adding a rule to /etc/udev/rules.d"); rpt_label (d2, "Add the current user to group i2c:"); rpt_label (d3, "sudo usermod -G i2c -a "); rpt_label (d2, "After this, you will have to logout and login again."); rpt_label (d2, "The changes to the user's group list are not read until a new login."); rpt_nl(); msg_issued = true; } else { // group i2c exists if (!accum->all_dev_i2c_has_group_i2c) { // Punt on odd case were some but not all /dev/i2c-N devices are in group i2c if (accum->any_dev_i2c_has_group_i2c) { rpt_label (d1, "Issue:"); rpt_multiline(d2, "Some but not all /dev/i2c-N devices have group i2c.", "If the /dev/i2c-N devices for connected monitors have group i2c," "this is not a problem. Remaining suggestions assume /dev/i2c-N " "devices require assignment to group i2c.", "", NULL ); // msg_issued = true; // redundant, clang complains } rpt_label (d1, "Issue:"); rpt_label (d2, "/dev/i2c-N devices not assigned to group i2c"); rpt_label (d1, "Suggestion:"); rpt_label (d2, "Assign /dev/i2c-N devices to group i2c by adding or editing a rule"); rpt_label (d2, "in /etc/udev/rules.d"); rpt_nl(); msg_issued = true; } // handle case of /dev/i2c-N devices have group i2c, but not RW if (!accum->cur_user_in_group_i2c) { rpt_label (d1, "Issue:"); rpt_label (d2, "Current user is not a member of group i2c"); rpt_label (d1, "Suggestion:"); rpt_label (d2, "Execute command:"); rpt_vstring(d3, "sudo usermod -G i2c -a %s", accum->cur_uname); rpt_label (d2, "After this, you will have to logout and login again."); rpt_label (d2, "The changes to the user's group list are not read until a new login."); rpt_nl(); msg_issued = true; } } if (!accum->all_dev_i2c_is_group_rw && !streq(accum->dev_i2c_common_group_name, "root")) { rpt_label (d1, "Issue:"); rpt_label (d2, "At least some /dev/i2c-N devices do not have group RW permission."); rpt_label (d1, "Suggestion:"); rpt_label (d2, "Set group RW access to /dev/i2c-N devices by adding or editing a rule"); rpt_label (d2, "in /etc/udev/rules.d"); rpt_nl(); msg_issued = true; } } } if (!msg_issued) { rpt_vstring(d1, "None"); rpt_nl(); } } void force_envcmd_settings(Parsed_Cmd * parsed_cmd) { f0printf(fout(), "Setting output level very-verbose...\n"); set_output_level(DDCA_OL_VV); // affects this thread only f0printf(fout(), "Setting maximum retries...\n"); try_data_set_maxtries2(WRITE_ONLY_TRIES_OP, MAX_MAX_TRIES); try_data_set_maxtries2(WRITE_READ_TRIES_OP, MAX_MAX_TRIES); try_data_set_maxtries2(MULTI_PART_READ_OP, MAX_MAX_TRIES); try_data_set_maxtries2(MULTI_PART_WRITE_OP, MAX_MAX_TRIES); f0printf(fout(), "Forcing --stats...\n"); parsed_cmd->stats_types = DDCA_STATS_ALL; f0printf(fout(), "Forcing --disable-capabilities-cache...\n"); enable_capabilities_cache(false); f0printf(fout(), "Forcing --force-slave-address..\n"); i2c_forceable_slave_addr_flag = true; f0printf(fout(), "Forcing --disable-cross-instance-locking...\n"); i2c_enable_cross_instance_locks(false); if (dsa2_is_enabled()) { f0printf(fout(), "Dynamic sleep currently enabled, disabling...\n"); dsa2_enable(false); } else { f0printf(fout(), "Dynamic sleep currently disabled.\n"); } } // // Mainline // /* Master function to query the system environment * * Arguments: none * * Returns: nothing */ void query_sysenv(bool quick_env) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); rpt_label(0, "The following tests probe the runtime environment using multiple overlapping methods."); char * s = getenv("SYSENV_QUICK_TEST"); if ((s && strlen(s) > 0) || quick_env) { sysfs_quick_test = true; rpt_label(0, "Environment variable SYSENV_QUICK_TEST or option --quickenv is set. Skipping some tests."); } else if (get_output_level() >= DDCA_OL_VERBOSE) { rpt_label(0, "Set environment variable SYSENV_QUICK_TEST or option --quickenv to skip some long-running tests."); } i2c_forceable_slave_addr_flag = true; // be a bully ddc_ensure_displays_detected(); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "display detection complete"); device_xref_init(); Env_Accumulator * accumulator = env_accumulator_new(); DDCA_Output_Level output_level = get_output_level(); if (output_level >= DDCA_OL_VERBOSE) { sysenv_rpt_current_time(NULL, 1); rpt_nl(); } if (output_level >= DDCA_OL_VERBOSE) { report_build_options(0); rpt_nl(); } rpt_vstring(0,"*** Basic System Information ***"); rpt_nl(); query_base_env(accumulator); rpt_nl(); rpt_vstring(0,"*** Primary Check 1: Identify video card and driver ***"); rpt_nl(); query_card_and_driver_using_sysfs(accumulator); rpt_nl(); rpt_vstring(0,"*** Primary Check 2: Check that /dev/i2c-* exist and writable ***"); rpt_nl(); accumulator->dev_i2c_device_numbers = identify_i2c_devices(); assert(accumulator->dev_i2c_device_numbers); // redundant // rpt_vstring(0, "Identified %d I2C devices", bva_length(accumulator->dev_i2c_device_numbers)); // rpt_nl(); check_i2c_devices(accumulator); rpt_nl(); rpt_vstring(0,"*** Primary Check 3: Check that module i2c_dev is loaded ***"); rpt_nl(); check_i2c_dev_module(accumulator, 0); rpt_nl(); rpt_vstring(0,"*** Primary Check 4: Driver specific checks ***"); rpt_nl(); driver_specific_tests(accumulator->driver_list); // TODO: move to end of function // Free the driver list created by query_card_and_driver_using_sysfs() // free_driver_name_list(accumulator->driver_list); // driver_list = NULL; #ifdef OLD rpt_nl(); rpt_vstring(0,"*** Primary Check 5: Installed packages ***"); rpt_nl(); query_packages(); rpt_nl(); #endif rpt_nl(); rpt_vstring(0,"*** Additional probes ***"); rpt_nl(); query_sys_bus_i2c(accumulator); rpt_nl(); env_accumulator_report(accumulator, 0); rpt_nl(); final_analysis(accumulator, 0); // A quick hack to reduce the amount of output when testing typedef enum { Probe_Class_None = 0, Probe_Class_Detect = 1, Probe_Class_Drivers = 2, Probe_Class_Most = 4, Probe_Class_Logs = 8, Probe_Class_Sysfs = 16, Probe_Class_Libdrm = 32, Probe_Class_I2cdetect = 64, Probe_Class_Local_Files = 128, Probe_Class_All = 255 } Probe_Class; Probe_Class probe_what = Probe_Class_All; if (output_level >= DDCA_OL_VERBOSE) { rpt_nl(); rpt_nl(); rpt_label(0, "*** Additional checks for remote diagnosis ***"); rpt_nl(); rpt_label(0, "Disabling capabilities cache ..."); enable_capabilities_cache(false); #ifdef DISPLAYS_CACHE rpt_label(0, "Disabling displays cache ..."); ddc_enable_displays_cache(false); #endif rpt_label(0, "Disabling dynamic sleep ..."); dsa2_enable(false); rpt_nl(); if (probe_what & Probe_Class_Detect) { rpt_vstring(0, "*** Displays as reported by DETECT Command ***"); /* int display_ct = */ ddc_report_displays( // function used by DETECT command true, // include_invalid_displays 1); // logical depth // printf("Detected: %d displays\n", display_ct); // not needed } if (probe_what & Probe_Class_Drivers) { query_loaded_modules(); rpt_nl(); // printf("Gathering card and driver information...\n"); query_proc_modules_for_video(); if (!accumulator->is_arm) { // rpt_nl(); // query_card_and_driver_using_lspci(); //rpt_nl(); //query_card_and_driver_using_lspci_alt(); } rpt_nl(); if ( driver_name_list_find_exact(accumulator->driver_list, "nvidia")) { query_proc_driver_nvidia(); rpt_nl(); } if (driver_name_list_find_exact(accumulator->driver_list, "amdgpu")) { rpt_vstring(0, "amdgpu configuration parameters:"); query_sys_amdgpu_parameters(1); rpt_nl(); } } if (probe_what & Probe_Class_Most) { rpt_vstring(0, "Checking display manager environment variables..."); char * s = getenv("DISPLAY"); rpt_vstring(1, "DISPLAY=%s", (s) ? s : "(not set)"); s = getenv("WAYLAND_DISPLAY"); rpt_vstring(1, "WAYLAND_DISPLAY=%s", (s) ? s : "(not set)"); s = getenv("XDG_SESSION_TYPE"); rpt_vstring(1, "XDG_SESSION_TYPE=%s", (s) ? s : "(not set)"); rpt_nl(); query_i2c_buses(); rpt_nl(); rpt_vstring(0,"xrandr connection report:"); execute_shell_cmd_rpt("xrandr|grep connected", 1 /* depth */); rpt_nl(); rpt_vstring(0,"Checking for possibly conflicting programs..."); execute_shell_cmd_rpt("ps aux | grep ddccontrol | grep -v grep", 1); rpt_nl(); execute_shell_cmd_rpt("lsmod | grep ddcci | grep -v grep", 1); rpt_nl(); } if (probe_what & Probe_Class_I2cdetect) { if (sysfs_quick_test) DBGMSG("!!! Skipping i2cdetect and get-edid|parse-edid to speed up testing !!!"); else { query_using_shell_command(accumulator->dev_i2c_device_numbers, "i2cdetect -y %d", // command to issue "i2cdetect"); // command name for error message rpt_nl(); // -i option may not exist query_using_shell_command(accumulator->dev_i2c_device_numbers, "get-edid -b %d | parse-edid", // command to issue "get-edid | parse-edid"); // command name for error message } } if (probe_what & Probe_Class_Most) { if (get_output_level() >= DDCA_OL_VV) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "--VV only output: test_read_variants()"); test_edid_read_variants(accumulator); } raw_scan_i2c_devices(accumulator); #ifdef USE_X11 query_x11(); #endif #ifdef ENABLE_UDEV probe_i2c_devices_using_udev(); #endif // temp // get_i2c_smbus_devices_using_udev(); probe_config_files(accumulator); } if (probe_what & Probe_Class_Logs) { if (sysfs_quick_test) DBGMSG("!!! Skipping log checking to speed up testing !!!"); else { probe_logs(accumulator); } } if (probe_what & Probe_Class_Libdrm) { #ifdef USE_LIBDRM probe_using_libdrm(); #else rpt_vstring(0, "Not built with libdrm support. Skipping DRM related checks"); #endif } if (probe_what & Probe_Class_Sysfs) { query_drm_using_sysfs(); rpt_nl(); rpt_title("Query file system for i2c nodes under /sys/class/drm/card*...", 0); execute_shell_cmd_rpt("ls -ld /sys/class/drm/card*/card*/i2c*", 1); rpt_title("Query file system for i2c nodes under /sys/class/drm/card*/ddc/i2c-dev/...", 0); execute_shell_cmd_rpt("ls -ld /sys/class/drm/card*/card*/ddc/i2c-dev/i2c*", 1); device_xref_report(0); probe_modules_d(0); dump_sysfs_i2c(accumulator); rpt_nl(); } #ifdef OLD if (get_output_level() >= DDCA_OL_VV) { rpt_nl(); rpt_label(0, "*** Calling get_sysfs_drm_card_numbers(), get_sysfs_drm_displays() from ddc_watch.c... ***"); Byte_Bit_Flags drm_card_numbers = get_sysfs_drm_card_numbers(); if (bbf_count_set(drm_card_numbers) > 0) { query_drm_using_sysfs(); } } #endif #ifdef TMI #ifdef ENABLE_UDEV if (get_output_level() >= DDCA_OL_VV) { rpt_nl(); query_using_shell_command(accumulator->dev_i2c_device_numbers, // "udevadm info --attribute-walk --path=$(udevadm info --query=path --name=i2c-%d)", "udevadm info --attribute-walk /dev/i2c-%d", "udevadm"); } #endif #endif if (probe_what & Probe_Class_Most) { query_xdg_files(0); } rpt_label(0, "*** environment command complete ***"); } env_accumulator_free(accumulator); // make Coverity happy DBGTRC_DONE(debug, TRACE_GROUP, ""); } void init_query_sysenv() { RTTI_ADD_FUNC(query_sysenv); #ifdef ENABLE_UDEV RTTI_ADD_FUNC(probe_i2c_devices_using_udev); #endif } ddcutil-2.2.0/src/app_sysenv/query_sysenv_access.c0000644000175000001440000003411014634171455016050 /* @file query_sysenv_access.c * * Checks on the the existence of and access to /dev/i2c devices */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include #include #include "config.h" #include "util/file_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #ifdef ENABLE_UDEV #include "util/udev_i2c_util.h" #endif #include "base/linux_errno.h" /** \endcond */ #include "i2c/i2c_bus_core.h" #include "query_sysenv_access.h" /** Perform redundant checks as cross-verification */ bool redundant_i2c_device_identification_checks = false; // // Get list of /dev/i2c devices // // There are too many ways of doing this throughout the code. // Consolidate them here. (IN PROGRESS) // /** Gets a list of all /dev/i2c-n devices by screen-scraping the output * of "ls /dev/i2c*". * * @return Byte_Value_Array containing the valid bus numbers */ static Byte_Value_Array get_i2c_devices_by_ls() { Byte_Value_Array bva = bva_create(); int ival; // returns array of I2C bus numbers in string form, sorted in numeric order GPtrArray * busnums = execute_shell_cmd_collect("ls /dev/i2c* | cut -c 10- | sort -n"); if (!busnums) { rpt_vstring(1, "No I2C buses found"); goto bye; } if (busnums->len > 0) { bool isint = str_to_int(g_ptr_array_index(busnums,0), &ival, 10); if (!isint) { rpt_vstring(1, "Apparently no I2C buses"); goto bye; } } for (int ndx = 0; ndx < busnums->len; ndx++) { char * sval = g_ptr_array_index(busnums, ndx); bool isint = str_to_int(sval, &ival, 10); if (!isint) { rpt_vstring(1, "Parsing error. Invalid I2C bus number: %s", sval); } else { bva_append(bva, ival); // is_smbus_device_using_sysfs(ival); } } bye: if (busnums) g_ptr_array_free(busnums, true); return bva; } /** Consolidated function to identify I2C devices. * * \return #ByteValueArray of bus numbers for detected I2C devices */ Byte_Value_Array identify_i2c_devices() { Byte_Value_Array i2c_device_numbers_result = NULL; // result Byte_Value_Array bva1 = NULL; Byte_Value_Array bva2 = NULL; #ifdef ENABLE_UDEV Byte_Value_Array bva3 = NULL; Byte_Value_Array bva4 = NULL; #endif bva1 = get_i2c_devices_by_existence_test(/*include_ignorable_devices=*/ true); if (redundant_i2c_device_identification_checks) { // normally false, set true for testing bva2 = get_i2c_devices_by_ls(); #ifdef ENABLE_UDEV bva3 = get_i2c_device_numbers_using_udev(/* include_smbus= */ true); bva4 = get_i2c_device_numbers_using_udev_w_sysattr_name_filter(NULL); #endif assert(bva_sorted_eq(bva1,bva2)); #ifdef ENABLE_UDEV assert(bva_sorted_eq(bva1,bva3)); assert(bva_sorted_eq(bva1,bva4)); #endif } i2c_device_numbers_result = bva1; if (redundant_i2c_device_identification_checks) { bva_free(bva2); #ifdef ENABLE_UDEV bva_free(bva3); bva_free(bva4); #endif } // DBGMSG("Identified %d I2C devices", bva_length(bva1)); return i2c_device_numbers_result; } /** Reports the username and id of the logged on user. Saves the id and a * copy of the name in the #Env_Accumulator structure passed. * * \param accumuator collects user name and userid */ static void get_username(Env_Accumulator * accum) { uid_t uid = getuid(); struct passwd * pwd = getpwuid(uid); rpt_vstring(0,"Current user: %s (%u)", pwd->pw_name, uid); rpt_nl(); accum->cur_uname = g_strdup(pwd->pw_name); accum->cur_uid = uid; } /** Checks which /dev/i2c devices are readable and writable. * * \param accum accumulates environment information * * \remark * Sets the following fields in **Env_Accumulator**: * - cur_user_all_devi2c_rw * - cur_user_any_devi2c_rw * - dev.i2c_common_group_name * - any_dev_i2c_is_group_rw * - all_dev_i2c_is_group_rw */ static void check_dev_i2c_access(Env_Accumulator * accum) { bool debug = false; DBGMSF(debug, "Starting"); // bool all_i2c_rw = false; assert(accum->dev_i2c_device_numbers); // already set int busct = bva_length(accum->dev_i2c_device_numbers); #ifndef NDEBUG int busct0 = i2c_device_count(); // simple count, no side effects, consider replacing with local code assert(busct == busct0); #endif if (busct == 0 && !accum->dev_i2c_devices_required) { rpt_vstring(0,"WARNING: No /dev/i2c-* devices found"); } else { // all_i2c_rw = true; int busno; char fnbuf[20]; for (int ndx = 0; ndx < busct; ndx++) { busno = bva_get(accum->dev_i2c_device_numbers, ndx); snprintf(fnbuf, sizeof(fnbuf), "/dev/i2c-%d", busno); int rc; int errsv; DBGMSF(debug, "Calling access() for %s", fnbuf); rc = access(fnbuf, R_OK|W_OK); if (rc < 0) { errsv = errno; rpt_vstring(0,"Device %s is not readable and writable. Error = %s", fnbuf, linux_errno_desc(errsv) ); // all_i2c_rw = false; accum->cur_user_all_devi2c_rw = false; } else accum->cur_user_any_devi2c_rw = true; struct stat fs; rc = stat(fnbuf, &fs); if (rc < 0) { errsv = errno; rpt_vstring(0,"Error getting group information for device %s. Error = %s", fnbuf, linux_errno_desc(errsv) ); } else { bool cur_file_grp_rw = ( fs.st_mode & S_IRGRP ) && (fs.st_mode & S_IWGRP) ; struct group* grp; errno = 0; grp = getgrgid(fs.st_gid); if (!grp) { errsv = errno; rpt_vstring(0,"Error getting group information for group %d. Error = %s", fs.st_gid, linux_errno_desc(errsv) ); } else { char * gr_name = grp->gr_name; if (accum->dev_i2c_common_group_name) { if (!streq(accum->dev_i2c_common_group_name, gr_name)) { free(accum->dev_i2c_common_group_name); accum->dev_i2c_common_group_name = g_strdup("MIXED"); } } else accum->dev_i2c_common_group_name = g_strdup(gr_name); if (streq(gr_name, "i2c")) accum->any_dev_i2c_has_group_i2c = true; else accum->all_dev_i2c_has_group_i2c = false; DBGMSF(debug, "file=%s, st_gid=%d, gr_name=%s, cur_file_grp_rw=%s", fnbuf, fs.st_gid, gr_name, sbool(cur_file_grp_rw)); if (fs.st_gid != 0) { // root group is special case if (cur_file_grp_rw) accum->any_dev_i2c_is_group_rw = true; else accum->all_dev_i2c_is_group_rw = false; } } } } rpt_nl(); if (!accum->cur_user_all_devi2c_rw) { rpt_vstring( 0, "WARNING: Current user (%s) does not have RW access to all /dev/i2c-* devices.", accum->cur_uname); } else rpt_vstring(0,"Current user (%s) has RW access to all /dev/i2c-* devices.", // username); accum->cur_uname); } DBGMSF(debug, "Done"); } /** Checks for group i2c and whether the current user is a * member of the group. * * \param accum accumulates environment information * * \remark * Sets the following fields in **Env_Accumulator**: * group_i2c_checked * group_i2c_exists * cur_user_in_group_i2c */ static void check_group_i2c(Env_Accumulator * accum, bool verbose) { bool debug = false; DBGMSF(debug, "Starting. verbose=%s", sbool(verbose)); // verbose = true; if (verbose) { rpt_nl(); rpt_vstring(0,"Checking for group i2c..."); } accum->group_i2c_checked = true; accum->group_i2c_exists = false; // avoid special value in gid_i2c // gid_t gid_i2c; struct group * pgi2c = getgrnam("i2c"); if (pgi2c) { if (verbose) rpt_vstring(0," Group i2c exists"); accum->group_i2c_exists = true; // gid_i2c = pgi2c->gr_gid; // DBGMSG("getgrnam returned gid=%d for group i2c", gid_i2c); // DBGMSG("getgrnam() reports members for group i2c: %s", *pgi2c->gr_mem); int ndx=0; char * curname; while ( (curname = pgi2c->gr_mem[ndx]) ) { rtrim_in_place(curname); // DBGMSG("member_names[%d] = |%s|", ndx, curname); if (streq(curname, accum->cur_uname)) { accum->cur_user_in_group_i2c = true; } ndx++; } if (verbose) { if (accum->cur_user_in_group_i2c) { rpt_vstring(1,"Current user %s is a member of group i2c", accum->cur_uname); } else if (streq(accum->cur_uname, "root")) { rpt_vstring(1, "Current user is root, membership in group i2c not needed"); } else { rpt_vstring(1, "WARNING: Current user %s is NOT a member of group i2c", accum->cur_uname); } } } else { if (verbose) rpt_label(1,"Group i2c does not exist"); } #ifdef BAD // getgroups, getgrouplist returning nonsense else { uid_t uid = geteuid(); gid_t gid = getegid(); struct passwd * pw = getpwuid(uid); printf("Effective uid %d: %s\n", uid, pw->pw_name); char * uname = g_strdup(pw->pw_name); struct group * pguser = getgrgid(gid); printf("Effective gid %d: %s\n", gid, pguser->gr_name); if (group_member(gid_i2c)) { printf("User %s (%d) is a member of group i2c (%d)\n", uname, uid, gid_i2c); } else { printf("WARNING: User %s (%d) is a not member of group i2c (%d)\n", uname, uid, gid_i2c); } size_t supp_group_ct = getgroups(0,NULL); gid_t * glist = calloc(supp_group_ct, sizeof(gid_t)); int rc = getgroups(supp_group_ct, glist); int errsv = errno; DBGMSF(debug, "getgroups() returned %d", rc); if (rc < 0) { DBGMSF(debug, "getgroups() returned %d", rc); } else { DBGMSG("Found %d supplementary group ids", rc); int ndx; for (ndx=0; ndxdriver_list** already set * * \remark * Sets: * accum->group_i2c_exists * accum->cur_user_in_group_i2c * accum->cur_user_any_devi2c_rw * accum->cur_user_all_devi2c_rw */ void check_i2c_devices(Env_Accumulator * accum) { bool debug = false; DBGMSF(debug, "Starting"); get_username(accum); rpt_vstring(0,"Checking /dev/i2c-* devices..."); DDCA_Output_Level output_level = get_output_level(); rpt_nl(); rpt_multiline(0, "Devices /dev/i2c-* must exist and the logged on user must have read/write " "permission for those devices (or at least those devices associated ", "with monitors).", "", "Typically, this access is enabled by:", " - setting the group for /dev/i2c-* to i2c", " - setting group RW permissions for /dev/i2c-*", " - making the current user a member of group i2c", "", "Alternatively, this can be enabled by just giving everyone RW permission", "The following tests probe for these conditions.", NULL ); rpt_nl(); rpt_vstring(0,"Checking for /dev/i2c-* devices..."); execute_shell_cmd_rpt("ls -l /dev/i2c-*", 1); check_dev_i2c_access(accum); bool verbose = !accum->cur_user_all_devi2c_rw || output_level >= DDCA_OL_VERBOSE; check_group_i2c(accum, verbose); if (verbose) { check_udev_files(); } DBGMSF(debug, "Done"); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_base.c0000644000175000001440000003505014754153540015523 /** @file query_sysenv_base.c * * Base structures and functions for subsystem that diagnoses user configuration */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include "util/data_structures.h" #include "util/file_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "base/core.h" /** \endcond */ #include "query_sysenv_base.h" static char * known_video_driver_modules[] = { "amdgpu", "fbdev", "fglrx", "fturbo", "i915", "mgag200", "nvidia", "nouveau", "radeon", "vboxvideo", "vc4", NULL }; static char * prefix_matches[] = { "amdgpu", "drm", "i2c", "video", "vc4", "ddc", NULL }; static char * other_driver_modules[] = { "drm", // "eeprom", // not really interesting "i2c_algo_bit", "i2c_dev", "i2c_piix4", "ddcci", NULL }; // in some contexts, module names are accepted with either underscores or hyphens static char * other_driver_modules_alt[] = { "i2c-algo-bit", "i2c-dev", "i2c-piix4", NULL }; /** Returns the null terminated list of known video driver names */ char ** get_known_video_driver_module_names() { return known_video_driver_modules; } /** Returns the null terminated list of match prefixes */ char ** get_prefix_match_names() { return prefix_matches; } /** Returns the null terminated list of names of other drivers of interest */ char ** get_other_driver_module_names() { return other_driver_modules; } /** Returns a null terminated list of all driver strings of interest */ char ** get_all_driver_module_strings() { static char ** all_strings = NULL; if (!all_strings) { char ** all1 = ntsa_join(known_video_driver_modules, prefix_matches, false); char ** all2 = ntsa_join(all1, other_driver_modules, false); char ** all3 = ntsa_join(all2, other_driver_modules_alt, false); all_strings = all3; ntsa_free(all1, false); ntsa_free(all2, false); } return all_strings; } /** Reports the first line of a file, indented under a title. * Issues a message if unable to read the file. * * \param fn file name * \param title title message * \param depth logical indentation depth */ void sysenv_rpt_file_first_line(const char * fn, const char * title, int depth) { int d1 = depth+1; if (title) rpt_title(title, depth); else rpt_vstring(depth, "%s:", fn); char * s = file_get_first_line(fn, true /* verbose */); if (s) { rpt_title(s, d1); free(s); } else rpt_vstring(d1, "Unable to read %s", fn); } /** Reports the contents of a file. * * \param dir_name directory name * \param simple_fn simple file name * \param verbose if ***true***, issue message if error * \param depth logical indentation depth */ bool sysenv_show_one_file(const char * dir_name, const char * simple_fn, bool verbose, int depth) { bool result = false; char * fqfn = g_strdup_printf("%s%s%s", dir_name, (str_ends_with(dir_name, "/")) ? "" : "/", simple_fn); if (regular_file_exists(fqfn)) { rpt_vstring(depth, "%s:", fqfn); rpt_file_contents(fqfn, /*verbose=*/true, depth+1); result = true; } else if (verbose) rpt_vstring(depth, "File not found: %s", fqfn); free(fqfn); return result; } /** Reports the current time as both local time and UTC time, * and also the elapsed time in seconds since boot. * * \param title optional title * \param depth logical indentation depth */ void sysenv_rpt_current_time(const char * title, int depth) { int d = depth; if (title) { rpt_title(title, depth); d = depth+1; } char buf0[80]; time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime( &rawtime ); strftime(buf0, 80, "%F %H:%M:%S %Z", timeinfo); rpt_vstring(d, "Current time (local): %s", buf0); timeinfo = gmtime( &rawtime ); strftime(buf0, 80, "%F %H:%M:%S", timeinfo); rpt_vstring(d, "Current time (UTC): %s", buf0); struct sysinfo info; sysinfo(&info); rpt_vstring(d, "Seconds since boot: %ld", info.uptime); } /** Allocates and initializes a #Env_Accumulator data structure * * \return newly allocated struct */ Env_Accumulator * env_accumulator_new() { Env_Accumulator * accum = calloc(1, sizeof(Env_Accumulator)); memcpy(accum->marker, ENV_ACCUMULATOR_MARKER, 4); // Defaults that differ from 0 values set by calloc(): accum->dev_i2c_devices_required = true; // will be set false if any instance fails the test accum->cur_user_all_devi2c_rw = true; accum->all_dev_i2c_has_group_i2c = true; accum->all_dev_i2c_is_group_rw = true; return accum; } /** Frees the #Env_Accumulator data structure. * * \param accum pointer to data structure */ void env_accumulator_free(Env_Accumulator * accum) { if (accum) { free(accum->architecture); free(accum->distributor_id); free(accum->cur_uname); free(accum->dev_i2c_common_group_name); if (accum->dev_i2c_device_numbers) bva_free(accum->dev_i2c_device_numbers); if (accum->driver_list) driver_name_list_free(accum->driver_list); if (accum->sys_bus_i2c_device_numbers) bva_free(accum->sys_bus_i2c_device_numbers); free(accum); } } /*** Debugging report for the **Env_Accumulator** struct * * @param accum pointer to data structure * @param depth logical indentation depth */ void env_accumulator_report(Env_Accumulator * accum, int depth) { int d1 = depth+1; char * dev_i2c_device_numbers_string = ""; if (accum->dev_i2c_device_numbers) dev_i2c_device_numbers_string = bva_as_string(accum->dev_i2c_device_numbers, /*as_hex*/ false, " "); char * driver_names = ""; if (accum->driver_list) driver_names = driver_name_list_string(accum->driver_list); char * sys_bus_i2c_device_numbers_string = ""; if (accum->sys_bus_i2c_device_numbers) sys_bus_i2c_device_numbers_string = bva_as_string(accum->sys_bus_i2c_device_numbers, /*as_hex*/ false, " "); rpt_label(depth, "Env_Accumulator:"); rpt_vstring(d1, "%-30s %s", "architecture:", (accum->architecture) ? accum->architecture : ""); rpt_vstring(d1, "%-30s %s", "distributor_id", (accum->distributor_id) ? accum->distributor_id : ""); rpt_vstring(d1, "%-30s %s", "Drivers detected:", driver_names); rpt_vstring(d1, "%-30s %s", "/dev/i2c device numbers:", dev_i2c_device_numbers_string); rpt_vstring(d1, "%-30s %s", "sysfs_i2c_devices_exist:", sbool(accum->sysfs_i2c_devices_exist)); rpt_vstring(d1, "%-30s %s", "/sys/bus/i2c device numbers:", sys_bus_i2c_device_numbers_string); rpt_vstring(d1, "%-30s %s", "dev_i2c_devices_required:", sbool(accum->dev_i2c_devices_required)); rpt_vstring(d1, "%-30s %s", "module_i2c_dev_needed:", sbool(accum->module_i2c_dev_needed)); rpt_vstring(d1, "%-30s %s", "module_i2c_dev_builtin:", sbool(accum->module_i2c_dev_builtin)); rpt_vstring(d1, "%-30s %s", "loadable_i2c_dev_exists:", sbool(accum->loadable_i2c_dev_exists)); rpt_vstring(d1, "%-30s %s", "i2c_dev_loaded_or_builtin:", sbool(accum->i2c_dev_loaded_or_builtin)); rpt_vstring(d1, "%-30s %s", "group_i2c_checked:", sbool(accum->group_i2c_checked)); rpt_vstring(d1, "%-30s %s", "group_i2c_exists:", sbool(accum->group_i2c_exists)); rpt_vstring(d1, "%-30s %s", "dev_i2c_common_group_name:", accum->dev_i2c_common_group_name); rpt_vstring(d1, "%-30s %s", "all_dev_i2c_has_group_i2c:", sbool(accum->all_dev_i2c_has_group_i2c)); rpt_vstring(d1, "%-30s %s", "any_dev_i2c_has_group_i2c:", sbool(accum->any_dev_i2c_has_group_i2c)); rpt_vstring(d1, "%-30s %s", "all_dev_i2c_is_group_rw:", sbool(accum->all_dev_i2c_is_group_rw)); rpt_vstring(d1, "%-30s %s", "any_dev_i2c_is_group_rw:", sbool(accum->any_dev_i2c_is_group_rw)); rpt_vstring(d1, "%-30s %s", "cur_uname:", accum->cur_uname); rpt_vstring(d1, "%-30s %d", "cur_uid:", accum->cur_uid); rpt_vstring(d1, "%-30s %s", "cur_user_in_group_i2c:", sbool(accum->cur_user_in_group_i2c)); rpt_vstring(d1, "%-30s %s", "cur_user_any_devi2c_rw:", sbool(accum->cur_user_any_devi2c_rw)); rpt_vstring(d1, "%-30s %s", "cur_user_all_devi2c_rw:", sbool(accum->cur_user_all_devi2c_rw)); if (accum->dev_i2c_device_numbers) free(dev_i2c_device_numbers_string); if (accum->sys_bus_i2c_device_numbers) free(sys_bus_i2c_device_numbers_string); if (accum->driver_list) free(driver_names); } // Functions to query and free the linked list of detected driver names. // The list is created by executing function query_card_and_driver_using_sysfs(), // which is grouped with the sysfs functions. /** Searches the driver name list for a specified name * * \param head list head * \param driver_name name of driver to search for * \return pointer to node containing driver, NULL if not found */ Driver_Name_Node * driver_name_list_find_exact( Driver_Name_Node * head, const char * driver_name) { Driver_Name_Node * cur_node = head; while (cur_node && !streq(cur_node->driver_name, driver_name)) cur_node = cur_node->next; return cur_node; } /** Checks if any driver name in the list of detected drivers starts with * the specified string. * * \param driver list head of linked list of driver names * \parar driver_prefix driver name prefix * \return pointer to first node satisfying the prefix match, NULL if none */ Driver_Name_Node * driver_name_list_find_prefix( Driver_Name_Node * head, const char * driver_prefix) { Driver_Name_Node * curnode = head; while (curnode && !str_starts_with(curnode->driver_name, driver_prefix) ) curnode = curnode->next; // DBGMSG("driver_prefix=%s, returning %p", driver_prefix, curnode); return curnode; } /** Adds a driver name to the head of the linked list of driver names. * * If the specified name is already in the list it is not added again. * * \param headptr pointer to address of head of the list * \param driver_name name to add */ void driver_name_list_add(Driver_Name_Node ** headptr, const char * driver_name) { // printf("(%s) Adding driver |%s|\n", __func__, driver_name); if (!driver_name_list_find_exact(*headptr, driver_name)) { Driver_Name_Node * newnode = calloc(1, sizeof(Driver_Name_Node)); newnode->driver_name = g_strdup(driver_name); newnode->next = *headptr; *headptr = newnode; } } /** Checks the list of detected drivers to see if AMD's proprietary * driver fglrx is the only driver. * * \param driver_list linked list of driver names * \return true if fglrx is the only driver, false otherwise */ bool only_fglrx(struct driver_name_node * driver_list) { int driverct = 0; bool fglrx_seen = false; struct driver_name_node * curnode = driver_list; while (curnode) { driverct++; if (str_starts_with(curnode->driver_name, "fglrx")) fglrx_seen = true; curnode = curnode->next; } bool result = (driverct == 1 && fglrx_seen); // DBGMSG("driverct = %d, returning %d", driverct, result); return result; } /** Checks the list of detected drivers to see if the proprietary * AMD and Nvidia drivers are the only ones. * * \param driver list linked list of driver names * \return true if both nvidia and fglrx are present and there are no other drivers, * false otherwise */ bool only_nvidia_or_fglrx(struct driver_name_node * driver_list) { int driverct = 0; bool other_driver_seen = false; struct driver_name_node * curnode = driver_list; while (curnode) { driverct++; if (!str_starts_with(curnode->driver_name, "fglrx") && !streq(curnode->driver_name, "nvidia") ) { other_driver_seen = true; } curnode = curnode->next; } bool result = (!other_driver_seen && driverct > 0); // DBGMSG("driverct = %d, returning %d", driverct, result); return result; } /** Frees the driver name list * * \param driver_list pointer to head of linked list of driver names */ void driver_name_list_free(struct driver_name_node * driver_list) { // Free the driver list struct driver_name_node * cur_node = driver_list; while (cur_node) { free(cur_node->driver_name); struct driver_name_node * next_node = cur_node->next; free(cur_node); cur_node = next_node; } } /** Returns a comma delimited list of all the driver names in a * driver name list. * * \param head pointer to head of list */ char * driver_name_list_string(Driver_Name_Node * head) { int reqd_sz = 1; // for trailing \0 Driver_Name_Node * cur = head; while (cur) { // printf("(%s) driver_name: |%s|\n", __func__, cur->driver_name); reqd_sz += strlen(cur->driver_name); if (cur != head) reqd_sz += 2; // for ", " cur = cur->next; } // printf("(%s) reqd_sz = %d\n", __func__, reqd_sz); char * result = malloc(reqd_sz); result[0] = '\0'; cur = head; while(cur) { if (cur != head) strcat(result, ", "); strcat(result, cur->driver_name); cur = cur->next; } assert(strlen(result) == reqd_sz-1); // printf("(%s) result: |%s|\n", __func__, result); return result; } /** Given a path whose final segment is of the form "i2c-n", * returns the bus number. * * \param path fully qualified or simple path name * \return I2C bus number, -1 if cannot be extracted */ int i2c_path_to_busno(const char * path) { bool debug = false; int busno = -1; if (path) { char * path2 = g_strdup(path); // for const-ness char * lastslash = strrchr(path2, '/'); char * basename = (lastslash) ? lastslash+1 : path2; // char * basename = basename(path); if (basename) { if (str_starts_with(basename, "i2c-")) { int ival = 0; if (str_to_int(basename+4, &ival, 10) ) busno = ival; } } free(path2); } DBGMSF(debug, "path=%s, returning: %d", path, busno); return busno; } #ifdef SYSENV_TEST_IDENTICAL_EDIDS // For testing situation where 2 displays have the same EDID, e.g. LG displays Byte * first_edid = NULL; #endif bool sysfs_quick_test = false; ddcutil-2.2.0/src/app_sysenv/query_sysenv_dmidecode.c0000644000175000001440000000704214441414365016524 /** @file query_sysenv_dmidecode.c * * dmidecode report for the environment command */ // Copyright (C) 2016-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include "util/data_structures.h" #include "util/report_util.h" #include "util/sysfs_util.h" #include "base/core.h" /** \endcond */ #include "query_sysenv_base.h" // // dmidecode related functions // // from dmidecode.c static const char *dmi_chassis_type(Byte code) { /* 7.4.1 */ static const char *type[] = { "Other", /* 0x01 */ "Unknown", "Desktop", "Low Profile Desktop", "Pizza Box", "Mini Tower", "Tower", "Portable", "Laptop", "Notebook", "Hand Held", "Docking Station", "All In One", "Sub Notebook", "Space-saving", "Lunch Box", "Main Server Chassis", /* CIM_Chassis.ChassisPackageType says "Main System Chassis" */ "Expansion Chassis", "Sub Chassis", "Bus Expansion Chassis", "Peripheral Chassis", "RAID Chassis", "Rack Mount Chassis", "Sealed-case PC", "Multi-system", "CompactPCI", "AdvancedTCA", "Blade", "Blade Enclosing", "Tablet", "Convertible", "Detachable", "IoT Gateway", "Embedded PC", "Mini PC", "Stick PC" /* 0x24 */ }; code &= 0x7F; /* bits 6:0 are chassis type, 7th bit is the lock bit */ if (code >= 0x01 && code <= 0x24) return type[code - 0x01]; return NULL; } /** Reports DMI information for the system. */ void query_dmidecode() { // Note: The alternative of calling execute_shell_cmd_collect() with the following // command fails if executing from a non-privileged account, which lacks permissions // for /dev/mem or /sys/firmware/dmi/tables/smbios_entry_point // char * cmd = "dmidecode | grep \"['Base Board Info'|'Chassis Info'|'System Info']\" -A2"; // GPtrArray * lines = execute_shell_cmd_collect(cmd); char * sysdir = "/sys/class/dmi/id"; rpt_title("DMI Information from /sys/class/dmi/id:", 0); char * dv = "(Unavailable)"; char buf[100]; int bufsz = 100; // verbose rpt_vstring(1, "%-25s %s","Motherboard vendor:", read_sysfs_attr_w_default_r(sysdir, "board_vendor", dv, buf, bufsz, false)); rpt_vstring(1, "%-25s %s","Motherboard product name:", read_sysfs_attr_w_default_r(sysdir, "board_name", dv, buf, bufsz, false)); rpt_vstring(1, "%-25s %s","System vendor:", read_sysfs_attr_w_default_r(sysdir, "sys_vendor", dv, buf, bufsz, false)); rpt_vstring(1, "%-25s %s","System product name:", read_sysfs_attr_w_default_r(sysdir, "product_name", dv, buf, bufsz, false)); rpt_vstring(1, "%-25s %s","Chassis vendor:", read_sysfs_attr_w_default_r(sysdir, "chassis_vendor",dv, buf, bufsz, false)); char * chassis_type_s = read_sysfs_attr(sysdir, "chassis_type", /*verbose=*/ true); char * chassis_desc = dv; char workbuf[100]; if (chassis_type_s) { int chassis_type_i = atoi(chassis_type_s); // TODO: use something safer? const char * chassis_type_name = dmi_chassis_type(chassis_type_i); if (chassis_type_name) snprintf(workbuf, 100, "%s - %s", chassis_type_s, chassis_type_name); else snprintf(workbuf, 100, "%s - Unrecognized value", chassis_type_s); chassis_desc = workbuf; free(chassis_type_s); } rpt_vstring(1, "%-25s %s", "Chassis type:", chassis_desc); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_i2c.c0000644000175000001440000004067614754153540015300 /** @file query_sysenv_i2c.c * * Check I2C devices using directly coded I2C calls */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include "util/edid.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "base/parms.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/linux_errno.h" #include "base/status_code_mgt.h" /** \endcond */ #include "sysfs/sysfs_base.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_edid.h" #include "i2c/i2c_execute.h" #include "query_sysenv_base.h" #include "query_sysenv_sysfs.h" #include "query_sysenv_xref.h" #include "query_sysenv_i2c.h" // Auxiliary function for raw_scan_i2c_devices() static bool is_i2c_device_rw(int busno) { bool debug = false; DBGMSF(debug, "Starting. busno=%d", busno); bool result = true; char fnbuf[PATH_MAX]; snprintf(fnbuf, sizeof(fnbuf), "/dev/i2c-%d", busno); int rc; int errsv; DBGMSF(debug, "Calling access() for %s", fnbuf); rc = access(fnbuf, R_OK|W_OK); if (rc < 0) { errsv = errno; rpt_vstring(0,"Device %s is not readable and writable. Error = %s", fnbuf, linux_errno_desc(errsv) ); result = false; } DBGMSF(debug, "Returning: %s", sbool(result)); return result; } // Auxiliary function for raw_scan_i2c_devices() // adapted from ddc_vcp_tests static Public_Status_Code try_single_getvcp_call( int fh, unsigned char vcp_feature_code, // bool use_smbus, int depth) { bool debug = false; // rpt_nl(); // DBGMSF(true, "Starting. vcp_feature_code=0x%02x. use_smbus=%s", vcp_feature_code, sbool(use_smbus) ); rpt_vstring(depth, "%s: vcp_feature_code=0x%02x", __func__, vcp_feature_code ); int ndx; Status_Errno rc = 0; // extra sleep time does not help P2411 #ifdef ALT // resets monitor state? unsigned char zeroByte = 0x00; // 0x00; rc = write(fh, &zeroByte, 1); if (rc < 0) { rpt_vstring(0,"(%s) Bus reset failed. rc=%d, errno=%d. ", __func__, rc, errno ); return -1; } #endif // without usleep() or 0 byte write, read() sometimes returns all 0 on P2411H usleep(50000); unsigned char ddc_cmd_bytes[] = { 0x6e, // address 0x37, shifted left 1 bit 0x51, // source address 0x02 | 0x80, // number of DDC data bytes, with high bit set 0x01, // DDC Get Feature Command vcp_feature_code, // 0x00, // checksum, to be set }; // calculate checksum by XORing bytes 0..4 ddc_cmd_bytes[5] = ddc_cmd_bytes[0]; for (ndx=1; ndx < 5; ndx++) ddc_cmd_bytes[5] ^= ddc_cmd_bytes[ndx]; // calculate checksum int writect = sizeof(ddc_cmd_bytes)-1; rpt_vstring(depth, "Sending Get VCP Feature Command request packet: %s", hexstring_t(ddc_cmd_bytes+1, writect)); rc = i2c_ioctl_writer(fh, 0x37, writect, ddc_cmd_bytes+1); if (rc < 0) { int errsv = errno; DBGMSF(debug, "write failed, errno=%s", linux_errno_desc(errsv)); rc = -errsv; goto bye; } usleep(50000); unsigned char ddc_response_bytes[12]; int readct = sizeof(ddc_response_bytes)-1; rpt_vstring(depth, "Reading Get Feature Reply response packet"); rc = i2c_ioctl_reader(fh, 0x37, false, readct, ddc_response_bytes+1); if (rc < 0) { rc = -errno; DBGMSF(debug, "read failed, errno=%s", linux_errno_desc(-rc)); goto bye; } rpt_vstring(depth, "read returned: %s", hexstring_t(ddc_response_bytes+1, readct) ); if ( all_bytes_zero( ddc_response_bytes+1, readct) ) { DBGMSF(debug, "All bytes zero"); rc = DDCRC_READ_ALL_ZERO; goto bye; } int ddc_data_length = ddc_response_bytes[2] & 0x7f; // some monitors return a DDC null response to indicate an invalid request: if (ddc_response_bytes[1] == 0x6e && ddc_data_length == 0 && ddc_response_bytes[3] == 0xbe) // 0xbe == checksum { DBGMSF(debug, "Received DDC null response"); rc = DDCRC_NULL_RESPONSE; goto bye; } if (ddc_response_bytes[1] != 0x6e) { // assert(ddc_response_bytes[1] == 0x6e); DBGMSF(debug, "Invalid address byte in response, expected 06e, actual 0x%02x", ddc_response_bytes[1] ); rc = DDCRC_DDC_DATA; // was DDCRC_INVALID_DATA; goto bye; } if (ddc_data_length != 8) { DBGMSF(debug, "Invalid query VCP response length: %d", ddc_data_length ); rc = DDCRC_DDC_DATA; // was DDCRC_BAD_BYTECT goto bye; } if (ddc_response_bytes[3] != 0x02) { // get feature response DBGMSF(debug, "Expected 0x02 in feature response field, actual value 0x%02x", ddc_response_bytes[3] ); rc = DDCRC_DDC_DATA; // was DDCRC_INVALID_DATA; goto bye; } ddc_response_bytes[0] = 0x50; // for calculating DDC checksum // checksum0 = xor_bytes(ddc_response_bytes, sizeof(ddc_response_bytes)-1); unsigned char calculated_checksum = ddc_response_bytes[0]; for (ndx=1; ndx < 11; ndx++) calculated_checksum ^= ddc_response_bytes[ndx]; // printf("(%s) checksum0=0x%02x, calculated_checksum=0x%02x\n", __func__, checksum0, calculated_checksum ); if (ddc_response_bytes[11] != calculated_checksum) { DBGMSF(debug, "Unexpected checksum. actual=0x%02x, calculated=0x%02x", ddc_response_bytes[11], calculated_checksum ); rc = DDCRC_DDC_DATA; // was DDCRC_CHECKSUM; goto bye; } if (ddc_response_bytes[4] == 0x00) { // valid VCP code // The interpretation for most VCP codes: int max_val = (ddc_response_bytes[7] << 8) + ddc_response_bytes[8]; int cur_val = (ddc_response_bytes[9] << 8) + ddc_response_bytes[10]; DBGMSF(debug, "cur_val = %d, max_val = %d", cur_val, max_val ); rc = 0; } else if (ddc_response_bytes[4] == 0x01) { // unsupported VCP code DBGMSF(debug, "Unsupported VCP code: 0x%02x", vcp_feature_code); rc = DDCRC_REPORTED_UNSUPPORTED; } else { DBGMSF(debug, "Unexpected value in supported VCP code field: 0x%02x ", ddc_response_bytes[4] ); rc = DDCRC_DDC_DATA; // was DDCRC_INVALID_DATA; } bye: DBGMSF(debug, "Returning: %s", psc_desc(rc)); return rc; } static bool simple_ioctl_read_edid( int busno, int read_size, bool write_before_read, int depth) { bool debug = false; DBGMSF(debug, "Starting. busno=%d, read_size=%d, write_before_read=%s", busno, read_size, sbool(write_before_read)); assert(read_size == 128 || read_size == 256); rpt_nl(); rpt_vstring(depth, "Attempting simple %d byte EDID read of /dev/i2c-%d, %s initial write", read_size, busno, (write_before_read) ? "WITH" : "WITHOUT" ); int rc = 0; char i2cdev[20]; // Byte edid_buf[256]; // valgrind reports uninitialized value error, so dynamically allocate buffer Byte * edid_buf = calloc(1, 256); snprintf(i2cdev, 20, "/dev/i2c-%d", busno); bool ok = false; int fd = open(i2cdev, O_RDWR ); if (fd < 0) { rpt_vstring(depth, "Open failed for %s, errno=%s", i2cdev, linux_errno_desc(errno)); } else { if (write_before_read) { edid_buf[0] = 0x00; rc = i2c_ioctl_writer(fd, 0x50, 1, edid_buf); if (rc < 0) { rpt_vstring(depth, "write of 1 byte failed, errno = %s", linux_errno_desc(errno)); rpt_label(depth, "Continuing"); } } DBGMSF(debug, "Calling i2c_ioctl_reader(), read_bytewise=false, read_size=%d, edid_buf=%p", read_size, edid_buf); rc = i2c_ioctl_reader(fd, 0x50, false, read_size, edid_buf); if (rc < 0) { rpt_vstring(depth,"read failed. errno = %s", linux_errno_desc(errno)); } else { rpt_hex_dump(edid_buf, read_size, depth+1); ok = true; } close(fd); } free(edid_buf); DBGMSF(debug, "Returning: %s", sbool(ok)); return ok; } void test_edid_read_variants(Env_Accumulator * accum) { bool debug = false; DBGMSF(debug, "Starting"); int depth = 0; int d1 = depth+1; int d2 = depth+2; rpt_nl(); rpt_title("Testing EDID read alternatives...",depth); sysenv_rpt_current_time(NULL, d1); int busct = 0; for (int busno=0; busno < I2C_BUS_MAX; busno++) { if (i2c_device_exists(busno)) { busct++; rpt_nl(); rpt_vstring(d1, "Examining device /dev/i2c-%d...", busno); if (sysfs_is_ignorable_i2c_device(busno)) { rpt_vstring(d2, "Device /dev/i2c-%d is a SMBus or other ignorable device. Skipping.", busno); continue; } if (!is_i2c_device_rw(busno)) // issues message if not RW continue; rpt_label(d2, "Tests using ioctl write and read..."); bool ok = false; rpt_label(d2, "Without write before read..."); ok = simple_ioctl_read_edid(busno, 128, false, d2); if (!ok) simple_ioctl_read_edid(busno, 128, false, d2); simple_ioctl_read_edid(busno, 256, false, d2); rpt_nl(); rpt_label(d2, "Retrying with write before read..."); ok = simple_ioctl_read_edid(busno, 128, true, d2); if (!ok) simple_ioctl_read_edid(busno, 128, true, d2); simple_ioctl_read_edid(busno, 256, true, d2); rpt_nl(); } } } /** Checks each I2C device. * * This function largely uses direct coding to probe the I2C buses. * Allows for trying to read x37 even if X50 fails, and provides clearer * diagnostic messages than relying entirely on the normal code path. * * As part of its scan, this function adds an entry to the display cross * reference table for each I2C device reporting an EDID. * It must be called before any other functions accessing the table, since * they will search by I2C bus number. * * \param accum accumulates sysenv query information */ void raw_scan_i2c_devices(Env_Accumulator * accum) { bool debug = false; DBGMSF(debug, "Starting"); int depth = 0; int d1 = depth+1; int d2 = depth+2; Parsed_Edid * edid = NULL; rpt_nl(); rpt_title("Performing alternative scans of I2C devices using local sysenv functions...",depth); sysenv_rpt_current_time(NULL, d1); Buffer * buf0 = buffer_new(1000, __func__); int busct = 0; Public_Status_Code psc; Status_Errno rc = 0; bool saved_i2c_force_slave_addr_flag = i2c_forceable_slave_addr_flag; for (int busno=0; busno < I2C_BUS_MAX; busno++) { if (i2c_device_exists(busno)) { busct++; rpt_nl(); rpt_vstring(d1, "Examining device /dev/i2c-%d...", busno); if (sysfs_is_ignorable_i2c_device(busno)) { rpt_vstring(d2, "Device /dev/i2c-%d is a SMBus or other ignorable device. Skipping.", busno); continue; } if (!is_i2c_device_rw(busno)) // issues message if not RW continue; rpt_label(d2, "Obtain and interpret EDID using normal i2c functions..."); rpt_nl(); int fd = -1; Error_Info * erec = i2c_open_bus(busno, CALLOPT_ERR_MSG, &fd); #ifdef ALT_LOCK_REC char filename[80]; g_snprintf(filename, 80, "i2c-%d", busno); Error_Info * erec = i2c_open_bus_basic(filename, CALLOPT_ERR_MSG, &fd); #endif if (erec) { ERRINFO_FREE(erec); continue; } unsigned long functionality = i2c_get_functionality_flags_by_fd(fd); // DBGMSG("i2c_get_functionality_flags_by_fd() returned %ul", functionality); i2c_report_functionality_flags(functionality, 90, d2); int maxtries = 3; for (int tryctr = 0; tryctr < maxtries; tryctr++) { // Base_Status_Errno rc = i2c_set_addr(fd, 0x50, CALLOPT_ERR_MSG); // TODO save force slave addr setting, set it for duration of call - do it outside loop rpt_vstring(d2, "Reading EDID using get_raw_edid_by_fd()..."); psc = i2c_get_raw_edid_by_fd(fd, buf0); if (psc != 0) { rpt_vstring(d2, "Unable to read EDID, psc=%s", psc_desc(psc)); tryctr = 999; // retries have already happened in i2c_get_raw_edid_by_fd() } else { rpt_label(d2, "Raw EDID:"); rpt_hex_dump(buf0->bytes, buf0->len, d2); edid = create_parsed_edid2(buf0->bytes, "I2C"); if (edid) { report_parsed_edid_base( edid, true, // verbose false, // show_edid d2); rpt_vstring(d2, "Attempt %d to read and parse EDID succeeded", tryctr+1); Byte * edidbytes = buf0->bytes; // Device_Id_Xref * xref = device_xref_get(buf0->bytes); // xref->i2c_busno = busno; device_xref_new_with_busno(busno, edidbytes); tryctr = 999; } else { rpt_vstring(d2, "Unable to parse EDID"); if (tryctr < maxtries) rpt_label(d2, "Retrying read EDID"); } } #ifdef SYSENV_TEST_IDENTICAL_EDIDS if (!first_edid) { DBGMSG("Setting first_edid"); first_edid = calloc(1,128); memcpy(first_edid, buf0->bytes, 128); } else { DBGMSG("Forcing duplicate EDID"); edidbytes = first_edid; } #endif } rpt_nl(); rpt_vstring(d2, "Trying simple VCP read of feature 0x10..."); if (rc == 0) { int maxtries = 3; psc = -1; for (int tryctr=0; tryctr // SPDX-License-Identifier: GPL-2.0-or-later /** cond */ #include #include #include #include #include #include #include #include #include #include #include "util/data_structures.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "base/core.h" #include "base/dsa2.h" #include "base/status_code_mgt.h" /** endcond */ #include "ddc/ddc_serialize.h" #include "vcp/persistent_capabilities.h" #include "query_sysenv_base.h" #include "query_sysenv_logs.h" static bool probe_log( char * log_fn, char ** filter_terms, bool ignore_case, int limit, int depth) { bool debug = false; assert(log_fn); DBGMSF(debug, "Starting. log_fn=%s, filter_terms=%p, ignore_case=%s, limit=%d", log_fn, filter_terms, sbool(ignore_case), limit); bool file_found = false; int rc = 0; if ( !regular_file_exists(log_fn) ) { rpt_vstring(depth, "File not found: %s", log_fn); goto bye; } if ( access(log_fn, R_OK) < 0 ) { rpt_vstring(depth, "File not readable: %s", log_fn); goto bye; } rpt_vstring(depth, "Scanning file: %s", log_fn); // char shell_cmd[PATH_MAX * 2 + 50]; bool bigfile = false; struct stat st; // Coverity complains if return code not checked. rc = stat(log_fn, &st); if (rc != 0) { DBGMSG("Error executing stat(), errno = %d", errno); DBGMSG("Assuming file %s is huge", log_fn); bigfile = true; } else if (st.st_size > 1000000) { if (debug) { uint64_t sz = st.st_size; DBGMSG( "File %s is huge. Size = %" PRIu64 ". ", log_fn, sz); } bigfile = true; } if (limit < 0) { rpt_vstring(depth, "Limiting output to last %d relevant lines...", -limit); } else if (limit > 0) { rpt_vstring(depth, "Limiting output to first %d relevant lines...", limit); } GPtrArray * found_lines = NULL; if (bigfile && limit <= 0) { int maxlines = 50000; f0printf(stderr, "File %s is huge. Examining only last %d lines\n", log_fn, maxlines); rc = file_get_last_lines(log_fn, maxlines, &found_lines, /*verbose*/ true); if (rc < 0) { DBGMSG("Error calling file_get_last_lines(), rc = %d", rc); goto bye; } // for (int ndx = 0; ndx < found_lines->len; ndx++) { // DBGMSG("Found line: %s", g_ptr_array_index(found_lines,ndx)); // } DBGMSF(debug, "file_get_last_lines() returned %d", rc); DBGMSF(debug, "before filter, found_lines->len = %d", found_lines->len); // filter_and_limit_g_ptr_array( // found_lines, filter_terms, ignore_case, limit, /* free_strings= */ true); filter_and_limit_g_ptr_array2( found_lines, filter_terms, ignore_case, limit); DBGMSF(debug, "after filter, found_lines->len = %d", found_lines->len); } else { found_lines = g_ptr_array_new_full(1000, g_free); rc = read_file_with_filter(found_lines, log_fn, filter_terms, ignore_case, limit, false); } if (rc < 0) { f0printf(stderr, "Error reading file: %s\n", psc_desc(rc)); } else if (rc == 0) { // rc >0 is the original number of lines rpt_title("Empty file", depth); file_found = true; } else if (found_lines->len == 0) { rpt_title("No lines found after filtering", depth); file_found = true; } else { for (int ndx = 0; ndx < found_lines->len; ndx++) { rpt_title(g_ptr_array_index(found_lines, ndx), depth+1); } file_found = true; } g_ptr_array_set_free_func(found_lines, g_free); g_ptr_array_free(found_lines, true); bye: DBGMSF(debug, "rc=%d, file_found=%s", rc, sbool(file_found)); rpt_nl(); return file_found; } /** Issue a command and report the output to the terminal. * * @param cmd command to issue * @param filter_terms if non-null, use these terms to filter the output * @param ignore_case ignore case when filtering * @param limit report at most this number of lines * @param limit if 0, return all lines that pass filter terms * if > 0, return at most the first #limit lines that satisfy the filter terms * if < 0, return at most the last #limit lines that satisfy the filter terms * @param depth logical indentation depth of output * @return true if at least 1 line was output, false if not */ static bool probe_cmd( char * cmd, char ** filter_terms, bool ignore_case, int limit, int depth) { bool debug = false; assert(cmd); DBGMSF(debug, "Starting. cmd=%s, filter_terms=%p, ignore_case=%s, limit=%d", cmd, filter_terms, sbool(ignore_case), limit); rpt_vstring(depth, "Executing command: %s", cmd); if (limit < 0) { rpt_vstring(depth, "Limiting output to last %d relevant lines...", -limit); } else if (limit > 0) { rpt_vstring(depth, "Limiting output to first %d relevant lines...", limit); } GPtrArray * filtered_lines = NULL; int rc = execute_cmd_collect_with_filter(cmd, filter_terms, ignore_case, limit, &filtered_lines); if (rc < 0) { f0printf(stderr, "Error executing command: %s\n", psc_desc(rc)); } else if (rc == 0) { // rc >0 is the original number of lines rpt_title("No output", depth); } else if (filtered_lines->len == 0) { rpt_title("No lines found after filtering", depth); } else { for (int ndx = 0; ndx < filtered_lines->len; ndx++) { rpt_title(g_ptr_array_index(filtered_lines, ndx), depth+1); } } if (filtered_lines) { g_ptr_array_set_free_func(filtered_lines, g_free); g_ptr_array_free(filtered_lines, true); } bool result = (rc >= 0); DBGMSF(debug, "rc=%d, returning %s", rc, sbool(result)); rpt_nl(); return result; } /** Scans log files for lines of interest. * * Depending on operating environment, some subset of * the following files and command output: * - dmesg * - journalctl * - /var/log/daemon.log * - /var/log/kern.log * - /var/log/messages * - /var/log/syslog * - /var/log/Xorg.0.log * * \param accum collected environment information */ void probe_logs(Env_Accumulator * accum) { // TODO: Function needs major cleanup int depth = 0; int d1 = depth+1; int d2 = depth+2; // DBGMSG("Starting"); // debug_output_dest(); rpt_nl(); rpt_title("Examining system logs...", depth); sysenv_rpt_current_time("Current timestamps:", depth); // TODO: Pick simpler data structures. Is Value_Name_Title_Table worth it? // 1 suffixes to not conflict with token in syslog.h const Byte LOG_XORG = 0x80; const Byte LOG_DAEMON1 = 0x40; const Byte LOG_SYSLOG1 = 0x20; const Byte LOG_KERN1 = 0x10; const Byte LOG_JOURNALCTL = 0x08; const Byte LOG_MESSAGES = 0x04; const Byte LOG_DMESG = 0x02; Value_Name_Title_Table log_table = { VNT(LOG_DMESG, "dmesg" ), VNT(LOG_JOURNALCTL, "journalctl" ), VNT(LOG_DAEMON1, "/var/log/daemon.log" ), VNT(LOG_KERN1, "/var/log/kern.log" ), VNT(LOG_MESSAGES, "/var/log/messages" ), VNT(LOG_SYSLOG1, "/var/log/syslog" ), VNT(LOG_XORG, "/var/log/Xorg.0.log"), VNT_END }; bool log_xorg_found = false; bool log_daemon_found = false; // Raspbian bool log_syslog_found = false; // Ubuntu, Raspbian bool log_kern_found = false; // Raspbian //bool log_journalctl_found = false; // Debian, Raspbian bool log_messages_found = false; // Raspbian bool log_dmesg_found = false; Byte logs_checked = 0x00; Byte logs_found = 0x00; #ifdef NO // Problem: dmesg can be filled w i2c errors from i2cdetect trying to // read an SMBus device // Disable prefix_matches until filter out SMBUS devices p = prefix_matches; #endif char * addl_matches[] = { "drm", "video", "eeprom", "i2c_", // was i2c_ NULL }; Null_Terminated_String_Array drivers_plus_addl_matches = ntsa_join(get_known_video_driver_module_names(), addl_matches, /*dup*/ false); // *** dmesg *** rpt_nl(); // first few lines of dmesg are lost. turning on any sort of debugging causes // them to reappear. apparently a NL in the stream does the trick. why? // it's a heisenbug. Just use the more verbose journalctl output logs_checked |= LOG_DMESG; rpt_title("Scanning dmesg output for I2C related entries...", depth+1); log_dmesg_found = probe_cmd( "dmesg", drivers_plus_addl_matches, true, // ignore_case 0, // no limit depth+1); if (log_dmesg_found) logs_found |= LOG_DMESG; // *** journalctl *** logs_checked |= LOG_JOURNALCTL; #ifdef ALT // if don't use this version, don't need to link with libsystemd DBGMSG("Using get_current_boot_messages..."); rpt_title("Checking journalctl for I2C related entries...", depth+1); GPtrArray * journalctl_msgs = get_current_boot_messages(drivers_plus_addl_matches, /* ignore case */true, 0); if (journalctl_msgs) { // log_journalctl_found = true; logs_found |= LOG_JOURNALCTL; for (int ndx = 0; ndx < journalctl_msgs->len; ndx++) { rpt_vstring(depth+2, "%s", g_ptr_array_index(journalctl_msgs, ndx)); } } rpt_nl(); #endif // has a few more lines from nvidia-persistence, lines have timestamp, hostname, and subsystem rpt_title("Scanning journalctl output for I2C related entries...", depth+1); log_dmesg_found = probe_cmd("journalctl --no-pager --boot", drivers_plus_addl_matches, /*ignore_case*/ true, 0, depth+1); if (log_dmesg_found) logs_found |= LOG_DMESG; rpt_nl(); // *** Xorg.0.log *** char * xorg_terms[] = { // "[Ll]oadModule:", // matches LoadModule, UnloadModule "LoadModule:", // matches LoadModule, UnloadModule // "[Ll]oading", // matches Loading Unloading "Loading", "driver for", "Matched .* as autoconfigured", "Loaded and initialized", "drm", "soc", "fbdev", // matches fbdevhw "vc4", "i2c", NULL }; // Null_Terminated_String_Array log_terms = all_terms; char * rasp_log_terms[] = { "i2c", "ddcutil", "ddcui", NULL }; Null_Terminated_String_Array log_terms = ntsa_join(drivers_plus_addl_matches, rasp_log_terms, false); Null_Terminated_String_Array all_terms = log_terms; if (accum->is_arm) { logs_checked |= LOG_XORG; log_xorg_found = probe_log("/var/log/Xorg.0.log", xorg_terms, /*ignore_case*/ true, 0, depth+1); if (log_xorg_found) logs_found |= LOG_XORG; } else { logs_checked |= LOG_XORG; // rpt_vstring(depth+1, "Limiting output to 200 lines..."); log_xorg_found = probe_log("/var/log/Xorg.0.log", drivers_plus_addl_matches, /*ignore_case*/ true, 200, depth+1); if (log_xorg_found) logs_found |= LOG_XORG; } // ***/var/log/kern.log, /var/log/daemon.log, /var/log/syslog, /var/log/messages *** // Using our own code instead of shell to scan files log_messages_found = probe_log("/var/log/messages", log_terms, /*ignore_case*/ true, -40, d1); log_kern_found = probe_log("/var/log/kern.log", log_terms, /*ignore_case*/ true, -20, d1); log_daemon_found = probe_log("/var/log/daemon.log", log_terms, /*ignore_case*/ true, -10, d1); log_syslog_found = probe_log("/var/log/syslog", log_terms, /*ignore_case*/ true, -50, d1); logs_checked |= (LOG_MESSAGES | LOG_KERN | LOG_DAEMON | LOG_SYSLOG); if (log_messages_found) logs_found |= LOG_MESSAGES; if (log_kern_found) logs_found |= LOG_KERN; if (log_daemon_found) logs_found |= LOG_DAEMON; if (log_syslog_found) logs_found |= LOG_SYSLOG; // for now, just report the logs seen to avoid warning about unused vars #ifdef NO rpt_title("Log files found: ", depth); rpt_bool("dmesg" , NULL, log_dmesg_found, d1); rpt_bool("/var/log/messages" , NULL, log_messages_found, d1); rpt_bool("journalctl" , NULL, log_journalctl_found, d1); rpt_bool("/var/log/kern" , NULL, log_kern_found, d1); rpt_bool("/var/log/syslog" , NULL, log_syslog_found, d1); rpt_bool("/var/log/daemaon" , NULL, log_daemon_found, d1); rpt_bool("/var/log/Xorg.0.log" , NULL, log_xorg_found, d1); #endif rpt_nl(); rpt_title("Log Summary", d1); rpt_vstring(d2, "%-30s %-7s %-6s", "Log", "Checked", "Found"); rpt_vstring(d2, "%-30s %-7s %-6s", "===", "=======", "====="); for (Value_Name_Title * entry = log_table; entry->title; entry++) { rpt_vstring(d2, "%-30s %-7s %-6s", entry->title, sbool(logs_checked & entry->value), sbool(logs_found & entry->value)); } rpt_nl(); if (log_terms != all_terms) ntsa_free(log_terms, false); ntsa_free(all_terms, false); ntsa_free(drivers_plus_addl_matches, false); } /** Examines kernel configuration files and DKMS. * * \param accum accumulated environment */ void probe_config_files(Env_Accumulator * accum) { int depth = 0; // DBGMSG("Starting"); // debug_output_dest(); rpt_nl(); rpt_title("Examining configuration files...", depth); if (accum->is_arm) { rpt_title("Examining /boot/config.txt:", depth+1); execute_shell_cmd_rpt("grep -E -i -edtparam -edtoverlay -edevice_tree /boot/config.txt | grep -v \"^ *#\"", depth+2); rpt_nl(); rpt_vstring(depth+1, "Looking for blacklisted drivers in /etc/modprobe.d:"); execute_shell_cmd_rpt("grep -ir blacklist /etc/modprobe.d | grep -v \"^ *#\"", depth+2); } else { rpt_nl(); rpt_vstring(0,"DKMS modules:"); execute_shell_cmd_rpt("dkms status", 1 /* depth */); rpt_nl(); rpt_vstring(0,"Kernel I2C configuration settings:"); // execute_shell_cmd_rpt("grep I2C /boot/config-$(uname -r)", 1 /* depth */); execute_shell_cmd_rpt("grep I2C_CHARDEV /boot/config-$(uname -r)", 1 /* depth */); rpt_nl(); rpt_vstring(0,"Kernel AMDGPU configuration settings:"); execute_shell_cmd_rpt("grep AMDGPU /boot/config-$(uname -r)", 1 /* depth */); rpt_nl(); // TMI: // rpt_vstring(0,"Full xrandr --props:"); // execute_shell_cmd_rpt("xrandr --props", 1 /* depth */); // rpt_nl(); } } /** Reports cache files * * @oaram depth logical indentation depth */ void probe_cache_files(int depth) { int d0 = depth; int d1 = depth+1; rpt_nl(); rpt_label(d0, "Examining cache files..."); rpt_nl(); char * fn = NULL; fn = capabilities_cache_file_name(); if (fn) { rpt_vstring(d0, "Reading %s:", fn); rpt_file_contents(fn, true, d1); free(fn); } else rpt_label(d0, "Undetermined capabilities cache file name"); rpt_nl(); fn = dsa2_stats_cache_file_name(); if (fn) { rpt_vstring(d0, "Reading %s:", fn); rpt_file_contents(fn, true, d1); free(fn); } else rpt_label(d0, "Undetermined dsa cache file name"); rpt_nl(); #ifdef DISPLAYS_CACHE fn = ddc_displays_cache_file_name(); if (fn) { rpt_vstring(d0, "Reading %s:", fn); rpt_file_contents(fn, true, d1); free(fn); } else rpt_label(d0, "Undetermined displays cache file name"); rpt_nl(); #endif } ddcutil-2.2.0/src/app_sysenv/query_sysenv_modules.c0000644000175000001440000001052414572333721016257 /** \f query_sysenv_modules.c * * Module checks */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" /** \endcond */ #include "base/core.h" #include "base/linux_errno.h" #include "query_sysenv_modules.h" /** Checks if module i2c_dev is required and if so whether it is loaded. * Reports the result. * * \param accum collects environment information * \param depth logical indentation depth * * \remark * Sets #accum->module_i2c_dev_needed * #accum->module_i2c_dev_loaded * #accum->loadable_i2c_dev_exists */ void check_i2c_dev_module(Env_Accumulator * accum, int depth) { // bool debug = false; int d0 = depth; int d1 = depth+1; rpt_vstring(d0,"Checking for driver i2c_dev..."); DDCA_Output_Level output_level = get_output_level(); bool is_loaded = is_module_loaded_using_sysfs("i2c-dev"); rpt_vstring(d1, "sysfs reports module i2c_dev is%s loaded.", (is_loaded) ? "" : " NOT"); bool is_builtin = false; bool loadable = false; int module_status = module_status_by_modules_builtin_or_existence("i2c-dev"); if (module_status < 0) { rpt_vstring(d1, "Unable to determine i2c-dev status."); rpt_vstring(d1, "module_status_by_modules_builtin_or_existence() returned %s", psc_desc(module_status)); rpt_vstring(d1, "Treating i2c-dev as not builtin and not loadable!!!"); } else if (module_status == 0) { rpt_vstring(d1, "Kernel module i2c-dev does not exist!"); } if (module_status == KERNEL_MODULE_BUILTIN) is_builtin = true; if (module_status == KERNEL_MODULE_LOADABLE_FILE) loadable = true; accum->module_i2c_dev_needed = true; // relic from driver fglrx, which did not require dev-i2c accum->module_i2c_dev_builtin = is_builtin; accum->loadable_i2c_dev_exists = loadable; accum->i2c_dev_loaded_or_builtin = is_loaded || is_builtin; rpt_vstring(d1, "Module i2c_dev is%s built into the kernel", (is_builtin) ? "" : " NOT"); if (!is_builtin) { rpt_vstring(d1,"Loadable i2c-dev module %sfound", (accum->loadable_i2c_dev_exists) ? "" : "NOT "); rpt_vstring(d1,"Module %s is %sloaded", "i2c_dev", (is_loaded) ? "" : "NOT "); assert(accum->dev_i2c_device_numbers); // already set if (bva_length(accum->dev_i2c_device_numbers) == 0 && !is_loaded ) { rpt_nl(); rpt_vstring(d0, "No /dev/i2c-N devices found, and module i2c_dev is not loaded."); rpt_nl(); } if ( !is_loaded || output_level >= DDCA_OL_VERBOSE) { rpt_nl(); rpt_vstring(0,"Check that kernel module i2c_dev is being loaded by examining files where this would be specified..."); execute_shell_cmd_rpt("grep -H i2c[-_]dev " "/etc/modules " "/etc/modules-load.d/*conf " "/run/modules-load.d/*conf " "/usr/lib/modules-load.d/*conf " , d1); rpt_nl(); rpt_vstring(0,"Check for any references to i2c_dev in /etc/modprobe.d ..."); execute_shell_cmd_rpt("grep -H i2c[-_]dev " "/etc/modprobe.d/*conf " "/run/modprobe.d/*conf " , d1); } } } /** Reports video related contents of directory /etc/modprobe.d * * @param depth logical indentation depth */ void probe_modules_d(int depth) { rpt_nl(); rpt_vstring(depth, "Video related contents of /etc/modprobe.d"); char ** strings = get_all_driver_module_strings(); char * grep_terms = strjoin((const char **) strings, ntsa_length(strings), "|"); int bufsz = strlen(grep_terms) + 100; char * cmd = calloc(1, bufsz); // g_snprintf(cmd, bufsz, "grep -El \"\(%s)\" /etc/modprobe.d/*conf | xargs tail -n +1", grep_terms ); g_snprintf(cmd, bufsz, "grep -EH \"\(%s)\" /etc/modprobe.d/*conf", grep_terms ); // DBGMSG("cmd: %s", cmd); execute_shell_cmd_rpt(cmd, depth+1); free(grep_terms); free(cmd); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_procfs.c0000644000175000001440000001102114634376340016077 /** @file query_sysenv_procfs.c * * Query environment using /proc file system */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include "util/data_structures.h" #include "util/file_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #include "base/core.h" /** \endcore */ #include "query_sysenv_base.h" #include "query_sysenv_procfs.h" /** Scans /proc/modules for information on loaded drivers of interest */ int query_proc_modules_for_video() { bool debug = false; DBGMSF(debug, "Starting."); int d1 = 1; int rc = 0; GPtrArray * garray = g_ptr_array_sized_new(300); g_ptr_array_set_free_func(garray, g_free); rpt_vstring(0,"Scanning /proc/modules for driver environment..."); int ct = file_getlines("/proc/modules", garray, true); if (ct < 0) rc = ct; else { int ndx = 0; for (ndx=0; ndxlen; ndx++) { char * curline = g_ptr_array_index(garray, ndx); // Per Issue 354, user encountered segfault if built with // -flto (Link Time Optimization). For an unclear reason, // initializing the destination string variables solves the problem. char mod_name[32] = {}; int mod_size; int mod_instance_ct; char mod_dependencies[500] = {}; char mod_load_state[10] = {}; // one of: Live Loading Unloading char mod_addr[30] = {}; int piece_ct = sscanf(curline, "%s %d %d %s %s %s", mod_name, &mod_size, &mod_instance_ct, mod_dependencies, mod_load_state, mod_addr); if (piece_ct != 6) { DBGMSG("Unexpected error parsing /proc/modules. sscanf returned %d", piece_ct); } if (streq(mod_name, "drm") ) { rpt_vstring(d1,"Loaded drm module depends on: %s", mod_dependencies); } else if (streq(mod_name, "video") ) { rpt_vstring(d1,"Loaded video module depends on: %s", mod_dependencies); } else if (exactly_matches_any(mod_name, (const char **) get_known_video_driver_module_names()) >= 0 ) { rpt_vstring(d1,"Found video driver module: %s", mod_name); } else if ( starts_with_any(mod_name, (const char **) get_prefix_match_names()) >= 0 ) { rpt_vstring(d1,"Found other loaded module: %s", mod_name); } } } g_ptr_array_free(garray, true); DBGMSF(debug, "Done."); return rc; } /** Reports nvidia proprietary driver information by examining * /proc/driver/nvidia. */ bool query_proc_driver_nvidia() { bool debug = false; bool result = false; char * dn = "/proc/driver/nvidia/"; if ( directory_exists(dn) ) { rpt_vstring(0,"Examining /proc/driver/nvidia:"); result = true; sysenv_show_one_file(dn, "version", debug, 1); sysenv_show_one_file(dn, "registry", debug, 1); sysenv_show_one_file(dn, "params", debug, 1); char * dn_gpus = "/proc/driver/nvidia/gpus/"; if (directory_exists(dn_gpus)) { DIR * dp = opendir(dn_gpus); struct dirent * ep; while ( (ep = readdir(dp)) ) { if ( !streq(ep->d_name,".") && !streq(ep->d_name, "..") ) { rpt_vstring(1, "PCI bus id: %s", ep->d_name); char dirbuf[400]; strcpy(dirbuf, dn_gpus); strcat(dirbuf, ep->d_name); // printf("Reading directory: %s\n", dirbuf); // DIR * dp2 = opendir(dirbuf); // if (dp2) { // struct dirent * ep2; // printf("GPU: %s\n", ep->d_name); // while ( (ep2 = readdir(dp2)) ) { // if ( !streq(ep2->d_name,".") && !streq(ep2->d_name, "..") ) { // puts(ep2->d_name); // } // } // closedir(dp2); // } if ( directory_exists(dirbuf)) { sysenv_show_one_file(dirbuf, "information", debug, 1); sysenv_show_one_file(dirbuf, "registry", debug, 1); } } } closedir(dp); } } else { DBGMSF(debug, "Nvidia driver directory %s not found\n", dn); } return result; } ddcutil-2.2.0/src/app_sysenv/query_sysenv_sysfs_common.c0000644000175000001440000000167414441414365017333 // query_sysenv_sysfs_common.c // Copyright (C) 2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "util/string_util.h" #include "util/sysfs_util.h" #include "base/core.h" #include "query_sysenv_sysfs_common.h" // Local conversion functions for data coming from sysfs, // which should always be valid. ushort h2ushort(char * hval) { bool debug = false; ushort ival; #ifdef NDEBUG sscanf(hval, "%hx", &ival); #else assert( sscanf(hval, "%hx", &ival) == 1); #endif DBGMSF(debug, "hhhh = |%s|, returning 0x%04x", hval, ival); return ival; } unsigned h2uint(char * hval) { bool debug = false; unsigned ival; #ifdef NDEBUG sscanf(hval, "%x", &ival); #else assert( sscanf(hval, "%x", &ival) == 1); #endif DBGMSF(debug, "hhhh = |%s|, returning 0x%08x", hval, ival); return ival; } ddcutil-2.2.0/src/app_sysenv/query_sysenv_original_sys_scans.c0000644000175000001440000002357114754153540020507 /** \file query_sysenv_original_sys_scans.c * * This file contains the original /sys scans, one that starts at /sys/bus/drm * and the second starting at /sys/bus/i2c/devices */ // Copyright (C) 2018-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "util/file_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "base/core.h" #include "query_sysenv_original_sys_scans.h" // Directory Report Functions // *** Detail for /sys/bus/i2c/devices (Initial Version) *** void one_bus_i2c_device(int busno, void * accumulator, int depth) { bool debug = false; DBGMSF(debug, "Starting. busno=%d", busno); int d1 = depth+1; char pb1[PATH_MAX]; // char pb2[PATH_MAX]; char * dir_devices_i2cN = g_strdup_printf("/sys/bus/i2c/devices/i2c-%d", busno); char * real_device_dir = realpath(dir_devices_i2cN, pb1); rpt_vstring(depth, "Examining (5) %s -> %s", dir_devices_i2cN, real_device_dir); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "name"); char * device_class = NULL; if ( RPT_ATTR_TEXT(d1, &device_class, dir_devices_i2cN, "device/class") ) { if ( str_starts_with(device_class, "0x03") ){ // TODO: replace test RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/boot_vga"); RPT_ATTR_REALPATH_BASENAME( d1, NULL, dir_devices_i2cN, "device/driver"); RPT_ATTR_REALPATH_BASENAME( d1, NULL, dir_devices_i2cN, "device/driver/module"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/enable"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/modalias"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/vendor"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/device"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/subsystem_vendor"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/subsystem_device"); char * i2c_dev_subdir = NULL; RPT_ATTR_SINGLE_SUBDIR(d1, &i2c_dev_subdir, NULL, NULL, dir_devices_i2cN, "i2c-dev"); if (i2c_dev_subdir) { RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "i2c-dev", i2c_dev_subdir, "dev"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "i2c-dev", i2c_dev_subdir, "name"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "i2c-dev", i2c_dev_subdir, "device"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "i2c-dev", i2c_dev_subdir, "subsystem"); free(i2c_dev_subdir); } } } else { // device/class not found g_snprintf(pb1, PATH_MAX, "%s/%s", dir_devices_i2cN, "device/class"); rpt_attr_output(d1, pb1, ":", "Not found. (May be display port)"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "subsystem"); bool ddc_subdir_found = RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device/ddc"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device/device"); RPT_ATTR_EDID( d1, NULL, dir_devices_i2cN, "device/edid"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/status"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device/subsystem"); char * realpath = NULL; RPT_ATTR_REALPATH(d1, &realpath, dir_devices_i2cN, "device/device"); if (realpath) { rpt_attr_output(d1, "","","Skipping linked directory"); free(realpath); } if (ddc_subdir_found) { RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/ddc/name"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device/ddc/subsystem"); char * i2c_dev_subdir = NULL; RPT_ATTR_SINGLE_SUBDIR(d1, &i2c_dev_subdir, NULL, NULL, dir_devices_i2cN, "device/ddc/i2c-dev"); // /sys/bus/i2c/devices/i2c-N/device/ddc/i2c-dev/i2c-M // dev // device (link) // name // subsystem (link) RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/ddc/i2c-dev", i2c_dev_subdir, "dev"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device/ddc/i2c-dev", i2c_dev_subdir, "device"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/ddc/i2c-dev", i2c_dev_subdir, "name"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device/ddc/i2c-dev", i2c_dev_subdir, "subsystem"); free(i2c_dev_subdir); } // /sys/bus/i2c/devices/i2c-N/device/drm_dp_auxNdump_sysfs_i2c char * drm_dp_aux_subdir = NULL; RPT_ATTR_SINGLE_SUBDIR( d1, &drm_dp_aux_subdir, str_starts_with, "drm_dp_aux", dir_devices_i2cN, "device"); RPT_ATTR_REALPATH_BASENAME(d1, NULL, dir_devices_i2cN, "device/ddc/device/driver"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device/enabled"); if (drm_dp_aux_subdir) { RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device", drm_dp_aux_subdir, "dev"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device", drm_dp_aux_subdir, "device"); RPT_ATTR_TEXT( d1, NULL, dir_devices_i2cN, "device", drm_dp_aux_subdir, "name"); RPT_ATTR_REALPATH(d1, NULL, dir_devices_i2cN, "device", drm_dp_aux_subdir, "device/subsystem"); free(drm_dp_aux_subdir); } } free(dir_devices_i2cN); } void each_i2c_device_new(const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGMSF(debug, "Starting. dirname=%s, fn=%s", dirname, fn); rpt_nl(); int busno = i2c_name_to_busno(fn); if (busno < 0) rpt_vstring(1, "Unexpected I2C device name: %s", fn); else { one_bus_i2c_device(busno, NULL, 1); } } // *** Detail for /sys/class/drm (initial version) *** void each_drm_device(const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGMSF(debug, "Starting. dirname=%s, fn=%s", dirname, fn); rpt_nl(); int d1 = depth+1; char * drm_cardX_dir = g_strdup_printf("/sys/class/drm/%s", fn); char * real_cardX_dir = realpath(drm_cardX_dir, NULL); rpt_vstring(depth, "Examining (6) %s -> %s", drm_cardX_dir, real_cardX_dir); // e.g. /sys/class/drm/card0-DP-1 RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, "ddc"); RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, "device"); char * drm_dp_aux_subdir = NULL; // exists only if DP RPT_ATTR_SINGLE_SUBDIR(d1, &drm_dp_aux_subdir, str_starts_with, "drm_dp_aux", drm_cardX_dir); RPT_ATTR_EDID( d1, NULL, drm_cardX_dir, "edid"); RPT_ATTR_TEXT( d1, NULL, drm_cardX_dir, "enabled"); char * i2cN_subdir = NULL; // exists only if DP RPT_ATTR_SINGLE_SUBDIR(d1, &i2cN_subdir, str_starts_with, "i2c-", drm_cardX_dir); RPT_ATTR_TEXT( d1, NULL, drm_cardX_dir, "status"); RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, "subsystem"); // messages subdirectories of card0/DP-1 // e.g. /sys/class/drm/card0-DP-1/drm_dp_aux0 // does not exist for non-DP if (drm_dp_aux_subdir) { rpt_nl(); RPT_ATTR_TEXT( d1, NULL, drm_cardX_dir, drm_dp_aux_subdir, "dev"); RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, drm_dp_aux_subdir, "device"); RPT_ATTR_TEXT( d1, NULL, drm_cardX_dir, drm_dp_aux_subdir, "name"); // RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, drm_dp_aux_subdir, "subsystem") free(drm_dp_aux_subdir); } // e.g. /sys/class/drm/card0-DP-1/i2c-13 // does not exist for non-DP if (i2cN_subdir) { rpt_nl(); RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, i2cN_subdir, "device"); RPT_ATTR_NOTE_SUBDIR( d1, NULL, drm_cardX_dir, i2cN_subdir, "i2c-dev"); RPT_ATTR_TEXT( d1, NULL, drm_cardX_dir, i2cN_subdir, "name"); RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, i2cN_subdir, "subsystem"); rpt_nl(); // e.g. /sys/class/drm-card0-DP-1/i2c-13/i2c-dev RPT_ATTR_NOTE_SUBDIR( d1, NULL, drm_cardX_dir, i2cN_subdir, "i2c-dev", i2cN_subdir); // or can subdir name vary? // e.g. /sys/class/drm-card0-DP-1/i2c-13/i2c-dev/i2c-13 RPT_ATTR_TEXT( d1, NULL, drm_cardX_dir, i2cN_subdir, "i2c-dev", i2cN_subdir, "dev"); RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, i2cN_subdir, "i2c-dev", i2cN_subdir, "device"); RPT_ATTR_TEXT( d1, NULL, drm_cardX_dir, i2cN_subdir, "i2c-dev", i2cN_subdir, "name"); RPT_ATTR_REALPATH( d1, NULL, drm_cardX_dir, i2cN_subdir, "i2c-dev", i2cN_subdir, "subsystem"); free(i2cN_subdir); } free(drm_cardX_dir); free(real_cardX_dir); } void dump_original_sys_scans() { if (get_output_level() >= DDCA_OL_VV) { rpt_nl(); rpt_label(0, "*** Detail for /sys/bus/i2c/devices (Initial Version) ***"); dir_ordered_foreach( "/sys/bus/i2c/devices", NULL, // fn_filter i2c_compare, each_i2c_device_new, NULL, // accumulator 0); // depth rpt_nl(); rpt_label(0, "*** Detail for /sys/class/drm (Initial Version) ***"); dir_ordered_foreach( "/sys/class/drm", predicate_cardN_connector, gaux_ptr_scomp, // GCompareFunc each_drm_device, // NULL, // accumulator 0); // depth #ifdef TMI GPtrArray * video_devices = execute_shell_cmd_collect( "find /sys/devices -name class | xargs grep -il 0x03 | xargs dirname | xargs ls -lR"); rpt_nl(); rpt_vstring(0, "Display devices: (class 0x03nnnn)"); for (int ndx = 0; ndx < video_devices->len; ndx++) { char * dirname = g_ptr_array_index(video_devices, ndx); rpt_vstring(2, "%s", dirname); } #endif } } ddcutil-2.2.0/src/app_sysenv/query_sysenv_detailed_bus_pci_devices.c0000644000175000001440000003103114754153540021565 /** \file query_sysenv_detailed_bus_pci_devices.c * * This file contains a variant of the scan of /sys/bus/pci/devices that * that performs minimal filtering of attributes. */ // Copyright (C) 2022-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include "util/data_structures.h" #include "util/device_id_util.h" #include "util/file_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "base/core.h" #include "base/linux_errno.h" #include "base/rtti.h" /** \endcond */ #include "sysfs/sysfs_sys_drm_connector.h" #include "query_sysenv_base.h" #include "query_sysenv_sysfs_common.h" #include "query_sysenv_detailed_bus_pci_devices.h" /** Reports a sysfs subdirectory N-0037, where N is the I2C bus number. * This directory is created by ddcci driver, which conflicts with ddcutil. * * \param depth * \param fq_i2c_dir_name * \param busno * * \TODO * Extract busno from fq_i2c_dir_name */ void rpt_0037_subdir(int depth, char * fq_i2c_dir_name, int busno) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "fqfn=%s, busno=%d", fq_i2c_dir_name, busno); int d0 = depth; char buf[20]; char * fn_0037 = NULL; g_snprintf(buf, 20, "%d-0037", busno); RPT_ATTR_SINGLE_SUBDIR(d0, &fn_0037, streq, buf, fq_i2c_dir_name); if (fn_0037) { RPT_ATTR_REALPATH(d0, NULL, fq_i2c_dir_name, fn_0037, "driver/module"); RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, "name"); char * ddcci_subdir = NULL; char ddcciN[20]; g_snprintf(ddcciN, 20, "ddcci%d", busno); RPT_ATTR_SINGLE_SUBDIR(d0, &ddcci_subdir, streq, ddcciN, fq_i2c_dir_name, fn_0037); if (ddcci_subdir) { RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "capabilities"); RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "dev"); // RPT_ATTR_TEXT(d0, NULL, fqfn, fn_0037, ddcciN, "idModel"); #ifdef HUH GByteArray * idModel = NULL; rpt_attr_binary(d0, &idModel, fq_i2c_dir_name, fn_0037, ddcciN, "idModel"); if (idModel) { char * node = "Fully qualified node name"; rpt_attr_output(d0, node, "=", hexstring_t(idModel->data, idModel->len)); } #endif // RPT_ATTR_TEXT(d0, NULL, fqfn, fn_0037, ddcciN, "idModule"); RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "idProt"); RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "idSerial"); RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "idType"); // RPT_ATTR_TEXT(d0, NULL, fqfn, fn_0037, ddcciN, "idVendor"); char * backlight_subdir = NULL; if ( RPT_ATTR_NOTE_SUBDIR(d0, &backlight_subdir, fq_i2c_dir_name, fn_0037, ddcciN, "backlight", ddcciN) ) { RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "backlight", ddcciN, "actual_brightness"); RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "backlight", ddcciN, "brightness"); RPT_ATTR_TEXT(d0, NULL, fq_i2c_dir_name, fn_0037, ddcciN, "backlight", ddcciN, "max_brightness"); RPT_ATTR_REALPATH(d0, NULL, fq_i2c_dir_name , fn_0037, ddcciN, "backlight", ddcciN, "subsystem"); } free(ddcci_subdir); } free(fn_0037); } DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } // Directory Report Functions void sysfs_dir_cardN_cardNconnector( const char * dirname, const char * filename, void * accumulator, int depth) { rpt_nl(); char dirname_fn[PATH_MAX]; g_snprintf(dirname_fn, PATH_MAX, "%s/%s", dirname, filename); // DBGMSG("dirname=%s, filename=%s, dirname_fn=%s", dirname, filename, dirname_fn); int d0 = depth; // int d1 = depth+1; // int d2 = depth+2; RPT_ATTR_REALPATH( d0, NULL, dirname_fn, "device"); RPT_ATTR_REALPATH( d0, NULL, dirname_fn, "ddc"); RPT_ATTR_EDID( d0, NULL, dirname_fn, "edid"); RPT_ATTR_TEXT( d0, NULL, dirname_fn, "enabled"); RPT_ATTR_TEXT( d0, NULL, dirname_fn, "status"); RPT_ATTR_REALPATH( d0, NULL, dirname_fn, "subsystem"); // for DP, also: // drm_dp_auxN // i2c-N char * dir_drm_dp_aux = NULL; RPT_ATTR_SINGLE_SUBDIR(d0, &dir_drm_dp_aux, str_starts_with, "drm_dp_aux", dirname_fn); if (dir_drm_dp_aux) { RPT_ATTR_REALPATH(d0, NULL, dirname_fn, dir_drm_dp_aux, "device"); RPT_ATTR_TEXT( d0, NULL, dirname_fn, dir_drm_dp_aux, "dev"); RPT_ATTR_TEXT( d0, NULL, dirname_fn, dir_drm_dp_aux, "name"); RPT_ATTR_REALPATH(d0, NULL, dirname_fn, dir_drm_dp_aux, "subsystem"); free(dir_drm_dp_aux); } char * dir_i2cN = NULL; RPT_ATTR_SINGLE_SUBDIR(d0, &dir_i2cN, str_starts_with, "i2c-",dirname_fn); if (dir_i2cN) { char pb1[PATH_MAX]; g_snprintf(pb1, PATH_MAX, "%s/%s", dirname_fn, dir_i2cN); // sysfs_dir_i2c_dev(fqfn, dir_i2cN, accumulator, d0); char * dir_i2cN_i2cdev_i2cN = NULL; RPT_ATTR_SINGLE_SUBDIR(d0, &dir_i2cN_i2cdev_i2cN, str_starts_with, "i2c-", dirname_fn, dir_i2cN, "i2c-dev"); if (dir_i2cN_i2cdev_i2cN) { RPT_ATTR_REALPATH(d0, NULL, dirname_fn, dir_i2cN, "i2c-dev", dir_i2cN_i2cdev_i2cN, "device"); RPT_ATTR_TEXT( d0, NULL, dirname_fn, dir_i2cN, "i2c-dev", dir_i2cN_i2cdev_i2cN, "dev"); RPT_ATTR_TEXT( d0, NULL, dirname_fn, dir_i2cN, "i2c-dev", dir_i2cN_i2cdev_i2cN, "name"); RPT_ATTR_REALPATH(d0, NULL, dirname_fn, dir_i2cN, "i2c-dev", dir_i2cN_i2cdev_i2cN, "subsystem"); free(dir_i2cN_i2cdev_i2cN); } RPT_ATTR_REALPATH( d0, NULL, dirname_fn, dir_i2cN, "device"); RPT_ATTR_TEXT( d0, NULL, dirname_fn, dir_i2cN, "name"); RPT_ATTR_REALPATH( d0, NULL, dirname_fn, dir_i2cN, "subsystem"); int busno = i2c_name_to_busno(dir_i2cN); rpt_nl(); rpt_0037_subdir(d0, pb1, busno); free(dir_i2cN); } } /** Process all /sys/bus/pci/devices//cardN directories * * These directories exist for DisplayPort connectors * * Note the realpath for these directories is one of * /sys/bus/devices/NNNN:NN:NN.N/cardN * /sys/bus/devices/NNNN:NN:NN.N/NNNN:NN:nn.N/cardN * Include subdirectory i2c-dev/i2c-N * * @param dirname name of device directory * @param filename i2c-N * @param accumulator * @param depth logical indentation depth */ void sysfs_dir_cardN( const char * dirname, const char * filename, void * accumulator, int depth) { char fqfn[PATH_MAX]; g_snprintf(fqfn, PATH_MAX, "%s/%s", dirname, filename); dir_ordered_foreach( fqfn, predicate_cardN_connector, gaux_ptr_scomp, // GCompareFunc sysfs_dir_cardN_cardNconnector, accumulator, depth); } /** Process /sys/bus/pci/devices//i2c-N directory * * These directories exist for non-DP connectors * * Note the realpath for these directories is one of * /sys/bus/devices/NNNN:NN:NN.N/i2c-N * /sys/bus/devices/NNNN:NN:NN.N/NNNN:NN:nn.N/i2c-N * Include subdirectory i2c-dev/i2c-N * * @param dirname name of device directory * @param filename i2c-N * @param accumulator * @param depth logical indentation depth */ void sysfs_dir_i2cN( const char * dirname, const char * filename, void * accumulator, int depth) { rpt_nl(); char fqfn[PATH_MAX]; g_snprintf(fqfn, PATH_MAX, "%s/%s", dirname, filename); int d0 = depth; RPT_ATTR_REALPATH(d0, NULL, fqfn, "device"); RPT_ATTR_TEXT( d0, NULL, fqfn, "name"); RPT_ATTR_REALPATH(d0, NULL, fqfn, "subsystem"); char * i2c_dev_fn = NULL; RPT_ATTR_SINGLE_SUBDIR(d0, &i2c_dev_fn, streq, "i2c-dev", fqfn); if (i2c_dev_fn) { char * i2cN = NULL; RPT_ATTR_SINGLE_SUBDIR(d0, &i2cN,NULL, NULL, fqfn, "i2c-dev"); RPT_ATTR_REALPATH( d0, NULL, fqfn, "i2c-dev", i2cN, "device"); RPT_ATTR_TEXT( d0, NULL, fqfn, "i2c-dev", i2cN, "dev"); RPT_ATTR_TEXT( d0, NULL, fqfn, "i2c-dev", i2cN, "name"); RPT_ATTR_REALPATH( d0, NULL, fqfn, "i2c-dev", i2cN, "subsystem"); free(i2cN); free(i2c_dev_fn); } int busno = i2c_name_to_busno(filename); rpt_0037_subdir(d0, fqfn, busno); } /** Process a single /sys/bus/pci/devices/ * * Returns immediately if class is not a display device or docking station * * PPPP:BB:DD:F * PPPP PCI domain * BB bus number * DD device number * F device function * * Note the realpath for these directories is one of * /sys/bus/devices/PPPP:BB:DD.F * /sys/bus/devices/NNNN:NN:NN.N/PPPP:BB:DD:F */ void one_pci_device( const char * dirname, const char * filename, void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dirname=%s, filename=%s", dirname, filename); int d0 = depth; int d1 = depth+1; char dir_fn[PATH_MAX]; g_snprintf(dir_fn, PATH_MAX, "%s/%s", dirname, filename); char * device_class = read_sysfs_attr(dir_fn, "class", false); if (!device_class) { DBGTRC_DONE(debug, DDCA_TRC_NONE, "no device_class"); return; } unsigned class_id = h2uint(device_class); // DBGMSF(debug, "class_id: 0x%08x", class_id); // if (str_starts_with(device_class, "0x03")) { if (class_id >> 16 != 0x03 && // Display controller class_id >> 16 != 0x0a) // Docking station { DBGTRC_DONE(debug, DDCA_TRC_NONE, "class not display or docking station"); return; } free(device_class); char rpath[PATH_MAX]; // without assignment, get warning that return value of realpath() is not used // causes compilation failures since all warnings treated as errors _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wunused-result\"") realpath(dir_fn, rpath); _Pragma("GCC diagnostic pop") // DBGMSG("dirname=%s, filename=%s, pb1=%s, rpath=%s", dirname, filename, pb1, rpath); rpt_nl(); rpt_vstring( d0, "Examining %s/%s -> %s", dirname, filename, rpath); RPT_ATTR_REALPATH(d1, NULL, dirname, filename, "device"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "class"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "boot_vga"); RPT_ATTR_REALPATH_BASENAME(d1, NULL, dirname, filename, "driver"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "enable"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "modalias"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "vendor"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "device"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "subsystem_vendor"); RPT_ATTR_TEXT( d1, NULL, dirname, filename, "subsystem_device"); RPT_ATTR_REALPATH(d1, NULL, dirname, filename, "subsystem"); rpt_nl(); // Process drm subdirectory char * drm_fn = NULL; bool has_drm_dir = RPT_ATTR_SINGLE_SUBDIR(d1, &drm_fn, streq, "drm", dir_fn); if (has_drm_dir) { char dir_fn_drm[PATH_MAX]; g_snprintf(dir_fn_drm, PATH_MAX, "%s/%s", dir_fn, "drm"); dir_ordered_foreach( dir_fn_drm, predicate_cardN, // only subdirectories named drm/cardN gaux_ptr_scomp, // GCompareFunc sysfs_dir_cardN, accumulator, d1); free(drm_fn); } // Process i2c-N subdirectories: dir_ordered_foreach( dir_fn, predicate_i2c_N, // only subdirectories named i2c-N i2c_compare, // order by i2c device number, handles names not of form "i2c-N" sysfs_dir_i2cN, accumulator, d1); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } void dump_detailed_sys_bus_pci(int depth) { rpt_label(depth, "*** Detailed /sys/bus/pci/devices scan ***"); // rpt_nl(); dir_filtered_ordered_foreach("/sys/bus/pci/devices", has_class_display_or_docking_station, // filter function NULL, // ordering function one_pci_device, NULL, // accumulator depth); } void init_query_detailed_bus_pci_devices() { RTTI_ADD_FUNC(rpt_0037_subdir); RTTI_ADD_FUNC(one_pci_device); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_simplified_sys_bus_pci_devices.c0000644000175000001440000001254014754153540023041 /** \file query_sysenv_sys_bus_pci_devices.c * * This file contains a variant of the scan of /sys/bus/pci/devices that * that focuses on attributes determined to be of significance. */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include "config.h" #include "public/ddcutil_c_api.h" #include "public/ddcutil_types.h" #include "util/file_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "base/core.h" #include "query_sysenv_sysfs_common.h" #include "query_sysenv_simplified_sys_bus_pci_devices.h" // Default trace class for this file // static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_ENV; // // Pruned Scan // // Directory report functions // report /drm void report_drm_dir( const char * dirname, // const char * fn, // drm void * data, int depth) { bool debug = false; DBGMSF(debug, "dirname=%s, fn=%s", dirname, fn); char * name_val; bool found_name = RPT_ATTR_TEXT(0, &name_val, dirname, fn, "name"); DBGMSF(debug, "RPT_ATTR_TEXT returned %s, name_val -> %s", sbool(found_name), name_val); } // report /i2c-N void report_one_i2c_dir( const char * dirname, // const char * fn, // i2c-1, i2c-2, etc., possibly 1-0037, 1-0023, 1-0050 etc void * data, int depth) { bool debug = false; DBGMSF(debug, "dirname=%s, fn=%s", dirname, fn); rpt_nl(); char * name_val; bool found_name = RPT_ATTR_TEXT(0, &name_val, dirname, fn, "name"); RPT_ATTR_TEXT(0, NULL, dirname, fn, "i2c-dev", fn, "name"); RPT_ATTR_TEXT(0, NULL, dirname, fn, "i2c-dev", fn, "dev"); DBGMSF(debug, "RPT_ATTR_TEXT returned %s, name_val -> %s", sbool(found_name), name_val); } static void report_one_connector( const char * dirname, // /drm/cardN const char * simple_fn, // card0-HDMI-1 etc void * data, int depth) { bool debug = false; DBGMSF(debug, "Starting. dirname=%s, simple_fn=%s", dirname, simple_fn); rpt_nl(); char * drm_dp_aux_subdir = NULL; char * i2c_subdir = NULL; RPT_ATTR_TEXT(depth, NULL, dirname, simple_fn, "enabled"); RPT_ATTR_TEXT(depth, NULL, dirname, simple_fn, "status"); RPT_ATTR_TEXT(depth, NULL, dirname, simple_fn, "dpms"); RPT_ATTR_EDID(depth, NULL, dirname, simple_fn, "edid"); RPT_ATTR_REALPATH(depth, NULL, dirname, simple_fn, "ddc"); RPT_ATTR_SINGLE_SUBDIR(depth, &drm_dp_aux_subdir, is_drm_dp_aux_subdir, "drm_dp_aux", dirname, simple_fn); if (drm_dp_aux_subdir) { // DisplayPort RPT_ATTR_TEXT(0, NULL, dirname, simple_fn, drm_dp_aux_subdir, "name"); RPT_ATTR_TEXT(0, NULL, dirname, simple_fn, drm_dp_aux_subdir, "dev"); free(drm_dp_aux_subdir); } RPT_ATTR_SINGLE_SUBDIR(depth, &i2c_subdir, is_i2cN_dir, "i2c-", dirname, simple_fn); if (i2c_subdir) { RPT_ATTR_TEXT(depth, NULL, dirname, simple_fn, i2c_subdir, "name"); RPT_ATTR_TEXT(depth, NULL, dirname, simple_fn, i2c_subdir, "dev"); free(i2c_subdir); } DBGMSF(debug, "Done"); } void report_one_cardN( const char * dirname, const char * simple_fn, void * accum, int depth) { bool debug = false; DBGMSF(debug, "Starting. dirname=%s, simple_fn=%s", dirname, simple_fn); char * thisdir = g_strdup_printf("%s/%s", dirname, simple_fn); dir_filtered_ordered_foreach( thisdir, is_card_connector_dir, NULL, report_one_connector, NULL, depth); DBGMSF(debug, "Done."); } void report_one_pci_device( const char * dirname, // const char * fn, // i2c-1, i2c-2, etc., possibly 1-0037, 1-0023, 1-0050 etc void * data, int depth) { bool debug = false; DBGMSF(debug, "dirname=%s, fn=%s", dirname, fn); RPT_ATTR_TEXT( depth, NULL, dirname, fn, "class"); RPT_ATTR_REALPATH(depth, NULL, dirname, fn, "driver"); char * thisdir = g_strdup_printf("%s/%s", dirname, fn); dir_filtered_ordered_foreach( thisdir, is_i2cN_dir, i2c_compare, report_one_i2c_dir, NULL, depth); if ( RPT_ATTR_NOTE_SUBDIR(0, NULL, dirname, fn, "drm")) { char * drmdir = g_strdup_printf("%s/%s/drm", dirname, fn); dir_filtered_ordered_foreach( drmdir, is_cardN_dir, gaux_ptr_scomp, // fails if card-11 etc.exist, but chance of that is vanishingly small report_one_cardN, NULL, depth); } rpt_nl(); } void dump_simplified_sys_bus_pci(int depth) { rpt_nl(); // rpt_nl(); // show_top_level_sys_entries(depth); rpt_nl(); rpt_label(depth, "*** Simplified /sys/bus/pci/devices scan ***"); rpt_nl(); dir_filtered_ordered_foreach("/sys/bus/pci/devices", has_class_display_or_docking_station, // filter function NULL, // ordering function report_one_pci_device, NULL, // accumulator depth); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_sysfs.c0000644000175000001440000007531114754153540015764 /** @file query_sysenv_sysfs.c * * Query environment using /sys file system */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include #include "util/data_structures.h" #include "util/device_id_util.h" #include "util/file_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "base/core.h" #include "base/linux_errno.h" #include "base/rtti.h" /** \endcond */ #include "sysfs/sysfs_i2c_sys_info.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "sysfs/sysfs_top.h" #include "query_sysenv_base.h" #include "query_sysenv_sysfs_common.h" #include "query_sysenv_original_sys_scans.h" #include "query_sysenv_detailed_bus_pci_devices.h" #include "query_sysenv_simplified_sys_bus_pci_devices.h" #include "query_sysenv_xref.h" #include "query_sysenv_sysfs.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_ENV; // Notes on directory structure // // Raspbian: // /sys/bus/platform/drivers/vc4_v3d // /sys/module/vc4 // Two ways to get the hex device identifiers. Both are ugly. // Reading modalias requires extracting values from a single string. // Reading individual ids from individual attributes is simpler, // but note the lack of error checking. // Pick your poison. /** Reads the device identifiers from directory * /sys/bus/pci/devices/nnnn:nn:nn.n/ using the individual vendor, device, * subsystem, and subsystem_device attributes. * * \param cur_dir_name directory name * \return struct containing the ids * * \remark * Note the struct itself is returned on the stack, not a pointer to a struct. * There is nothing to free. */ Device_Ids read_device_ids1(char * cur_dir_name) { Device_Ids result = {0}; char * vendor_id = read_sysfs_attr_w_default(cur_dir_name, "vendor", "0x00", true); char * device_id = read_sysfs_attr_w_default(cur_dir_name, "device", "0x00", true); char * subsystem_device = read_sysfs_attr_w_default(cur_dir_name, "subsystem_device", "0x00", true); char * subsystem_vendor = read_sysfs_attr_w_default(cur_dir_name, "subsystem_vendor", "0x00", true); result.vendor_id = h2ushort(vendor_id); result.device_id = h2ushort(device_id); result.subvendor_id = h2ushort(subsystem_vendor); result.subdevice_id = h2ushort(subsystem_device); free(vendor_id); free(device_id); free(subsystem_device); free(subsystem_vendor); return result; } /** Reads the device identifiers from the directory of a PCI device * (/sys/bus/pci/devices/nnnn:nn:nn.n/) by reading and parsing the modalias * attribute. * * \param cur_dir_name directory name * \return struct containing the ids * * \remark * Note the struct itself is returned on the stack, not a pointer to a struct. * There is nothing to free. */ Device_Ids read_device_ids2(char * cur_dir_name) { Device_Ids result = {0}; // TODO: Reimplement using proper parsing. See kernel file file2alias.c // See also: // http://people.skolelinux.org/pere/blog/Modalias_strings___a_practical_way_to_map__stuff__to_hardware.html char * modalias = read_sysfs_attr(cur_dir_name, "modalias", true); // printf("modalias: %s\n", modalias); if (modalias) { // printf("\nParsing modalias for values...\n"); char * colonpos = strchr(modalias, ':'); assert(colonpos); // coverity complains that strchr() might return NULL assert(*(colonpos+1) == 'v'); // vendor_id char * vendor_id = substr(colonpos, 2, 8); // printf("vendor_id: %s\n", vendor_id); assert(*(colonpos+10) == 'd'); char * device_id = lsub(colonpos+11,8); // printf("device_id: %s\n", device_id); assert( *(colonpos+19) == 's'); assert( *(colonpos+20) == 'v'); char * subsystem_vendor = lsub(colonpos+21,8); // printf("subsystem_vendor: %s\n", subsystem_vendor); assert( *(colonpos+29) == 's'); assert( *(colonpos+30) == 'd'); char * subsystem_device = lsub(colonpos+31,8); // printf("subsystem_device: %s\n", subsystem_device); assert( *(colonpos+39) == 'b'); assert( *(colonpos+40) == 'c'); // not used //char * base_class = lsub(colonpos+41,2); // printf("base_class: %s\n", base_class); // bytes 0-1 of value from class assert( *(colonpos+43) == 's'); assert( *(colonpos+44) == 'c'); // not used // char * sub_class = lsub(colonpos+45,2); // bytes 1-2 of value from class // printf("sub_class: %s\n", sub_class); assert( *(colonpos+47) == 'i'); // not used // char * interface_id = lsub(colonpos+48,2); // printf("interface_id: %s\n", interface_id); // bytes 4-5 of value from class? result.vendor_id = h2ushort(vendor_id); result.device_id = h2ushort(device_id); result.subvendor_id = h2ushort(subsystem_vendor); result.subdevice_id = h2ushort(subsystem_device); free(vendor_id); free(device_id); free(subsystem_vendor); free(subsystem_device); free(modalias); } return result; } #ifdef FUTURE_FRAGMENT void report_modalias(char * cur_dir_name, int depth) { char * modalias = read_sysfs_attr(cur_dir_name, "modalias", true); // printf("modalias: %s\n", modalias); if (modalias) { char * colonpos = strchr(modalias, ':'); assert(colonpos); // coverity complains that strchr() might return NULL if (!colonpos) { rpt_vstring(depth, "Unexpected modalias value: %s", modalias); } if (memcmp(modalias, "pci", (colonpos-1)-modalias) == 0) { // TO DO: properly refactor Device_Ids = read_device_ids2(cur_dir_name); // TOD: report it } else if (memcmp(modalias, "of", (colonpos-1)-modalias) == 0) { // format: of:NnameTtypeCclass // type may be "" // Cclass is optional // may repeat? char * re = "^of:N(.*)T(.*)" } else { rpt_vstring(depth, "modialias: %s", modalias); } } } #endif /** Reports one directory whose name is of the form /sys/bus/pci/devices/nnnn:nn:nn.n/driver * * Processes only files whose name is of the form i2c-n, * reporting the i2c-n dname and the the contained name attribute. * * This function is passed from #each_video_pci_device() to #dir_foreach() , * which in turn invokes this function. * * \param dirname always /sys/bus/pci/devices/nnnn:nn:nn.n/driver * \param fn fn, process only those of form i2c-n * \param accumulator accumulator struct * \param depth logical indentation depth */ void each_video_device_i2c( const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGMSF(debug, "dirname=%s, fn=%s", dirname, fn); if (str_starts_with(fn, "i2c")) { char cur_dir[PATH_MAX]; snprintf(cur_dir, PATH_MAX, "%s/%s", dirname, fn); char * name = read_sysfs_attr_w_default(cur_dir, "name","", false); rpt_vstring(depth, "I2C device: %-10s name: %s", fn, name); free(name); } } /** Reports the device identifiers in directory /sys/bus/pci/devices/nnnn:nn:nn.n * * Note that the devices/nnnn:nn:nn.n under /sys/bus/pci always has * vendor/device etc from modalias extracted into individual attributes. * Other device subdirectories do not necessarily have these attributes. * * \param sysfs_device_dir always /sys/bus/pci/devices/nnnn:nn:nn.n * \param depth logical indentation depth */ void report_device_identification(char * sysfs_device_dir, int depth) { bool debug = false; DBGMSF(debug, "sysfs_device_dir: %s", sysfs_device_dir); int d1 = depth+1; DBGMSF(debug, "Reading device ids from individual attribute files..."); Device_Ids dev_ids = read_device_ids1(sysfs_device_dir); #ifdef ALTERNATIVE // works, pick one DBGMSF(debug, "Reading device ids by parsing modalias attribute..."); Device_Ids dev_ids2 = read_device_ids2(sysfs_device_dir); assert(dev_ids.vendor_id == dev_ids2.vendor_id); assert(dev_ids.device_id == dev_ids2.device_id); assert(dev_ids.subvendor_id == dev_ids2.subvendor_id); assert(dev_ids.subdevice_id == dev_ids2.subdevice_id); #endif bool pci_ids_ok = devid_ensure_initialized(); if (pci_ids_ok) { Pci_Usb_Id_Names names = devid_get_pci_names( dev_ids.vendor_id, dev_ids.device_id, dev_ids.subvendor_id, dev_ids.subdevice_id, 4); if (!names.vendor_name) names.vendor_name = "unknown vendor"; if (!names.device_name) names.device_name = "unknown device"; rpt_vstring(d1,"Vendor: x%04x %s", dev_ids.vendor_id, names.vendor_name); rpt_vstring(d1,"Device: x%04x %s", dev_ids.device_id, names.device_name); if (names.subsys_or_interface_name) rpt_vstring(d1,"Subvendor/Subdevice: %04x/%04x %s", dev_ids.subvendor_id, dev_ids.subdevice_id, names.subsys_or_interface_name); } else { rpt_vstring(d1,"Unable to find pci.ids file for name lookup."); rpt_vstring(d1,"Vendor: %04x ", dev_ids.vendor_id); rpt_vstring(d1,"Device: %04x ", dev_ids.device_id); rpt_vstring(d1,"Subvendor/Subdevice: %04x/%04x ", dev_ids.subvendor_id, dev_ids.subdevice_id); } } /** Returns the name for video class ids. * * Hardcoded because device_ids_util.c does not process the class * information that is maintained in file pci.ids. * * \param class_id * \return class name, "" if not a display controller class */ static char * video_device_class_name(unsigned class_id) { char * result = ""; switch(class_id >> 8) { case 0x0300: result = "VGA compatible controller"; break; case 0x0301: result = "XGA compatible controller"; break; case 0x0302: result = "3D controller"; break; case 0x0380: result = "Display controller"; break; default: if (class_id >> 16 == 0x03) result = "Unspecified display controller"; } return result; } /** Process attributes of a /sys/bus/pci/devices/nnnn:nn:nn.n directory.\ * * Ignores non-video devices, i.e. devices whose class does not begin * with x03. * * Called by #query_card_and_driver_using_sysfs() via #dir_foreach() * * \param dirname always /sys/bus/pci/devices * \param fn nnnn:nn:nn.n PCI device path * \param accum pointer to accumulator struct, may be NULL * \param depth logical indentation depth * * \remark * Adds detected driver to list of detected drivers */ void each_video_pci_device( const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGMSF(debug, "Starting. dirname=%s, fn=%s, accumulator=%p", dirname, fn, accumulator); int d1 = depth+1; Env_Accumulator * accum = accumulator; assert(accum && memcmp(accum->marker, ENV_ACCUMULATOR_MARKER, 4) == 0); char cur_dir_name[PATH_MAX]; sprintf(cur_dir_name, "%s/%s", dirname, fn); char * device_class = read_sysfs_attr(cur_dir_name, "class", /*verbose=*/true); // DBGMSF(debug, "cur_dir_name=%s, device_class: %s", cur_dir_name, device_class); if (!device_class) { rpt_vstring(depth, "Unexpected for %s: class not found", cur_dir_name); goto bye; } unsigned class_id = h2uint(device_class); // DBGMSF(debug, "class_id: 0x%08x", class_id); // if (str_starts_with(device_class, "0x03")) { if (class_id >> 16 == 0x03) { bool is_primary_video = false; switch(class_id >> 8) { case 0x0300: is_primary_video=true; break; case 0x0380: break; default: rpt_vstring(depth, "Unexpected class for video device: %s", device_class); } char * boot_vga = read_sysfs_attr_w_default(cur_dir_name, "boot_vga", "-1", false); // DBGMSG("boot_vga: %s", boot_vga); bool boot_vga_flag = (boot_vga && streq(boot_vga, "1")) ; rpt_vstring(depth, "%s video controller at PCI address %s (boot_vga flag is %sset)", (is_primary_video) ? "Primary" : "Secondary", fn, (boot_vga_flag) ? "" : "not "); rpt_vstring(d1, "Device class: x%06x %s", class_id, video_device_class_name(class_id)); report_device_identification(cur_dir_name, depth); // rpt_nl(); // rpt_vstring(d1,"Determining driver name and possibly version..."); char workfn[PATH_MAX]; g_snprintf(workfn, PATH_MAX, "%s/%s", cur_dir_name, "driver"); char resolved_path[PATH_MAX]; // DBGMSF("resulved_path = |%s|", resolved_path); char * rpath = realpath(workfn, resolved_path); if (!rpath) { int errsv = errno; if (errsv == ENOENT) rpt_vstring(d1, "No driver"); else { rpt_vstring(d1, "realpath(%s) returned NULL, errno=%d (%s)", workfn, errsv, linux_errno_name(errsv)); } } else { // printf("realpath returned %s\n", rpath); // printf("%s --> %s\n",workfn, resolved_path); char * rp2 = strdup(rpath); // DBGMSF(debug, "Driver name path: rp2 = rpath = %s", rp2); char * driver_name = g_path_get_basename(rp2); rpt_vstring(d1, "Driver name: %s", driver_name); driver_name_list_add(&accum->driver_list, driver_name); free(rp2); free(driver_name); char driver_module_dir[PATH_MAX]; g_snprintf(driver_module_dir, PATH_MAX, "%s/driver/module", cur_dir_name); // printf("driver_module_dir: %s\n", driver_module_dir); char * driver_version = read_sysfs_attr(driver_module_dir, "version", false); if (driver_version) { rpt_vstring(d1,"Driver version: %s", driver_version); free(driver_version); } else rpt_vstring(d1,"Driver version: Unable to determine"); // list associated I2C devices dir_foreach(cur_dir_name, NULL, each_video_device_i2c, NULL, d1); } free(boot_vga); } else if (str_starts_with(device_class, "0x0a")) { rpt_vstring(depth, "Encountered docking station (class 0x0a) device. dir=%s", cur_dir_name); } free(device_class); bye: DBGMSF(debug, "Done"); return; } /** Process attributes of a /sys/bus/platform/drivers directory * * Only processes entry for driver vc4_v3d. * * Called by #query_card_and_driver_using_sysfs() via #dir_foreach() * * \param dirname always /sys/bus/platform/drivers * \param fn driver name * \param accum pointer to accumulator struct, may be NULL * \param depth logical indentation depth * * \remark * Adds detected driver to list of detected drivers */ void each_arm_driver( const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGMSF(debug, "Starting. dirname=%s, fn=%s, accumulator=%p", dirname, fn, accumulator); Env_Accumulator * accum = accumulator; assert(accumulator && memcmp(accum->marker, ENV_ACCUMULATOR_MARKER, 4) == 0); if (streq(fn, "vc4_v3d")) { const char * driver_name = fn; rpt_vstring(depth, "Driver name: %s", driver_name); driver_name_list_add(&accum->driver_list, driver_name); } DBGMSF(debug, "Done"); } /** Depending on architecture, examines /sys/bus/pci/devices or * /sub/bus/platform/drivers. * * \accum accum * * \remark * Updates list of detected drivers, accum->driver_list */ void query_card_and_driver_using_sysfs(Env_Accumulator * accum) { bool debug = false; DBGMSF(debug, "Starting. accum=%p", accum); rpt_vstring(0,"Obtaining card and driver information from /sys..."); if (accum->is_arm) { DBGMSF(debug, "Machine architecture is %s. Skipping /sys/bus/pci checks.", accum->architecture); char * platform_drivers_dir_name = "/sys/bus/platform/drivers"; dir_foreach(platform_drivers_dir_name, /*fn_filter*/ NULL, each_arm_driver, accum, 0); } else { char * pci_devices_dir_name = "/sys/bus/pci/devices"; // each entry in /sys/bus/pci/devices is a symbolic link dir_foreach(pci_devices_dir_name, /*fn_filter*/ NULL, each_video_pci_device, accum, 0); } DBGMSF(debug, "Done"); } // end query_card_and_driver_using_sysfs() section /** For each driver module name known to be relevant, checks /sys to * see if it is loaded. */ void query_loaded_modules_using_sysfs() { rpt_vstring(0,"Testing if modules are loaded using /sys..."); // known_video_driver_modules // other_driver_modules char ** pmodule_name = get_known_video_driver_module_names(); char * curmodule; int ndx; for (ndx=0; (curmodule=pmodule_name[ndx]) != NULL; ndx++) { bool is_loaded = is_module_loaded_using_sysfs(curmodule); // DBGMSF(debug, "is_loaded=%d", is_loaded); rpt_vstring(0," Module %-16s is %sloaded", curmodule, (is_loaded) ? "" : "NOT "); } pmodule_name = get_other_driver_module_names(); for (ndx=0; (curmodule=pmodule_name[ndx]) != NULL; ndx++) { bool is_loaded = is_module_loaded_using_sysfs(curmodule); rpt_vstring(0," Module %-16s is %sloaded", curmodule, (is_loaded) ? "" : "NOT "); } } /** Examines a single /sys/bus/i2c/devices/i2c-N directory. * * Called by #dir_foreach() from #query_sys_bus_i2c() * * \param dirname always /sys/bus/i2c/devices * \param fn i2c-0, i2c-1, ... (n. these are symbolic links) * \param accumulator collects environment information * \param depth logical indentation depth * * \remark * Adds current bus number to **accumulator->sys_bus_i2c_device_numbers */ void each_i2c_device( const char * dirname, // always /sys/bus/i2c/devices const char * fn, // i2c-0, i2c-1, ... void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dirname=%s, fn=%s", dirname, fn); assert(streq(dirname, "/sys/bus/i2c/devices")); Env_Accumulator * accum = accumulator; char cur_dir_name[100]; sprintf(cur_dir_name, "%s/%s", dirname, fn); char * dev_name = read_sysfs_attr(cur_dir_name, "name", true); char buf[106]; snprintf(buf, 106, "%s/name:", cur_dir_name); rpt_vstring(depth, "%-34s %s", buf, dev_name); free(dev_name); int busno = i2c_name_to_busno(fn); if (busno >= 0) { bva_append(accum->sys_bus_i2c_device_numbers, busno); accum->sysfs_i2c_devices_exist = true; } else if (str_ends_with(fn, "-0037")) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ddcci device name: %s", fn); accum->sysfs_ddcci_devices_exist = true; } else { // rpt_vstring(depth, "%-34s Unexpected file name: %s", cur_dir_name, fn); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Ignorable /sys/bus/i2c/devices file name: %s", fn); } DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } /** Examines /sys/bus/i2c/devices * * \param accumulator collects environment information * * \remark * Sets **accumulator->sys_bus_i2c_device_numbers** to sorted * array of detected I2C device numbers. */ void query_sys_bus_i2c(Env_Accumulator * accumulator) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); accumulator->sys_bus_i2c_device_numbers = bva_create(); rpt_vstring(0,"Examining /sys/bus/i2c/devices..."); char * dname = "/sys/bus/i2c"; if (!directory_exists(dname)) { rpt_vstring(1, "Directory not found: %s", dname); } else { char * dname = "/sys/bus/i2c/devices"; accumulator->sysfs_i2c_devices_exist = false; // each entry in /sys/bus/i2c/devices is a symbolic link dir_ordered_foreach(dname, NULL, i2c_compare, each_i2c_device, accumulator, 1); if (!accumulator->sysfs_i2c_devices_exist) rpt_vstring(1, "No i2c devices found in %s", dname); bva_sort(accumulator->sys_bus_i2c_device_numbers); if (accumulator->sysfs_ddcci_devices_exist) { rpt_nl(); rpt_vstring(1, "Device(s) possibly created by driver ddcci found in %s", dname); rpt_vstring(1, "May require option --force-slave-address to recover from EBUSY errors."); } } DBGTRC_DONE(debug, TRACE_GROUP, ""); } void query_sys_amdgpu_parameters(int depth) { const char * parmdir = "/sys/module/drm/holders/amdgpu/parameters"; int d1 = depth; int d2 = depth+1; rpt_vstring(d1, "amdgpu parameters (%s)", parmdir); if (!directory_exists(parmdir)) { rpt_vstring(d2, "Directory not found: %s", parmdir); } else { DIR *dirp; struct dirent *dp; if ((dirp = opendir(parmdir)) == NULL) { int errsv = errno; rpt_vstring(d2, "Couldn't open %s. errno = %d (%s)", parmdir, errsv, linux_errno_name(errsv)); } else { GPtrArray * sorted_names = g_ptr_array_new_with_free_func(g_free); while (true){ dp = readdir(dirp); // per man page, do not free if (!dp) break; if (dp->d_type & DT_REG) { g_ptr_array_add(sorted_names, strdup(dp->d_name)); } } g_ptr_array_sort(sorted_names, indirect_strcmp); for (int ndx = 0; ndx < sorted_names->len; ndx++) { char * fn = g_ptr_array_index(sorted_names, ndx); char * value = read_sysfs_attr(parmdir, fn, /*verbose=*/ false); char n[100]; g_snprintf(n, 100, "%s:", fn); rpt_vstring(d2, "%-20s %s", n, value); free(value); } closedir(dirp); g_ptr_array_free(sorted_names, true); } } } /** Examines /sys/class/drm */ static void insert_drm_xref( int depth, const char * cur_dir_name, const char * i2c_node_name, const Byte * edidbytes) { bool debug = false; DBGMSF(debug, "depth=%d, cur_dir_name=%s, i2c_node_name = %s, edidbytes=%p", depth, cur_dir_name, i2c_node_name, edidbytes); int d2 = depth; assert(cur_dir_name); // i2c_node_name should should always be non-null, but don't assume assert(edidbytes); int drm_busno = i2c_path_to_busno(cur_dir_name); DBGMSF(debug, "drm_busno=%d", drm_busno); Device_Id_Xref * xref = device_xref_find_by_busno(drm_busno); if (!xref) DBGMSG("Unexpected. Bus %d not in xref table", drm_busno); // can we assert that edidbytes != NULL? if (!xref) { // DBGMSG("searching by EDID"); #ifdef SYSENV_TEST_IDENTICAL_EDIDS if (first_edid) { DBGMSG("Forcing duplicate EDID"); edidbytes = first_edid; } #endif xref = device_xref_find_by_edid(edidbytes); if (!xref) { char * tag = device_xref_edid_tag(edidbytes); DBGMSG("Unexpected. EDID ...%s not in xref table", tag); free(tag); } } if (xref) { if (xref->ambiguous_edid) { rpt_vstring(d2, "Multiple displays have same EDID ...%s", xref->edid_tag); rpt_vstring(d2, "drm name, and bus number in device cross reference table may be incorrect"); } xref->sysfs_drm_name = strdup(cur_dir_name); if (i2c_node_name) xref->sysfs_drm_i2c = strdup(i2c_node_name); xref->sysfs_drm_busno = drm_busno; DBGMSF(debug, "sysfs_drm_busno = %d", xref->sysfs_drm_busno); } } static void report_one_connector( const char * dirname, // /drm/cardN const char * simple_fn, // card0-HDMI-1 etc void * data, int depth) { bool debug = false; int d1 = depth+1; int d2 = depth+2; DBGMSF(debug, "Starting. dirname=%s, simple_fn=%s", dirname, simple_fn); assert(dirname); assert(simple_fn); rpt_nl(); rpt_vstring(depth, "Connector: %s", simple_fn); GByteArray * edid_byte_array; char * i2c_subdir_name = NULL; // i2c-N RPT_ATTR_TEXT(d1, NULL, dirname, simple_fn, "enabled"); RPT_ATTR_TEXT(d1, NULL, dirname, simple_fn, "status"); RPT_ATTR_EDID(d1, &edid_byte_array, dirname, simple_fn, "edid"); GET_ATTR_SINGLE_SUBDIR(&i2c_subdir_name, is_i2cN_dir, NULL, dirname, simple_fn); // rpt_vstring(d1, "i2c_device: %s", i2c_subdir_name); if (i2c_subdir_name) { char * node_name = NULL; // e.g. "AMDGPU DM aux hw bus 0" rpt_vstring(d1, "i2c_device: %s", i2c_subdir_name); RPT_ATTR_TEXT(d2, &node_name, dirname, simple_fn, i2c_subdir_name, "name"); if (edid_byte_array) { insert_drm_xref(d2, i2c_subdir_name, node_name, edid_byte_array->data); } free(i2c_subdir_name); free(node_name); } else { rpt_vstring(d2, "No i2c-N subdirectory"); } if (edid_byte_array) g_byte_array_free(edid_byte_array, true); DBGMSF(debug, "Done"); } void query_drm_using_sysfs() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); int depth = 1; int d0 = depth; rpt_nl(); char * dname = #ifdef TARGET_BSD "/compat/linux/sys/class/drm"; #else "/sys/class/drm"; #endif rpt_vstring(d0, "*** Examining %s ***", dname); dir_filtered_ordered_foreach( dname, is_card_connector_dir, // filter function NULL, // ordering function report_one_connector, NULL, // accumulator depth); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Functions for probing /sys // void show_top_level_sys_entries(int depth) { rpt_label(depth, "*** Character device major numbers of interest: ***"); char * names[] = {"i2c", "drm", "ddcci", "aux", "vfio", NULL}; GPtrArray * filtered_proc_devices = g_ptr_array_new(); read_file_with_filter( filtered_proc_devices, "/proc/devices", names, false, // ignore_case, 0, // no limit false); // free strings for (int ndx = 0; ndx < filtered_proc_devices->len; ndx++) { rpt_label(depth+1, g_ptr_array_index(filtered_proc_devices, ndx)); } rpt_nl(); rpt_label(depth, "*** Top Level I2C Related Nodes ***"); rpt_nl(); char * cmds[] = { #ifdef NOT_USEFUL "ls -l /sys/bus/pci_express/devices", "ls -l /sys/devices/pci*", "ls -l /sys/class/pci*", // pci_bus, pci_epc #endif "ls -l /sys/bus/pci/devices", "ls -l /sys/bus/i2c/devices", "ls -l /sys/bus/ddcci/devices", "ls -l /sys/bus/platform/devices", // not symbolic links "ls -l /sys/class/drm*", // drm, drm_dp_aux_dev "ls -l /sys/class/i2c*", // i2c, i2c-adapter, i2c-dev "ls -l /sys/class/backlight", "ls -l /sys/class/vfio*", NULL }; int ndx = 0; while ( cmds[ndx] ) { rpt_vstring(1, "%s ...", cmds[ndx]); execute_shell_cmd_rpt(cmds[ndx],depth + 2); ndx++; rpt_nl(); } for (int ndx = 0; ndx < filtered_proc_devices->len; ndx++) { char * name = NULL; int number = 0; if (sscanf(g_ptr_array_index(filtered_proc_devices, ndx), "%d %ms", &number, &name) == 2) { // allow for pathological case of invalid /proc data // DBGMSG("number = %d, name = %s"show_top_level_sys_entries, number, name); char cmd[100]; snprintf(cmd, 100, "ls -l /sys/dev/char/%d:*", number); // DBGMSG("cmd: %s", cmd); rpt_vstring(depth+1, "Char major: %d %s", number, name); execute_shell_cmd_rpt(cmd,depth + 2); free(name); rpt_nl(); } } g_ptr_array_free(filtered_proc_devices, true); } /** Master function for dumping /sys directory */ void dump_sysfs_i2c(Env_Accumulator * accum) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); rpt_nl(); rpt_label(0, "****** Dumping sysfs i2c entries ******"); rpt_nl(); show_top_level_sys_entries(0); // dump_original_sys_scans(); // dump_simplified_sys_bus_pci(0); dump_detailed_sys_bus_pci(0); // keep? rpt_nl(); rpt_label(0, "*** Scan /sys/bus/i2c ***"); rpt_nl(); dbgrpt_sys_bus_i2c(1); rpt_nl(); consolidated_i2c_sysfs_report(0); rpt_nl(); rpt_label(0, "*** All sysfs class attributes ***"); execute_shell_cmd("find /sys/devices -name class | xargs grep \".*\""); rpt_nl(); report_drm_connector_states(0); if (accum->is_arm) { rpt_label(0,"*** Extended dump of sysfs video devices for ARM architecture ***"); rpt_nl(); GPtrArray * video_devices = get_video_adapter_devices(); #ifdef OLD GPtrArray * video_devices = execute_shell_cmd_collect( "find /sys/devices -name class | xargs grep -il 0x03 | xargs dirname"); // "find /sys/devices -name class | xargs grep -il 0x03 | xargs dirname | xargs ls -lR"); #endif if (video_devices->len == 0) { rpt_vstring(1,"No devices with class 0x03nnnn found."); } else { rpt_vstring(0, "Display devices: (class 0x03nnnn)"); for (int ndx = 0; ndx < video_devices->len; ndx++) { char * dirname = g_ptr_array_index(video_devices, ndx); rpt_vstring(2, "%s", dirname); char * s = g_strdup_printf("ls -lR %s", dirname); execute_shell_cmd(s); free(s); } } // g_ptr_array_set_free_func(video_devices,free); //redundant g_ptr_array_free(video_devices,true); } rpt_label(0,"*** Examining displaylink related attributes ***"); rpt_nl(); GPtrArray * displaylink_devices = execute_shell_cmd_collect( "find /sys -name \"evdi*\""); if (displaylink_devices->len == 0) { rpt_vstring(1,"No displaylink devices found."); } else { rpt_vstring(0, "Displaylink devices:"); for (int ndx = 0; ndx < displaylink_devices->len; ndx++) { char * dirname = g_ptr_array_index(displaylink_devices, ndx); rpt_vstring(2, "%s", dirname); char * s = g_strdup_printf("ls -lR %s", dirname); execute_shell_cmd(s); free(s); } } // g_ptr_array_set_free_func(displaylink_devices,free); //redundant g_ptr_array_free(displaylink_devices,true); DBGTRC_DONE(debug, TRACE_GROUP, ""); } void init_query_sysenv_sysfs() { RTTI_ADD_FUNC(query_drm_using_sysfs); RTTI_ADD_FUNC(query_sys_bus_i2c); RTTI_ADD_FUNC(each_i2c_device); RTTI_ADD_FUNC(dump_sysfs_i2c); init_query_detailed_bus_pci_devices(); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_xref.c0000644000175000001440000002272514441414365015560 /** @file query_sysenv.xref.h * * Table cross-referencing the multiple ways that a display is referenced * in various Linux subsystems. */ // Copyright (C) 2017-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" /** \endcond */ #include "query_sysenv_xref.h" /** Collection of #Device_Id_Xref */ static GPtrArray * device_xref = NULL; static bool i2c_bus_scan_complete = false; /** Initializes the device cross reference table */ void device_xref_init() { device_xref = g_ptr_array_new(); } static void device_xref_mark_duplicate_edid(Byte * raw_edid) { assert(i2c_bus_scan_complete); for (int ndx = 0; ndx < device_xref->len; ndx++) { Device_Id_Xref * cur = g_ptr_array_index(device_xref, ndx); assert( memcmp(cur->marker, DEVICE_ID_XREF_MARKER, 4) == 0); if ( memcmp(cur->raw_edid, raw_edid, 128) == 0 ) { cur->ambiguous_edid = true; } } } static int device_xref_count_by_edid(Byte * raw_edid) { int ct = 0; assert(i2c_bus_scan_complete); for (int ndx = 0; ndx < device_xref->len; ndx++) { Device_Id_Xref * cur = g_ptr_array_index(device_xref, ndx); assert( memcmp(cur->marker, DEVICE_ID_XREF_MARKER, 4) == 0); if ( memcmp(cur->raw_edid, raw_edid, 128) == 0 ) { ct++; } } return ct; } // A truly dumb algorithm, but the size of device_xref is tiny static void device_xref_mark_duplicate_edids() { int ct = device_xref->len; for (int start = 0; start < ct-1; start++) { Device_Id_Xref * cur_xref = g_ptr_array_index(device_xref, start); int dupct = device_xref_count_by_edid(cur_xref->raw_edid); if (dupct > 1) { device_xref_mark_duplicate_edid(cur_xref->raw_edid); } } } /** Indicates that scanning by I2C device number is complete, * and triggers check for duplicate EDIDs. */ void device_xref_set_i2c_bus_scan_complete() { bool debug = false; // DBGMSG("Setting i2c_bus_scan_complete"); i2c_bus_scan_complete = true; device_xref_mark_duplicate_edids(); if (debug) { DBGMSG("After checking for duplicate EDIDs:"); device_xref_report(3); } } #ifdef UNUSED bool device_xref_i2c_bus_scan_complete() { return i2c_bus_scan_complete; } #endif /** Finds an existing cross-reference entry with the specified * 128 byte EDID value. * * \param raw_edid pointer to 128 byte EDID * \return pointer to existing #Device_Id_Xref,\n * NULL if not found * * \remark If multiple monitors have the same EDID (e.x. identical LG display monitors) * returns the first entry in the cross-reference list */ Device_Id_Xref * device_xref_find_by_edid(const Byte * raw_edid) { assert(i2c_bus_scan_complete); Device_Id_Xref * result = NULL; for (int ndx = 0; ndx < device_xref->len; ndx++) { Device_Id_Xref * cur = g_ptr_array_index(device_xref, ndx); assert( memcmp(cur->marker, DEVICE_ID_XREF_MARKER, 4) == 0); if ( memcmp(cur->raw_edid, raw_edid, 128) == 0 ) { result = cur; break; } } return result; } /** Returns the last 4 bytes of a 128-byte EDID as a * hexadecimal string. * * @param raw_edid pointer to EDID * @return bytes 124..127 as a string, caller must free */ char * device_xref_edid_tag(const Byte * raw_edid) { return hexstring2(raw_edid+124, 4, NULL, true, NULL, 0); } /** Creates a new #Device_Id_Xref with the specified EDID value. * * \param raw_edid pointer 128 byte EDID * \return pointer to newly allocated #Device_Id_Xref * * \todo merge into #device_xref_new_with_busno() */ static Device_Id_Xref * device_xref_new(Byte * raw_edid) { Device_Id_Xref * xref = calloc(1, sizeof(Device_Id_Xref)); memcpy(xref->marker, DEVICE_ID_XREF_MARKER, 4); memcpy(xref->raw_edid, raw_edid, 128); xref->edid_tag = device_xref_edid_tag(xref->raw_edid); xref->i2c_busno = -1; // #ifdef ALTERNATIVE xref->sysfs_drm_busno = -1; // #endif // DBGMSG("Created xref %p with tag: %s", xref, xref->edid_tag); return xref; } #ifdef OLD /** Returns the #Device_Id_Xref for the specified EDID value. * If the #Device_Id_Xref does not already exist, it is created * * \param raw_edid pointer 128 byte EDID * \return pointer to #Device_Id_Xref */ Device_Id_Xref * device_xref_get(Byte * raw_edid) { if (!device_xref) device_xref_init(); Device_Id_Xref * xref = device_xref_find_by_edid(raw_edid); if (!xref) { xref = device_xref_new(raw_edid); g_ptr_array_add(device_xref, xref); } // else // DBGMSG("Found Device_Id_Xref %p for edid ...%s", xref, xref->edid_tag); return xref; } #endif /** Find the #Device_Id_Xref for the specified I2C bus number * * \param busno I2C bus number * \return device identification cross-reference entry,\n * NULL if not found */ Device_Id_Xref * device_xref_find_by_busno(int busno) { bool debug = false; Device_Id_Xref * result = NULL; for (int ndx = 0; ndx < device_xref->len; ndx++) { Device_Id_Xref * cur = g_ptr_array_index(device_xref, ndx); assert( memcmp(cur->marker, DEVICE_ID_XREF_MARKER, 4) == 0); if ( cur->i2c_busno == busno) { result = cur; break; } } if (debug) { if (result) DBGMSG("busno = %d, returning Device_Id_Xref %p for EDID ...%s", busno, result, result->edid_tag); else DBGMSG("busno = %d, not found", busno); } return result; } /** Creates a new #Device_Id_Xref with the specified bus number and EDID value. * * \param busno I2C bus number * \param raw_edid pointer to 128 byte EDID * \return pointer to newly allocated #Device_Id_Xref */ Device_Id_Xref * device_xref_new_with_busno(int busno, Byte * raw_edid) { assert(busno >= 0); assert(raw_edid); bool debug = false; Device_Id_Xref * xref = NULL; xref = device_xref_find_by_busno(busno); assert(!xref); xref = device_xref_new(raw_edid); xref->i2c_busno = busno; xref->udev_busno = -1; g_ptr_array_add(device_xref, xref); DBGMSF(debug, "Created xref %p with busno %d, EDID tag: ...%s", xref, xref->i2c_busno, xref->edid_tag); return xref; } /** Reports the device identification cross-reference table. * * \param depth logical indentation depth */ void device_xref_report(int depth) { int d1 = depth+1; int d2 = depth+2; rpt_nl(); rpt_vstring(depth, "Device Identifier Cross Reference Report"); // rpt_nl(); // rpt_vstring(d1, "EDID Busno Xrandr DRM Udev name Udev Path"); for (int ndx = 0; ndx < device_xref->len; ndx++) { Device_Id_Xref * xref = g_ptr_array_index(device_xref, ndx); assert( memcmp(xref->marker, DEVICE_ID_XREF_MARKER, 4) == 0); Parsed_Edid * parsed_edid = create_parsed_edid(xref->raw_edid); #ifdef NO rpt_vstring(d1, "...%s %2d %-10s %-10s %-30s %s", xref->edid_tag, xref->i2c_busno, xref->xrandr_name, xref->drm_connector_name, xref->udev_name, xref->udev_syspath); if (parsed_edid) { rpt_vstring(d2, "Mfg: %s", parsed_edid->mfg_id); rpt_vstring(d2, "Model: %s", parsed_edid->model_name); rpt_vstring(d2, "SN: %s", parsed_edid->serial_ascii); } #endif rpt_nl(); rpt_vstring(d1, "/dev/i2c busno: %d", xref->i2c_busno); if (parsed_edid) { rpt_vstring(d2, "EDID: ...%s Mfg: %-3s Model: %-13s SN: %-13s", xref->edid_tag, parsed_edid->mfg_id, parsed_edid->model_name, parsed_edid->serial_ascii); rpt_vstring(d2, " Product number: %d, binary SN: %d", parsed_edid->product_code, parsed_edid->serial_binary); free_parsed_edid(parsed_edid); } else rpt_vstring(d2, "EDID: ...%s", xref->edid_tag); // if (xref->i2c_busno == -1) // rpt_vstring(d2, "/dev/i2c busno: Not found"); // else // rpt_vstring(d2, "/dev/i2c busno: %d", xref->i2c_busno); rpt_vstring(d2, "XrandR output: %s", xref->xrandr_name); rpt_vstring(d2, "DRM connector: %s", xref->drm_connector_name); // rpt_vstring(d2, "DRM path: %s", xref->drm_device_path); rpt_vstring(d2, "UDEV name: %s", xref->udev_name); rpt_vstring(d2, "UDEV syspath: %s", xref->udev_syspath); rpt_vstring(d2, "UDEV busno: %d", xref->udev_busno); rpt_vstring(d2, "sysfs drm path: %s", xref->sysfs_drm_name); // pick one way or the other rpt_vstring(d2, "sysfs drm I2C: %s", xref->sysfs_drm_i2c); // #ifdef ALTERNATIVE if (xref->sysfs_drm_busno == -1) rpt_vstring(d2, "sysfs drm busno: Unknown"); else rpt_vstring(d2, "sysfs drm busno: %d", xref->sysfs_drm_busno); // #endif rpt_vstring(d2, "ambiguous EDID: %s", sbool(xref->ambiguous_edid)); if (xref->ambiguous_edid) { rpt_vstring(d2, "WARNING: Multiple displays have same EDID. XrandR and DRM values may be incorrect"); } // TEMP to screen scrape the EDID: // if (xref->raw_edid) { // char * s = hexstring2(xref->raw_edid, 128, // NULL, true, NULL, 0); // puts(s); // free(s); // } } } ddcutil-2.2.0/src/app_sysenv/query_sysenv_usb.c0000644000175000001440000003103314545020413015365 /** @file query_sysenv_usb.c * Probe the USB environment */ // Copyright (C) 2016-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include // #define _GNU_SOURCE 1 // for function group_member /** \cond */ #include #include #include #include #include #include #include #include #include /** \endcond */ #include "util/file_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_util.h" #include "util/udev_util.h" #include "util/udev_usb_util.h" #include "usb_util/hiddev_reports.h" #include "usb_util/hiddev_util.h" #include "usb_util/hidraw_util.h" #include "usb_util/libusb_util.h" #include "usb_util/usb_hid_common.h" #include "base/core.h" #include "base/ddc_errno.h" #include "usb/usb_displays.h" #include "query_sysenv_usb.h" static bool is_hid_monitor_rdesc(const char * fn) { bool debug = false; bool result = false; char * first_line = file_get_first_line(fn, /*verbose=*/ true); DBGMSF(debug, "First line: %s", first_line); if ( first_line && str_starts_with( first_line, "05 80")) result = true; DBGMSF(debug, "fn=%s, returning: %s", fn, sbool(result)); return result; } /* Probe using the UHID debug interface in /sys/kernel/debug/hid * * For each HID device that's a monitor, displays the HID Report Descriptor. * * Arguments: * depth logical indentation depth * * Returns: nothing */ static void probe_uhid(int depth) { int d1 = depth+1; int d2 = depth+2; bool debug = false; DBGMSF(debug, "Starting"); struct dirent * ep; char * dirname = "/sys/kernel/debug/hid/"; DIR * dp; dp = opendir(dirname); if (!dp) { int errsv = errno; rpt_vstring(depth, "Unable to open directory %s: %s", dirname, strerror(errsv)); } else { while ( (ep = readdir(dp))) { // puts(ep->d_name); char fqfn[PATH_MAX]; if (!streq(ep->d_name, ".") && !streq(ep->d_name, "..") ) { // file names look like: "0003:0424:3328:004D" // field 1: ? // field 2: vid // field 3: pid // field 4: appears to be a sequence number of some sort // increases with each call to ddcutil env -v snprintf(fqfn, PATH_MAX, "%s%s/rdesc", dirname, ep->d_name); // puts(fqfn); #ifdef FAILS puts(ep->d_name); printf("(%s) strlen(d_name) = %ld\n", __func__, strlen(ep->d_name)); uint16_t vid, pid, x, seq = 0; int ct = sscanf(ep->d_name, "%hX:%hX:%hX:%hX", &x, &vid, &pid, &seq); if (ct != 2) printf("(%s) sscanf failed, ct = %d\n", __func__, ct); else printf("(%s) sscanf ok, vid=0x%04x, pid=0x%04x\n", __func__, vid, pid); printf("(%s) x=0x%04x, vid=0x%04x, pid=0x%04x, seq=0x%04x\n", __func__,x,vid,pid,seq); // returns ct = 3, seq is unset, why? #endif char * endptr; uint16_t vid = (uint16_t) strtoul(ep->d_name+5, &endptr, 16); uint16_t pid = (uint16_t) strtoul(ep->d_name+10, &endptr, 16); bool is_monitor = false; if (deny_hid_monitor_by_vid_pid(vid, pid)) { rpt_vstring(d1, "Device ignored by vid.pid %d.%d", vid, pid); } else { is_monitor = is_hid_monitor_rdesc(fqfn); if (!is_monitor) { is_monitor = force_hid_monitor_by_vid_pid(vid, pid); } if (is_monitor) { rpt_nl(); rpt_vstring(d1, "%s:", fqfn); rpt_file_contents(fqfn, /*verbose=*/true, d2); } } } } closedir(dp); } DBGMSF(debug, "Done"); } /* Probe using the hiddev API * * Arguments: * depth logical indentation depth * * Returns: nothing */ static void probe_hiddev(int depth) { int d1 = depth+1; int rc; rpt_label(depth, "hiddev device names found in file system:"); GPtrArray * hiddev_devices = get_hiddev_device_names_using_filesys(); for (int ndx = 0; ndx < hiddev_devices->len; ndx++) { rpt_vstring(d1, "%s", (char *) g_ptr_array_index(hiddev_devices,ndx)); } g_ptr_array_free(hiddev_devices, true); rpt_label(depth, "hiddev device names found in udev:"); hiddev_devices = get_hiddev_device_names_using_udev(); for (int ndx = 0; ndx < hiddev_devices->len; ndx++) { rpt_vstring(d1, "%s", (char *) g_ptr_array_index(hiddev_devices,ndx)); } rpt_vstring(depth, "Examining hiddev devices reported by udev..."); // rpt_vstring(0, "Checking for USB HID devices using hiddev..."); // GPtrArray * hiddev_devices = get_hiddev_device_names(); rpt_vstring(depth, "Found %d USB HID devices.", hiddev_devices->len); for (int devndx=0; devndxlen; devndx++) { rpt_nl(); errno=0; char * curfn = g_ptr_array_index(hiddev_devices,devndx); if (!is_possible_monitor_by_hiddev_name(curfn)) { rpt_vstring(depth, "Device %s is not a HID device or is a mouse or keyboard. Skipping", curfn); } else { int fd = usb_open_hiddev_device(curfn, CALLOPT_RDONLY); // do not emit error msg if (fd < 0) { // fd is -errno rpt_vstring(depth, "Unable to open device %s: %s", curfn, strerror(errno)); Usb_Detailed_Device_Summary * devsum = lookup_udev_usb_device_by_devname(curfn, true); if (devsum) { // rpt_vstring(d1, "Detailed device summary for testing: "); // report_usb_detailed_device_summary(devsum, d1+1); rpt_vstring(d1, "USB bus %s, device %s, vid:pid: %s:%s - %s:%s", devsum->busnum_s, devsum->devnum_s, devsum->vendor_id, devsum->product_id, devsum->vendor_name, devsum->product_name); free_usb_detailed_device_summary(devsum); } } else { char * cgname = get_hiddev_name(fd); struct hiddev_devinfo dev_info; errno = 0; rc = ioctl(fd, HIDIOCGDEVINFO, &dev_info); if (rc != 0) { rpt_vstring(d1, "Device %s, unable to retrieve information: %s", curfn, strerror(errno)); } else { char dev_summary[200]; snprintf(dev_summary, 200, "Device %s, devnum.busnum: %d.%d, vid:pid: %04x:%04x - %s", curfn, dev_info.busnum, dev_info.devnum, dev_info.vendor, dev_info.product & 0xffff, cgname); rpt_vstring(depth, "%s", dev_summary); bool b0 = is_hiddev_monitor(fd); if (b0) rpt_vstring(d1, "Identifies as a USB HID monitor"); else { rpt_vstring(d1, "Not a USB HID monitor"); b0 = force_hiddev_monitor(fd); if (b0) rpt_vstring(d1, "Device vid/pid matches exception list. Forcing report for device.\n"); } if (get_output_level() >= DDCA_OL_VERBOSE) { if (b0) { char * simple_devname = strstr(curfn, "hiddev"); Udev_Usb_Devinfo * dinfo = get_udev_usb_devinfo("usbmisc", simple_devname); if (dinfo) { // report_hidraw_devinfo(dinfo, d2); rpt_vstring( d1,"Busno:Devno as reported by get_udev_usb_devinfo() for %s: %03d:%03d", simple_devname, dinfo->busno, dinfo->devno); free(dinfo); } else rpt_vstring(d1, "Error getting busno:devno using get_udev_usb_devinfo()"); dbgrpt_hiddev_device_by_fd(fd, d1); } } if (b0) { Buffer * edid_buffer = hiddev_get_edid(fd); if (edid_buffer) { Parsed_Edid * parsed_edid = create_parsed_edid2(edid_buffer->bytes, "USB"); // copies bytes if (!parsed_edid) { rpt_label(d1, "get_hiddev_edid() returned invalid EDID"); // if debug or verbose, dump the bad edid ?? // if (debug || get_output_level() >= OL_VERBOSE) { // } } else { report_parsed_edid(parsed_edid, /*verbose*/ true, d1); free_parsed_edid(parsed_edid); } } else { rpt_label(d1, "Unable to read EDID using hiddev"); } } } free(cgname); } close(fd); } } // n. free function was set at allocation time g_ptr_array_free(hiddev_devices, true); } /** Master function to query USB aspects of the system environment */ void query_usbenv() { DDCA_Output_Level output_level = get_output_level(); rpt_label(0, "The following tests probe for monitors that use USB for VCP communication..."); rpt_nl(); rpt_vstring(0, "Checking for USB connected monitors..."); rpt_nl(); rpt_vstring(1, "Using lsusb to summarize USB devices..."); execute_shell_cmd_rpt("lsusb|sort", 2); rpt_nl(); rpt_vstring(1, "USB device topology..."); execute_shell_cmd_rpt("lsusb -t", 2); rpt_nl(); if (output_level >= DDCA_OL_VERBOSE) { rpt_vstring(1, "libusb verbose report..."); execute_shell_cmd_rpt("lsusb -v", 2); rpt_nl(); } rpt_vstring(1, "Listing /dev/usb..."); execute_shell_cmd_rpt("ls -l /dev/usb", 2); rpt_nl(); rpt_vstring(1, "Listing /dev/hiddev*..."); execute_shell_cmd_rpt("ls -l /dev/hiddev*", 2); rpt_nl(); rpt_vstring(1, "Listing /dev/bus/usb..."); execute_shell_cmd_rpt("ls -l /dev/bus/usb", 2); rpt_nl(); rpt_vstring(1, "Listing /dev/hidraw*..."); execute_shell_cmd_rpt("ls -l /dev/hidraw*", 2); rpt_nl(); rpt_vstring(1, "Searching /sys for hiddev* entries..."); execute_shell_cmd_rpt("find /sys -name \"hiddev*\"", 2); rpt_nl(); rpt_vstring(1, "Searching /sys for hidraw* entries..."); execute_shell_cmd_rpt("find /sys -name \"hidraw*\"", 2); rpt_nl(); if (output_level >= DDCA_OL_VERBOSE) { char * subsys_name = "usbmisc"; rpt_nl(); rpt_vstring(0, "Probing USB HID devices using udev, susbsystem %s...", subsys_name); probe_udev_subsystem(subsys_name, /*show_usb_parent=*/ true, 1); subsys_name = "hidraw"; rpt_nl(); rpt_vstring(0, "Probing USB HID devices using udev, susbsystem %s...", subsys_name); probe_udev_subsystem(subsys_name, /*show_usb_parent=*/ true, 1); } #ifdef DISABLE if (output_level >= DDCA_OL_VERBOSE) { // currently an overwhelming amount of information - need to display // only possible HID connected monitors rpt_nl(); rpt_vstring(0, "Probing possible HID monitors using libusb..."); probe_libusb(/*possible_monitors_only=*/ true, /*depth=*/ 1); rpt_nl(); rpt_vstring(0, "Checking for USB connected monitors on /dev/hidraw* ..."); probe_hidraw( true, // possible_monitors_only 1); // logical indentation depth // printf("\nProbing using hidapi...\n"); // don't use. wipes out /dev/hidraw and /dev/usb/hiddev devices it opens // no addional information. Feature values are returned as with libusb - // leading byte is report number // note that probe_hidapi() tests all possible report numbers, not just those // listed in the report descriptor. Found some additional reports in the // vendor specific range on the Apple Cinema display // probe_hidapi(1); } #endif rpt_nl(); rpt_vstring(0, "Checking for USB HID devices using hiddev..."); probe_hiddev(1); rpt_nl(); rpt_vstring(0, "Checking for USB HID Report Descriptors in /sys/kernel/debug/hid..."); probe_uhid(1); rpt_nl(); rpt_vstring(0, "Checking for USB connected monitors complete"); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_drm.c0000644000175000001440000007214414754153540015400 /** @file query_drm_sysenv.c * * drm reporting for the environment command */ // Copyright (C) 2017-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later // #define _GNU_SOURCE /** \cond */ #include #include #include #include #include #include #include #include #include #include // NO. We want the versions in /usr/include/libdrm #ifdef NO #include #include #endif #include "util/drm_common.h" #include "util/edid.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/libdrm_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "base/core.h" #include "base/linux_errno.h" /** \endcond */ #include "query_sysenv_base.h" #include "query_sysenv_xref.h" #include "query_sysenv_drm.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_ENV; #ifdef REF // local copy for reference #define DRM_BUS_PCI 0 typedef struct _drmPciBusInfo { uint16_t domain; uint8_t bus; uint8_t dev; uint8_t func; } drmPciBusInfo, *drmPciBusInfoPtr; typedef struct _drmPciDeviceInfo { uint16_t vendor_id; uint16_t device_id; uint16_t subvendor_id; uint16_t subdevice_id; uint8_t revision_id; } drmPciDeviceInfo, *drmPciDeviceInfoPtr; typedef struct _drmDevice { char **nodes; /* DRM_NODE_MAX sized array */ int available_nodes; /* DRM_NODE_* bitmask */ int bustype; union { drmPciBusInfoPtr pci; } businfo; union { drmPciDeviceInfoPtr pci; } deviceinfo; } drmDevice, *drmDevicePtr; extern int drmGetDevice(int fd, drmDevicePtr *device); extern void drmFreeDevice(drmDevicePtr *device); #endif #ifdef UNUSED // can't find basename, roll our own char * basename0(char * fn) { char * result = NULL; if (fn) { int l = strlen(fn); if (l == 0) result = fn; else { char * p = fn+(l-1); while (*p != '/') { if (p == fn) { break; } p--; } result = (p == fn) ? p : p+1;; } } return result; } #endif static void report_drmVersion(drmVersion * vp, int depth) { rpt_vstring(depth, "Version: %d.%d.%d", vp->version_major, vp->version_minor, vp->version_patchlevel); rpt_vstring(depth, "Driver: %.*s", vp->name_len, vp->name); rpt_vstring(depth, "Date: %.*s", vp->date_len, vp->date); rpt_vstring(depth, "Description: %.*s", vp->desc_len, vp->desc); } /* Examines a single open DRM device. * * Arguments: * fd file handle of open DRM device * depth logical indentation depth * * Returns: nothing */ static void probe_open_device_using_libdrm(int fd, int depth) { int d1 = depth+1; int d2 = depth+2; int d3 = depth+3; bool debug = false; int rc; char * busid = NULL; // int errsv; rpt_nl(); DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d", fd); // succeeds if run as root, fails w errno=EACCES(13) if not // but no effect on subsequent failures for nvidia // reviewed code in drm_ioctl.c. ioctl calls would fail with EACCES // if lack of master access were the cause #ifdef NO // fails on suse // rc is ioctl() return code, i.e. 0 or -1 for failure) // if -1, errno is set rc = drmSetMaster(fd); if (rc < 0) rpt_vstring(d1, "drmSetMaster() failed, errno=%s", linux_errno_desc(errno)); rpt_nl(); #endif // if returns NULL, errno is as set from the underlying ioctl() drmVersionPtr vp = drmGetVersion(fd); if (vp) { rpt_vstring(d1, "DRM driver version information:"); report_drmVersion(vp, d2); drmFreeVersion(vp); } else { rpt_vstring(d1, "Error calling drmGetVersion(). errno=%s", linux_errno_desc(errno)); } rpt_nl(); // fills in a hardcoded version number (currently 1.3.0), never fails // only fills in the major, minor, and patchLevel fields, others are always 0 vp = drmGetLibVersion(fd); // rpt_vstring(d1, "DRM library version information:"); // report_drmVersion(vp, d2); rpt_vstring(d1, "DRM library version: %d.%d.%d.", vp->version_major, vp->version_minor, vp->version_patchlevel); drmFreeVersion(vp); rpt_nl(); // returns null string if open() instead of drmOpen(,busid) used to to open // uses successive DRM_IOCTL_GET_UNIQUE calls busid = drmGetBusid(fd); if (busid) { rpt_vstring(d1, "DRM Busid: %s", busid); // drmFreeBusid(busid); // requires root free(busid); } else { rpt_vstring(d1, "Error calling drmGetBusid(). errno=%s", linux_errno_desc(errno)); } char busid2[30] = ""; rpt_nl(); struct _drmDevice * ddev; // gets information about the opened DRM device // returns 0 on success, negative error code otherwise rc = drmGetDevice(fd, &ddev); if (rc < 0) { rpt_vstring(depth, "drmGetDevice() returned %d, interpreted as error code: %s", rc, linux_errno_desc(-rc)); } else { rpt_vstring(d1, "Device information:"); rpt_vstring(d2, "bustype: %d - %s", ddev->bustype, drm_bus_type_name(ddev->bustype)); #ifdef OLD rpt_vstring(d2, "bus,dev,domain,func: %d, %d, %d, %d", ddev->businfo.pci->bus, ddev->businfo.pci->dev, ddev->businfo.pci->domain, ddev->businfo.pci->func); #endif snprintf(busid2, sizeof(busid2), "%s:%04x:%02x:%02x.%d", drm_bus_type_name(ddev->bustype), ddev->businfo.pci->domain, ddev->businfo.pci->bus, ddev->businfo.pci->dev, ddev->businfo.pci->func); rpt_vstring(d2, "domain:bus:device.func: %04x:%02x:%02x.%d", ddev->businfo.pci->domain, ddev->businfo.pci->bus, ddev->businfo.pci->dev, ddev->businfo.pci->func); rpt_vstring(d2, "vendor vid:pid: 0x%04x:0x%04x", ddev->deviceinfo.pci->vendor_id, ddev->deviceinfo.pci->device_id); rpt_vstring(d2, "subvendor vid:pid: 0x%04x:0x%04x", ddev->deviceinfo.pci->subvendor_id, ddev->deviceinfo.pci->subdevice_id); rpt_vstring(d2, "revision id: 0x%04x", ddev->deviceinfo.pci->revision_id); drmFreeDevice(&ddev); } if (strlen(busid2) > 0) { rpt_nl(); // Notes from examining the code for drmCheckModesettingAvailable() // // Checks if a modesetting capable driver has been attached to the pci id // n.b. drmCheckModesettingSupport() takes a busid string as argument, not filename // // Returns 0 if bus id valid and modesetting supported // -EINVAL if invalid bus id // -ENOSYS if no modesetting support // does not set errno // parses busid using sscanf(busid, "pci:%04x:%02x:%02x.%d", &domain, &bus, &dev, &func); rpt_vstring(d1, "Is a modesetting capable driver attached to bus id: %s?", busid2); rpt_vstring(d1,"(calling drmCheckModesettingAvailable())"); rc = drmCheckModesettingSupported(busid2); switch (rc) { case (0): rpt_vstring(d2, "Yes"); break; case (-EINVAL): rpt_vstring(d2, "Invalid bus id (-EINVAL)"); break; case (-ENOSYS): rpt_vstring(d2, "Modesetting not supported (-ENOSYS)"); break; default: rpt_vstring(d2, "drmCheckModesettingSupported() returned undocumented status code %d", rc); } } rpt_nl(); int is_master = drmIsMaster(fd); rpt_vstring(d1, "drmIsMaster() returned %d", is_master); // 1 == true, 0 == false rpt_vstring(d2, "i.e. %s master", (is_master) ? "IS" : "IS NOT"); // int drmrc = drmSetMaster(fd); // if (drmrc != 0) // rpt_vstring(d1, "drmSetMaster failed. drmrc = %d - %s", drmrc, psc_name(-drmrc)); // else // rpt_vstring(d1, "drmSetMaster() succeeded"); #ifdef REF extern drmModePropertyPtr drmModeGetProperty(int fd, uint32_t propertyId); extern void drmModeFreeProperty(drmModePropertyPtr ptr); #endif rpt_nl(); rpt_vstring(d1, "Retrieving DRM resources..."); drmModeResPtr res = drmModeGetResources(fd); DBGMSF(debug,"res=%p", (void*)res); if (!res) { int errsv = errno; rpt_vstring(d1, "Failure retrieving DRM resources, errno=%s", linux_errno_desc(errno)); if (errsv == EINVAL) rpt_vstring(d1,"Driver apparently does not provide needed DRM ioctl calls"); goto bye; } if (debug) report_drmModeRes(res, d2); int edid_prop_id = 0; int subconnector_prop_id = 0; int dpms_prop_id = 0; int link_status_prop_id = 0; int type_prop_id = 0; drmModePropertyPtr edid_prop_ptr = NULL; drmModePropertyPtr subconn_prop_ptr = NULL; drmModePropertyPtr dpms_prop_ptr = NULL; drmModePropertyPtr link_status_prop_ptr = NULL; drmModePropertyPtr type_prop_ptr = NULL; rpt_nl(); rpt_vstring(d1, "Scanning defined properties..."); for (int prop_id = 0; prop_id < 200; prop_id++) { drmModePropertyPtr prop_ptr = drmModeGetProperty(fd, prop_id); if (prop_ptr) { if (debug) report_drm_modeProperty(prop_ptr, d2); else { // TMI summarize_drm_modeProperty(prop_ptr, d2); } // printf("prop_id=%d\n", prop_id); if (streq(prop_ptr->name, "EDID")) { // rpt_vstring(d1, "Found EDID property, prop_id=%d, prop_ptr->prop_id=%u", prop_id, prop_ptr->prop_id); edid_prop_id = prop_id; edid_prop_ptr = prop_ptr; } else if (streq(prop_ptr->name, "subconnector")) { // rpt_vstring(d1, "Found subconnector property, prop_id=%d, prop_ptr->prop_id=%u", prop_id, prop_ptr->prop_id); subconnector_prop_id = prop_id; subconn_prop_ptr = prop_ptr; if (subconn_prop_ptr->flags & DRM_MODE_PROP_ENUM) { // rpt_vstring(d2, "Property values table:"); for (int i = 0; i < subconn_prop_ptr->count_enums; i++) { rpt_vstring(d3, "enum value: %"PRIu64", enum name: %s", subconn_prop_ptr->enums[i].value, subconn_prop_ptr->enums[i].name); } } } else if (streq(prop_ptr->name, "DPMS")) { // rpt_vstring(d1, "Found DPMS property, prop_id=%d, prop_ptr->prop_id=%u", prop_id, prop_ptr->prop_id); dpms_prop_id = prop_id; dpms_prop_ptr = prop_ptr; if (prop_ptr->flags & DRM_MODE_PROP_ENUM) { // rpt_vstring(d2, "Property values table:"); for (int i = 0; i < prop_ptr->count_enums; i++) { rpt_vstring(d3, "enum value: %"PRIu64", enum name: %s", prop_ptr->enums[i].value, prop_ptr->enums[i].name); } } } else if (streq(prop_ptr->name, "link-status")) { // rpt_vstring(d1, "Found link-status property, prop_id=%d, prop_ptr->prop_id=%u", prop_id, prop_ptr->prop_id); link_status_prop_id = prop_id; link_status_prop_ptr = prop_ptr; if (prop_ptr->flags & DRM_MODE_PROP_ENUM) { // rpt_vstring(d2, "Property values table:"); for (int i = 0; i < prop_ptr->count_enums; i++) { rpt_vstring(d3, "enum value: %"PRIu64", enum name: %s", prop_ptr->enums[i].value, prop_ptr->enums[i].name); } } } else if (streq(prop_ptr->name, "type")) { // rpt_vstring(d1, "Found type property, prop_id=%d, prop_ptr->prop_id=%u", prop_id, prop_ptr->prop_id); type_prop_id = prop_id; type_prop_ptr = prop_ptr; if (prop_ptr->flags & DRM_MODE_PROP_ENUM) { // rpt_vstring(d2, "Property values table:"); for (int i = 0; i < prop_ptr->count_enums; i++) { rpt_vstring(d3, "enum value: %"PRIu64", enum name: %s", prop_ptr->enums[i].value, prop_ptr->enums[i].name); } } } else { drmModeFreeProperty(prop_ptr); } } } #ifdef REF extern drmModePropertyBlobPtr drmModeGetPropertyBlob(int fd, uint32_t blob_id); extern void drmModeFreePropertyBlob(drmModePropertyBlobPtr ptr); typedef struct _drmModePropertyBlob { uint32_t id; uint32_t length; void *data; } drmModePropertyBlobRes, *drmModePropertyBlobPtr; #endif rpt_nl(); rpt_vstring(d1, "Scanning connectors..."); for (int i = 0; i < res->count_connectors; ++i) { drmModeConnector * conn = drmModeGetConnector(fd, res->connectors[i]); if (!conn) { rpt_vstring(d1, "Cannot retrieve DRM connector id %d errno=%s", res->connectors[i], linux_errno_desc(errno)); continue; } if (debug) report_drmModeConnector(fd, conn, d1) ; char connector_name[100]; snprintf(connector_name, 100, "%s-%u", drm_connector_type_title(conn->connector_type), conn->connector_type_id); rpt_vstring(d1, "%-20s %u", "connector_id:", conn->connector_id); // rpt_vstring(d2, "%-20s %s-%u", "connector name", connector_type_title(conn->connector_type), // conn->connector_type_id); rpt_vstring(d2, "%-20s %s", "connector name", connector_name); rpt_vstring(d2, "%-20s %d - %s", "connector_type:", conn->connector_type, drm_connector_type_title(conn->connector_type)); rpt_vstring(d2, "%-20s %d", "connector_type_id:", conn->connector_type_id); rpt_vstring(d2, "%-20s %d - %s", "connection:", conn->connection, connector_status_title(conn->connection)); uint32_t encoder_id = conn->encoder_id; // current encoder rpt_vstring(d2, "%-20s %d", "encoder:", encoder_id); drmModeEncoderPtr penc = drmModeGetEncoder(fd, encoder_id); if (penc) { rpt_vstring(d3, "%-20s %d - %s", "encoder type (signal format):", penc->encoder_type, encoder_type_title(penc->encoder_type)); free(penc); } else { rpt_vstring(d2, "Encoder with id %d not found", encoder_id); } for (int ndx = 0; ndx < conn->count_props; ndx++) { if (conn->props[ndx] == edid_prop_id) { rpt_vstring(d2, "EDID property"); uint64_t blob_id = conn->prop_values[ndx]; drmModePropertyBlobPtr blob_ptr = drmModeGetPropertyBlob(fd, blob_id); if (!blob_ptr) { rpt_vstring(d3, "Blob not found"); } else { // printf("blob_ptr->id = %d\n", blob_ptr->id); rpt_vstring(d3, "Raw property blob:"); report_drmModePropertyBlob(blob_ptr, d3); if (blob_ptr->length >= 128) { Parsed_Edid * parsed_edid = create_parsed_edid2(blob_ptr->data, "DRM"); if (parsed_edid) { report_parsed_edid_base( parsed_edid, true, // verbose false, // show_raw d3); free_parsed_edid(parsed_edid); } // DBGMSG("Before xref lookup by edid"); // Initial bus scan by I2C device must already have occurred, // to populate the cross-reference table by bus number // bool complete = device_xref_i2c_bus_scan_complete(); // DBGMSG("i2c bus scan completed: %s", sbool(complete) ); // assert(complete); // device_xref_report(3); Byte * edidbytes = blob_ptr->data; #ifdef SYSENV_TEST_IDENTICAL_EDIDS if (first_edid) { DBGMSG("Forcing duplicate EDID"); edidbytes = first_edid; } #endif // Device_Id_Xref * xref = device_xref_get(blob_ptr->data); Device_Id_Xref * xref = device_xref_find_by_edid(edidbytes); if (xref) { // TODO check for multiple entries with same edid xref->drm_connector_name = g_strdup(connector_name); xref->drm_connector_type = conn->connector_type; // xref->drm_device_path = g_strdup(conn-> if (xref->ambiguous_edid) { rpt_vstring(d3, "Multiple displays have same EDID ...%s", xref->edid_tag); rpt_vstring(d3, "drm connector name and type for this EDID in device cross reference table may be incorrect"); } } else { char * edid_tag = device_xref_edid_tag(edidbytes); DBGMSG("Unexpected: EDID ...%s not found in device cross reference table", edid_tag); free(edid_tag); } } drmModeFreePropertyBlob(blob_ptr); } } else if (conn->props[ndx] == subconnector_prop_id) { rpt_vstring(d2, "Subconnector property"); assert(subconn_prop_ptr); // if subconnector_prop_id found, subconn_prop_ptr must have been set uint32_t enum_value = conn->prop_values[ndx]; // printf("subconnector value: %d, count_enums:%d\n", enum_value, subconn_prop_ptr->count_enums); assert(subconn_prop_ptr->flags & DRM_MODE_PROP_ENUM); bool found = false; for (int i = 0; i < subconn_prop_ptr->count_enums && !found; i++) { if (subconn_prop_ptr->enums[i].value == enum_value) { rpt_vstring(d3, "Subconnector value = %2d - %s", enum_value, subconn_prop_ptr->enums[i].name); found = true; } } if (!found) { rpt_vstring(d3, "Unrecognized subconnector value: %d", enum_value); } } else if (conn->props[ndx] == dpms_prop_id) { rpt_vstring(d2, "DPMS property"); assert(dpms_prop_ptr); // if dpms_prop_id found, dpms_prop_ptr must have been set uint32_t enum_value = conn->prop_values[ndx]; // printf("dpms value: %d\n", enum_value); assert(dpms_prop_ptr->flags & DRM_MODE_PROP_ENUM); if (dpms_prop_ptr->flags & DRM_MODE_PROP_ENUM) { bool found = false; for (int i = 0; i < dpms_prop_ptr->count_enums && !found; i++) { if (dpms_prop_ptr->enums[i].value == enum_value) { rpt_vstring(d3, "dpms value = %d - %s", enum_value, dpms_prop_ptr->enums[i].name); found = true; } } if (!found) { rpt_vstring(d3, "Unrecognized dpms value: %d", enum_value); } } else { rpt_vstring(d2, "dpms not type enum!. Value = %d", enum_value); } } else if (conn->props[ndx] == link_status_prop_id) { rpt_vstring(d2, "link-status property"); assert(link_status_prop_ptr); // if link_status_prop_id found, link_status_prop_ptr must have been set uint64_t enum_value = conn->prop_values[ndx]; // printf("link_status value: %d\n", enum_value); assert(link_status_prop_ptr->flags & DRM_MODE_PROP_ENUM); bool found = false; for (int i = 0; i < link_status_prop_ptr->count_enums && !found; i++) { if (link_status_prop_ptr->enums[i].value == enum_value) { rpt_vstring(d3, "link-status value = %u - %s", (unsigned) enum_value, link_status_prop_ptr->enums[i].name); found = true; } } if (!found) { rpt_vstring(d2, "Unrecognized link-status value: %u", (unsigned) enum_value); } } else if (conn->props[ndx] == type_prop_id) { rpt_vstring(d2, "type property"); assert(type_prop_ptr); // if type_prop_id found, type_prop_ptr must have been set uint32_t enum_value = conn->prop_values[ndx]; // printf("type value: %d\n", enum_value); assert(type_prop_ptr->flags & DRM_MODE_PROP_ENUM); bool found = false; for (int i = 0; i < type_prop_ptr->count_enums && !found; i++) { if (type_prop_ptr->enums[i].value == enum_value) { rpt_vstring(d2, "type value = %u - %s", enum_value, type_prop_ptr->enums[i].name); found = true; } } if (!found) { rpt_vstring(d2, "Unrecognized type value: %u", enum_value); } } #ifdef FUTURE else { drmModePropertyPtr prop_ptr = drmModeGetProperty(fd, conn->props[ndx]); if (prop_ptr) { // now in connector report function // report_property_value(dri_fd, prop_ptr, conn->prop_values[ndx], 1); // to implement: summarize_property_value(fd, prop_ptr, conn->prop_values[ndx], d2); drmModeFreeProperty(prop_ptr); } else { printf("Unrecognized property id: %d\n", conn->props[ndx]); } } #endif } drmModeFreeConnector(conn); rpt_nl(); } if (edid_prop_ptr) { drmModeFreeProperty(edid_prop_ptr); } if (subconn_prop_ptr) { drmModeFreeProperty(subconn_prop_ptr); } if (dpms_prop_ptr) { drmModeFreeProperty(dpms_prop_ptr); } if (link_status_prop_ptr) { drmModeFreeProperty(link_status_prop_ptr); } if (type_prop_ptr) { drmModeFreeProperty(type_prop_ptr); } DBGMSF(debug, "freeing res=%p", (void*)res); drmModeFreeResources(res); bye: DBGTRC_DONE(debug, TRACE_GROUP, ""); rpt_nl(); return; } #ifdef NO // modified from libdrm test code kms.c static const char * const modules[] = { "i915", "radeon", "nouveau", #ifdef SKIP "vmwgfx", "omapdrm", "exynos", "tilcdc", "msm", "sti", "tegra", "imx-drm", "rockchip", "atmel-hlcdc", "fsl-dcu-drm", "vc4", #endif "nvidia_drm", "nvidia_modeset", "nvidia", NULL, }; int util_open(const char *device, const char *module) { int fd; if (module) { fd = drmOpen(module, device); if (fd < 0) { fprintf(stderr, "failed to open device '%s': %s\n", module, strerror(errno)); return -errno; } } else { unsigned int i; for (i = 0; i < ARRAY_SIZE(modules); i++) { printf("trying to open device %s using'%s'...", device, modules[i]); fd = drmOpen(modules[i], device); if (fd < 0) { printf("failed\n"); } else { printf("done\n"); break; } } if (fd < 0) { fprintf(stderr, "no device found\n"); return -ENODEV; } } return fd; } #endif /* Examines a single DRM device, specified by name. * * Arguments: * devname device name * depth logical indentation depth * * Returns: nothing */ static void probe_one_device_using_libdrm(char * devname, int depth) { rpt_vstring(depth, "Probing device %s...", devname); int fd = -1; // drmOpen() returns a file descriptor if successful, // if < 0, its an errno value // n. errno = -fd if a passthru, but will not be set if generated internally // within drmOpen (examined the code) // drmOopen() can also return DRM_ERR_NOT_ROOT (-1003) // DRM specific error numbers are in range -1001..-1005, // conflicts with our Global _Status_Code mapping #ifdef FAIL fd = drmOpen(bname, NULL); if (fd < 0) { rpt_vstring(depth, "Error opening device %s using drmOpen(), fd=%s", bname, linux_errno_desc(-fd)); } if (fd < 0) { fd = drmOpen(devname, NULL); if (fd < 0) { rpt_vstring(depth, "Error opening device %s using drmOpen(), fd=%s", devname, linux_errno_desc(-fd)); } } #endif #ifdef NO char * busid = "pci:0000:01:00.0"; // open succeeds using hardcoded busid, but doesn't solve problem of // driver not modesetting // but .. if this isn't used, drmGetBusid() fails // #ifdef WORKS_BUT_NOT_HELPFUL if (fd < 0) { fd = drmOpen(NULL, busid); if (fd < 0) { rpt_vstring(depth, "Error opening busid %s using drmOpen(), fd=%s", busid, linux_errno_desc(-fd)); } else { rpt_vstring(depth, "Successfully opened using drmOpen(NULL, \"%s\")\n", busid); } } // #endif if (fd < 0) { fd = util_open(busid, NULL); } #endif if (fd < 0) { errno = 0; fd = open(devname,O_RDWR | O_CLOEXEC); if (fd < 0) { rpt_vstring(depth+1, "Error opening device %s using open(), errno=%s", devname, linux_errno_desc(errno)); } else rpt_vstring(depth+1, "Open succeeded for device: %s", devname); } if (fd >= 0) { probe_open_device_using_libdrm(fd, depth); CLOSE_W_ERRMSG(fd); } } #ifdef DUPLICATE /* Filter to find driN files using scandir() in get_filenames_by_filter() */ static int is_dri(const struct dirent *ent) { return !strncmp(ent->d_name, "card", strlen("card")); } /* Scans /dev/dri to obtain list of device names * * Returns: GPtrArray of device device names. */ GPtrArray * get_dri_device_names_using_filesys() { const char *dri_paths[] = { "/dev/dri/", NULL }; GPtrArray* dev_names = get_filenames_by_filter(dri_paths, is_dri); g_ptr_array_sort(dev_names, gaux_ptr_scomp); // needed? return dev_names; } #endif /* Main function for probing device information, particularly EDIDs, * using libdrm. * * 2/2017: Nvidia's proprietary drm driver does not appear to * support the ioctls underlying the libdrm functions, and hence * the functions, set errno=22 (EINVAL). */ void probe_using_libdrm() { int d0 = 0; int d1 = d0+1; int d2 = d0+2; rpt_label(d0, "*** Probing connected monitors using libdrm ***"); if ( directory_exists("/proc/driver/nvidia/") ) { rpt_nl(); rpt_vstring(1,"Checking Nvidia options to see if experimental kernel modesetting enabled:"); char * cmd = "modprobe -c | grep \"^options nvidia\""; rpt_vstring(d1, "Executing command: %s", cmd); execute_shell_cmd_rpt(cmd, d2); } // Check libdrm version, since there seems to be some sensitivity rpt_nl(); if (is_command_in_path("pkg-config")) { rpt_vstring(d1, "Checking libdrm version using pkg-config..."); char * cmd = "pkg-config --modversion libdrm"; execute_shell_cmd_rpt(cmd, d2); } else { // try the most common distribution specific tools if (is_command_in_path("dpkg-query")) { char * cmd = "dpkg-query -l libdrm2 | grep ii"; rpt_vstring(d1, "Checking libdrm version using dpkg-query..."); execute_shell_cmd_rpt(cmd, d2); } rpt_nl(); if (is_command_in_path("rpm")) { char * cmd = "rpm -qa | grep libdrm"; rpt_vstring(d1, "Checking libdrm version using rpm..."); execute_shell_cmd_rpt(cmd, d2); } } // Examining the implementation in xf86drm.c, we see that // drmAvailable first calls drmOpenMinor(), then if that // succeeds calls drmGetVersion(). If both succeed, returns true. // n. drmOpenMinor() is a static function rpt_nl(); // returns 1 if the DRM driver is loaded, 0 otherwise int drm_available = drmAvailable(); rpt_vstring(d1, "Has a DRM kernel driver been loaded? (drmAvailable()): %s", sbool(drm_available)); #ifdef DOESNT_WORK // function drmOpenMinor() is static if (!drm_available) { // try the functions that drmAvailable() calls to see where the failure is int fd = drmOpenMinor(0, 1, DRM_MODE_PRIMARY); if (fd < 0) { rpt_vstring(1, "drmOpenMinor() failed, errno=%s", linux_errno_desc(-fd)); } else { rpt_vstring(1, "drmOpenMinor() succeeded"); drmVersionPtr ver = drmGetVersion(fd); if (ver) { rpt_vstring(1, "drmGetVersion() succeeded"); drmFreeVersion(ver); } else { rpt_vstring(1, "drmGetVersion() failed"); } } } #endif GPtrArray * dev_names = get_dri_device_names_using_filesys(); for (int ndx = 0; ndx < dev_names->len; ndx++) { char * dev_name = g_ptr_array_index(dev_names, ndx); rpt_nl(); probe_one_device_using_libdrm( dev_name, 1); } g_ptr_array_free(dev_names, true); } ddcutil-2.2.0/src/app_sysenv/query_sysenv_access.h0000644000175000001440000000075214754576332016070 /* @file query_sysenv_access.h * * Checks on the the existence of and access to /dev/i2c devices */ // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_ACCESS_H_ #define QUERY_SYSENV_ACCESS_H_ #include "util/data_structures.h" #include "app_sysenv/query_sysenv_base.h" Byte_Value_Array identify_i2c_devices(); void check_i2c_devices(Env_Accumulator * accum); #endif /* QUERY_SYSENV_ACCESS_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_base.h0000644000175000001440000000645114754576332015543 /** @file query_sysenv_base.h * * Base structures and functions for subsystem that diagnoses user configuration */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_BASE_H_ #define QUERY_SYSENV_BASE_H_ /** \cond */ #include #include #include "util/data_structures.h" /** \endcond */ // if defined, some tests with long elapsed times are skipped to shorten time of test runs // #define SYSENV_QUICK_TEST_RUN // #define SYSENV_TEST_IDENTICAL_EDIDS #ifdef SYSENV_TEST_IDENTICAL_EDIDS // For testing situation where 2 displays have the same EDID, e.g. LG displays extern Byte * first_edid; #endif char ** get_known_video_driver_module_names(); char ** get_prefix_match_names(); char ** get_other_driver_module_names(); char ** get_all_driver_module_strings(); void sysenv_rpt_file_first_line(const char * fn, const char * title, int depth); bool sysenv_show_one_file(const char * dir_name, const char * simple_fn, bool verbose, int depth); void sysenv_rpt_current_time(const char * title, int depth); /** Linked list of names of detected drivers */ typedef struct driver_name_node { char * driver_name; struct driver_name_node * next; } Driver_Name_Node; Driver_Name_Node * driver_name_list_find_exact( Driver_Name_Node * head, const char * driver_name); Driver_Name_Node * driver_name_list_find_prefix(Driver_Name_Node * head, const char * driver_prefix); void driver_name_list_add(Driver_Name_Node ** headptr, const char * driver_name); void driver_name_list_free(Driver_Name_Node * driver_list); char * driver_name_list_string(Driver_Name_Node * head); bool only_fglrx(Driver_Name_Node * driver_list); bool only_nvidia_or_fglrx(Driver_Name_Node * driver_list); int i2c_path_to_busno(const char * path); #define ENV_ACCUMULATOR_MARKER "ENVA" /** Collects system environment information */ typedef struct { char marker[4]; char * architecture; char * distributor_id; bool is_raspbian; bool is_arm; Byte_Value_Array dev_i2c_device_numbers; Driver_Name_Node * driver_list; bool sysfs_i2c_devices_exist; Byte_Value_Array sys_bus_i2c_device_numbers; bool sysfs_ddcci_devices_exist; bool group_i2c_checked; bool group_i2c_exists; bool dev_i2c_devices_required; bool all_dev_i2c_has_group_i2c; bool any_dev_i2c_has_group_i2c; char * dev_i2c_common_group_name; char * cur_uname; uid_t cur_uid; bool cur_user_in_group_i2c; bool cur_user_any_devi2c_rw; bool cur_user_all_devi2c_rw; bool module_i2c_dev_needed; bool loadable_i2c_dev_exists; bool module_i2c_dev_builtin; bool i2c_dev_loaded_or_builtin; // loaded or built-in bool any_dev_i2c_is_group_rw; bool all_dev_i2c_is_group_rw; } Env_Accumulator; Env_Accumulator * env_accumulator_new(); void env_accumulator_free(Env_Accumulator * accum); void env_accumulator_report(Env_Accumulator * accum, int depth); extern bool sysfs_quick_test; #endif /* QUERY_SYSENV_BASE_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_detailed_bus_pci_devices.h0000644000175000001440000000061414754576332021605 // query_sysenv_detailed_bus_pci_devices.h // Copyright (C) 2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_DETAILED_BUS_PCI_DEVICES_H_ #define QUERY_SYSENV_DETAILED_BUS_PCI_DEVICES_H_ void dump_detailed_sys_bus_pci(int depth); void init_query_detailed_bus_pci_devices(); #endif // QUERY_SYSENV_DETAILED_BUS_PCI_DEVICES_H_ ddcutil-2.2.0/src/app_sysenv/query_sysenv_dmidecode.h0000644000175000001440000000052414754576332016541 /** @file query_sysenv_dmidecode.h * * dmidecode report for the environment command */ // Copyright (C) 2016-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_DMIDECODE_H_ #define QUERY_SYSENV_DMIDECODE_H_ void query_dmidecode(); #endif /* QUERY_SYSENV_DMIDECODE_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_drm.h0000644000175000001440000000047414754576332015412 /** @file query_drm_sysenv.h * * drm reporting for the environment command */ // Copyright (C) 2017-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_DRM_SYSENV_H_ #define QUERY_DRM_SYSENV_H_ void probe_using_libdrm(); #endif /* QUERY_DRM_SYSENV_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_i2c.h0000644000175000001440000000071314754576332015301 /** @file query_sysenv_i2c.h * * Check I2C devices using directly coded I2C calls */ // Copyright (C) 2014-2018 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_I2C_H_ #define QUERY_SYSENV_I2C_H_ #include "query_sysenv_base.h" void raw_scan_i2c_devices(Env_Accumulator * accum); void test_edid_read_variants(Env_Accumulator * accum); void query_i2c_buses(); #endif /* QUERY_SYSENV_I2C_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_modules.h0000644000175000001440000000065114754576332016275 /** \f query_sysenv_modules.h * * Module checks */ // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_MODULES_H_ #define QUERY_SYSENV_MODULES_H_ #include #include "query_sysenv_base.h" void check_i2c_dev_module(Env_Accumulator * accum, int depth); void probe_modules_d(int depth); #endif /* QUERY_SYSENV_MODULES_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_original_sys_scans.h0000644000175000001440000000047414754576332020521 // query_sysenv_original_sys_scans.h // Copyright (C) 2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_ORIGINAL_SYS_SCANS_H_ #define QUERY_SYSENV_ORIGINAL_SYS_SCANS_H_ void dump_original_sys_scans(); #endif /* QUERY_SYSENV_ORIGINAL_SYS_SCANS_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_procfs.h0000644000175000001440000000064614754576332016125 /** @file query_sysenv_procfs.h * * Query environment using /proc file system */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_PROCFS_H_ #define QUERY_SYSENV_PROCFS_H_ /** \cond */ #include /** \endcond */ int query_proc_modules_for_video(); bool query_proc_driver_nvidia(); #endif /* QUERY_SYSENV_PROCFS_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_simplified_sys_bus_pci_devices.h0000644000175000001440000000055614754576332023062 // query_sysenv_sys_bus_pci_devices.h // Copyright (C) 2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_SIMPLIFIED_SYS_BUS_PCI_DEVICES_H_ #define QUERY_SYSENV_SIMPLIFIED_SYS_BUS_PCI_DEVICES_H_ void dump_simplified_sys_bus_pci(int depth); #endif /* QUERY_SYSENV_SIMPLIFIED_SYS_BUS_PCI_DEVICES_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_sysfs_common.h0000644000175000001440000000056314754576332017346 // query_sysenv_sysfs_common.h // Copyright (C) 2018-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_SYSFS_COMMON_H_ #define QUERY_SYSENV_SYSFS_COMMON_H_ #include #include ushort h2ushort(char * hval); unsigned h2uint(char * hval); #endif /* QUERY_SYSENV_SYSFS_COMMON_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_usb.h0000644000175000001440000000044614754576332015420 /** @file query_usb_sysenv.h * * Probe the USB environment */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_USB_SYSENV_H_ #define QUERY_USB_SYSENV_H_ void query_usbenv(); #endif /* QUERY_USB_SYSENV_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_xref.h0000644000175000001440000000372314754576332015574 /** @file query_sysenv.xref.h * * Table cross-referencing the multiple ways that a display is referenced * in various Linux subsystems. */ // Copyright (C) 2017-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_XREF_H_ #define QUERY_SYSENV_XREF_H_ #include "util/edid.h" #define DEVICE_ID_XREF_MARKER "DXRF" /** Device identifier cross-reference entry */ typedef struct { char marker[4]; // Subsystem ids: // I2C scan by I2C bus number // DRM // SYSFS query /sys // X11 query X11 // UDEV query udev Byte raw_edid[128]; // All DRM I2C SYSFS X11 char * edid_tag; Parsed_Edid * parsed_edid; // All DRM I2C SUSFS int i2c_busno; // I2C char * xrandr_name; // X11 char * udev_name; // UDEV char * udev_syspath; // UDEV int udev_busno; // UDEV char * drm_connector_name; // DRM int drm_connector_type; // DRM char * drm_device_path; // DRM char * sysfs_drm_name; // SYSFS char * sysfs_drm_i2c; // SYSFS // or save I2C bus number found? // #ifdef ALTERNATIVE int sysfs_drm_busno; // #endif bool ambiguous_edid; } Device_Id_Xref; void device_xref_init(); void device_xref_set_i2c_bus_scan_complete(); // bool device_xref_i2c_bus_scan_complete(); char * device_xref_edid_tag(const Byte * raw_edid); Device_Id_Xref * device_xref_find_by_edid(const Byte * raw_edid); Device_Id_Xref * device_xref_find_by_busno(int busno); Device_Id_Xref * device_xref_new_with_busno(int busno, Byte * raw_edid); void device_xref_report(int depth); #endif /* QUERY_SYSENV_XREF_H_ */ ddcutil-2.2.0/src/app_sysenv/app_sysenv_services.h0000644000175000001440000000057314754576332016066 // app_sysenv_services.h // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "query_sysenv_detailed_bus_pci_devices.h" #include "query_sysenv_sysfs.h" #include "query_sysenv.h" #ifndef APP_SYSENV_SERVICES_H_ #define APP_SYSENV_SERVICES_H_ void init_app_sysenv_services(); #endif /* APP_SYSENV_SERVICES_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_logs.h0000644000175000001440000000073314754576332015572 /** @file query_sysenv_logs.h * * Query configuration files, logs, and output of logging commands. */ // Copyright (C) 2017-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_LOGS_H_ #define QUERY_SYSENV_LOGS_H_ #include "query_sysenv_base.h" void probe_logs(Env_Accumulator * accum); void probe_config_files(Env_Accumulator * accum); void probe_cache_files(int depth); #endif /* QUERY_SYSENV_LOGS_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv.h0000644000175000001440000000067114754576332014547 /** @file query_sysenv.h * * Primary file for the ENVIRONMENT command */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_H_ #define QUERY_SYSENV_H_ #include #include "cmdline/parsed_cmd.h" void force_envcmd_settings(Parsed_Cmd * parsed_cmd); void query_sysenv(bool quickenv); void init_query_sysenv(); #endif /* QUERY_SYSENV_H_ */ ddcutil-2.2.0/src/app_sysenv/query_sysenv_sysfs.h0000644000175000001440000000170614754576332015776 /** @file query_sysenv_sysfs.h * * Query environment using /sys file system */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef QUERY_SYSENV_SYSFS_H_ #define QUERY_SYSENV_SYSFS_H_ #include "query_sysenv_base.h" typedef struct { unsigned short int vendor_id; unsigned short int device_id; unsigned short int subdevice_id; // subsystem device id unsigned short int subvendor_id; // subsystem vendor id } Device_Ids; Device_Ids read_device_ids1(char * cur_dir_name); Device_Ids read_device_ids2(char * cur_dir_name); void query_card_and_driver_using_sysfs(Env_Accumulator * accum); void query_loaded_modules_using_sysfs(); void query_sys_bus_i2c(Env_Accumulator * accum); void query_sys_amdgpu_parameters(int depth); void query_drm_using_sysfs(); void dump_sysfs_i2c(Env_Accumulator * accum); void init_query_sysenv_sysfs(); #endif /* QUERY_SYSENV_SYSFS_H_ */ ddcutil-2.2.0/src/base/0000775000175000001440000000000014754576333010424 5ddcutil-2.2.0/src/base/Makefile.am0000644000175000001440000000543114754153540012370 # src/base/Makefile.am AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) # Does not work to force recompilation # AM_MAKEFLAGS = -Wbuild_timestamp.c CLEANFILES = \ *expand \ build_details.h # Use empty header file that is rebuilt on every execution to force recompilation of build_timestamp.h. # See: https://stackoverflow.com/questions/54303270/how-to-execute-shell-commands-in-automake-makefile-am BUILT_SOURCES = build_details.h # Fails. Under some circumstances $0 is null, so explicitly redirect to build_details.h instead # build_details.h: # echo "// Dummy include file to force rebuilding built_timestamp.c" >$0 build_details.h: echo "// Dummy include file to force rebuilding built_timestamp.c" > build_details.h # all-local: # @echo "(src/base/Makefile) all-local" # rm -fv build_details.h clean-local: @echo "(src/base/Makefile) clean-local" mostlyclean-local: @echo "(src/base/Makefile) mostlyclean-local" distclean-local: @echo "(src/base/Makefile) distclean-local" dist-hook: @echo "(src/base/Makefile) dist-hook" # Intermediate Library noinst_LTLIBRARIES = libbase.la libbase_la_SOURCES = \ base_services.c \ build_info.c \ build_details.h \ build_timestamp.c \ core.c \ core_per_thread_settings.c \ ddc_command_codes.c \ ddc_errno.c \ ddc_packets.c \ display_lock.c \ displays.c \ drm_connector_state.c \ dsa2.c \ dynamic_features.c \ execution_stats.c \ feature_lists.c \ feature_metadata.c \ feature_set_ref.c \ flock.c \ i2c_bus_base.c \ linux_errno.c \ monitor_model_key.c \ monitor_quirks.c \ per_thread_data.c \ rtti.c \ sleep.c \ stats.c \ trace_control.c \ tuned_sleep.c \ status_code_mgt.c \ vcp_version.c \ per_display_data.c \ display_retry_data.c nodist_libbase_la_SOURCES = adl_errors.h # Rename all-local-disabled to "all-local" for development all-local-disabled: @echo "" @echo "(src/base/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" ddcutil-2.2.0/src/base/Makefile.in0000664000175000001440000007267514754576155012434 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # src/base/Makefile.am VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/base ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libbase_la_LIBADD = am_libbase_la_OBJECTS = base_services.lo build_info.lo \ build_timestamp.lo core.lo core_per_thread_settings.lo \ ddc_command_codes.lo ddc_errno.lo ddc_packets.lo \ display_lock.lo displays.lo drm_connector_state.lo dsa2.lo \ dynamic_features.lo execution_stats.lo feature_lists.lo \ feature_metadata.lo feature_set_ref.lo flock.lo \ i2c_bus_base.lo linux_errno.lo monitor_model_key.lo \ monitor_quirks.lo per_thread_data.lo rtti.lo sleep.lo stats.lo \ trace_control.lo tuned_sleep.lo status_code_mgt.lo \ vcp_version.lo per_display_data.lo display_retry_data.lo nodist_libbase_la_OBJECTS = libbase_la_OBJECTS = $(am_libbase_la_OBJECTS) \ $(nodist_libbase_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/base_services.Plo \ ./$(DEPDIR)/build_info.Plo ./$(DEPDIR)/build_timestamp.Plo \ ./$(DEPDIR)/core.Plo ./$(DEPDIR)/core_per_thread_settings.Plo \ ./$(DEPDIR)/ddc_command_codes.Plo ./$(DEPDIR)/ddc_errno.Plo \ ./$(DEPDIR)/ddc_packets.Plo ./$(DEPDIR)/display_lock.Plo \ ./$(DEPDIR)/display_retry_data.Plo ./$(DEPDIR)/displays.Plo \ ./$(DEPDIR)/drm_connector_state.Plo ./$(DEPDIR)/dsa2.Plo \ ./$(DEPDIR)/dynamic_features.Plo \ ./$(DEPDIR)/execution_stats.Plo ./$(DEPDIR)/feature_lists.Plo \ ./$(DEPDIR)/feature_metadata.Plo \ ./$(DEPDIR)/feature_set_ref.Plo ./$(DEPDIR)/flock.Plo \ ./$(DEPDIR)/i2c_bus_base.Plo ./$(DEPDIR)/linux_errno.Plo \ ./$(DEPDIR)/monitor_model_key.Plo \ ./$(DEPDIR)/monitor_quirks.Plo \ ./$(DEPDIR)/per_display_data.Plo \ ./$(DEPDIR)/per_thread_data.Plo ./$(DEPDIR)/rtti.Plo \ ./$(DEPDIR)/sleep.Plo ./$(DEPDIR)/stats.Plo \ ./$(DEPDIR)/status_code_mgt.Plo ./$(DEPDIR)/trace_control.Plo \ ./$(DEPDIR)/tuned_sleep.Plo ./$(DEPDIR)/vcp_version.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libbase_la_SOURCES) $(nodist_libbase_la_SOURCES) DIST_SOURCES = $(libbase_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) # Does not work to force recompilation # AM_MAKEFLAGS = -Wbuild_timestamp.c CLEANFILES = \ *expand \ build_details.h # Use empty header file that is rebuilt on every execution to force recompilation of build_timestamp.h. # See: https://stackoverflow.com/questions/54303270/how-to-execute-shell-commands-in-automake-makefile-am BUILT_SOURCES = build_details.h # Intermediate Library noinst_LTLIBRARIES = libbase.la libbase_la_SOURCES = \ base_services.c \ build_info.c \ build_details.h \ build_timestamp.c \ core.c \ core_per_thread_settings.c \ ddc_command_codes.c \ ddc_errno.c \ ddc_packets.c \ display_lock.c \ displays.c \ drm_connector_state.c \ dsa2.c \ dynamic_features.c \ execution_stats.c \ feature_lists.c \ feature_metadata.c \ feature_set_ref.c \ flock.c \ i2c_bus_base.c \ linux_errno.c \ monitor_model_key.c \ monitor_quirks.c \ per_thread_data.c \ rtti.c \ sleep.c \ stats.c \ trace_control.c \ tuned_sleep.c \ status_code_mgt.c \ vcp_version.c \ per_display_data.c \ display_retry_data.c nodist_libbase_la_SOURCES = adl_errors.h all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/base/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/base/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libbase.la: $(libbase_la_OBJECTS) $(libbase_la_DEPENDENCIES) $(EXTRA_libbase_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libbase_la_OBJECTS) $(libbase_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/base_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/build_info.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/build_timestamp.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/core.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/core_per_thread_settings.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_command_codes.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_errno.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_packets.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/display_lock.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/display_retry_data.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/displays.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/drm_connector_state.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dsa2.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dynamic_features.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/execution_stats.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/feature_lists.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/feature_metadata.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/feature_set_ref.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/flock.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_bus_base.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/linux_errno.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/monitor_model_key.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/monitor_quirks.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/per_display_data.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/per_thread_data.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rtti.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sleep.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stats.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/status_code_mgt.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/trace_control.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tuned_sleep.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vcp_version.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) clean: clean-am clean-am: clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/base_services.Plo -rm -f ./$(DEPDIR)/build_info.Plo -rm -f ./$(DEPDIR)/build_timestamp.Plo -rm -f ./$(DEPDIR)/core.Plo -rm -f ./$(DEPDIR)/core_per_thread_settings.Plo -rm -f ./$(DEPDIR)/ddc_command_codes.Plo -rm -f ./$(DEPDIR)/ddc_errno.Plo -rm -f ./$(DEPDIR)/ddc_packets.Plo -rm -f ./$(DEPDIR)/display_lock.Plo -rm -f ./$(DEPDIR)/display_retry_data.Plo -rm -f ./$(DEPDIR)/displays.Plo -rm -f ./$(DEPDIR)/drm_connector_state.Plo -rm -f ./$(DEPDIR)/dsa2.Plo -rm -f ./$(DEPDIR)/dynamic_features.Plo -rm -f ./$(DEPDIR)/execution_stats.Plo -rm -f ./$(DEPDIR)/feature_lists.Plo -rm -f ./$(DEPDIR)/feature_metadata.Plo -rm -f ./$(DEPDIR)/feature_set_ref.Plo -rm -f ./$(DEPDIR)/flock.Plo -rm -f ./$(DEPDIR)/i2c_bus_base.Plo -rm -f ./$(DEPDIR)/linux_errno.Plo -rm -f ./$(DEPDIR)/monitor_model_key.Plo -rm -f ./$(DEPDIR)/monitor_quirks.Plo -rm -f ./$(DEPDIR)/per_display_data.Plo -rm -f ./$(DEPDIR)/per_thread_data.Plo -rm -f ./$(DEPDIR)/rtti.Plo -rm -f ./$(DEPDIR)/sleep.Plo -rm -f ./$(DEPDIR)/stats.Plo -rm -f ./$(DEPDIR)/status_code_mgt.Plo -rm -f ./$(DEPDIR)/trace_control.Plo -rm -f ./$(DEPDIR)/tuned_sleep.Plo -rm -f ./$(DEPDIR)/vcp_version.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-local distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/base_services.Plo -rm -f ./$(DEPDIR)/build_info.Plo -rm -f ./$(DEPDIR)/build_timestamp.Plo -rm -f ./$(DEPDIR)/core.Plo -rm -f ./$(DEPDIR)/core_per_thread_settings.Plo -rm -f ./$(DEPDIR)/ddc_command_codes.Plo -rm -f ./$(DEPDIR)/ddc_errno.Plo -rm -f ./$(DEPDIR)/ddc_packets.Plo -rm -f ./$(DEPDIR)/display_lock.Plo -rm -f ./$(DEPDIR)/display_retry_data.Plo -rm -f ./$(DEPDIR)/displays.Plo -rm -f ./$(DEPDIR)/drm_connector_state.Plo -rm -f ./$(DEPDIR)/dsa2.Plo -rm -f ./$(DEPDIR)/dynamic_features.Plo -rm -f ./$(DEPDIR)/execution_stats.Plo -rm -f ./$(DEPDIR)/feature_lists.Plo -rm -f ./$(DEPDIR)/feature_metadata.Plo -rm -f ./$(DEPDIR)/feature_set_ref.Plo -rm -f ./$(DEPDIR)/flock.Plo -rm -f ./$(DEPDIR)/i2c_bus_base.Plo -rm -f ./$(DEPDIR)/linux_errno.Plo -rm -f ./$(DEPDIR)/monitor_model_key.Plo -rm -f ./$(DEPDIR)/monitor_quirks.Plo -rm -f ./$(DEPDIR)/per_display_data.Plo -rm -f ./$(DEPDIR)/per_thread_data.Plo -rm -f ./$(DEPDIR)/rtti.Plo -rm -f ./$(DEPDIR)/sleep.Plo -rm -f ./$(DEPDIR)/stats.Plo -rm -f ./$(DEPDIR)/status_code_mgt.Plo -rm -f ./$(DEPDIR)/trace_control.Plo -rm -f ./$(DEPDIR)/tuned_sleep.Plo -rm -f ./$(DEPDIR)/vcp_version.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: all check install install-am install-exec install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am dist-hook \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-local distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool mostlyclean-local pdf \ pdf-am ps ps-am tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Fails. Under some circumstances $0 is null, so explicitly redirect to build_details.h instead # build_details.h: # echo "// Dummy include file to force rebuilding built_timestamp.c" >$0 build_details.h: echo "// Dummy include file to force rebuilding built_timestamp.c" > build_details.h # all-local: # @echo "(src/base/Makefile) all-local" # rm -fv build_details.h clean-local: @echo "(src/base/Makefile) clean-local" mostlyclean-local: @echo "(src/base/Makefile) mostlyclean-local" distclean-local: @echo "(src/base/Makefile) distclean-local" dist-hook: @echo "(src/base/Makefile) dist-hook" # Rename all-local-disabled to "all-local" for development all-local-disabled: @echo "" @echo "(src/base/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/base/base_services.c0000644000175000001440000000323014754153540013310 /** @file base_services.c * * Initialize and release base services. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "util/debug_util.h" #include "util/error_info.h" #include "core.h" #include "ddc_packets.h" #include "displays.h" #include "drm_connector_state.h" #include "dynamic_features.h" #include "dsa2.h" #include "execution_stats.h" #include "flock.h" #include "feature_metadata.h" #include "i2c_bus_base.h" #include "linux_errno.h" #include "monitor_model_key.h" #include "per_display_data.h" #include "per_thread_data.h" #include "rtti.h" #include "sleep.h" #include "tuned_sleep.h" #include "base_services.h" /** Master initialization function for files in subdirectory base */ void init_base_services() { bool debug = false; DBGF(debug, "Starting."); errinfo_init(psc_name, psc_desc); init_core(); init_monitor_model_key(); init_base_dynamic_features(); init_ddc_packets(); init_dsa2(); init_execution_stats(); // init_linux_errno(); init_per_display_data(); init_per_thread_data(); init_sleep_stats(); init_status_code_mgt(); init_tuned_sleep(); init_displays(); init_i2c_bus_base(); init_feature_metadata(); init_drm_connector_state(); init_flock(); DBGF(debug, "Done"); } /** Cleanup at termination helps to reveal where the real leaks are */ void terminate_base_services() { bool debug = false; DBGF(debug, "Starting"); terminate_per_thread_data(); terminate_per_display_data(); terminate_execution_stats(); terminate_dsa2(); terminate_displays(); terminate_rtti(); DBGF(debug, "Done"); } ddcutil-2.2.0/src/base/build_info.c0000644000175000001440000000606614663160562012620 /** \file build_info.c * * Build Information: version, build options etc. * * This file hides the quirks and redundancies in configure.ac. * It is the single source of version information for all of * ddcutil. In particular, it handles how an optional version * suffix (e.g. RC1) is appended to the version string. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include "util/report_util.h" #include "base/build_info.h" /** Returns the base ddcutil version as a string, e.g. 1.2.3 * * \return ddcutil version string, do not free */ const char * get_base_ddcutil_version() { return VERSION; } /** Returns the ddcutil version suffix, e.g. "dev". * * \return version suffix, "" if no suffix. Do not free. */ const char * get_ddcutil_version_suffix() { return VERSION_VSUFFIX; } /** Returns the full ddcutil version, e.g. "1.2.3", "1.2.3-dev". * * \return full ddcutil version, do not free. */ const char * get_full_ddcutil_version() { static char full_ddcutil_version[20] = {0}; if (full_ddcutil_version[0] == '\0') { g_strlcpy( full_ddcutil_version, VERSION, 20); if (strlen(VERSION_VSUFFIX) > 0) { g_strlcat(full_ddcutil_version, "-", 20); g_strlcat(full_ddcutil_version, VERSION_VSUFFIX, 20); } } return full_ddcutil_version; } /** Reports build options used. * * \depth logical indentation depth */ void report_build_options(int depth) { int d1 = depth+1; rpt_label(depth, "General Build Options:"); // doesn't work, fails if option name undefined // #define REPORT_BUILD_OPTION(_name) rpt_vstring(d1, "%-20s %s", #_name ":", ( _name ## "+0" ) ? "Set" : "Not Set" ) #define IS_SET(_name) \ rpt_vstring(d1, "%-24s Defined", #_name ":"); #define NOT_SET(_name) \ rpt_vstring(d1, "%-24s Not defined", #_name ":"); #ifdef BUILD_SHARED_LIB IS_SET(BUILD_SHARED_LIB); #else NOT_SET(BUILD_SHARED_LIB); #endif #ifdef ENABLE_ENVCMDS IS_SET(ENABLE_ENVCMDS); #else NOT_SET(ENABLE_ENVCMDS); #endif #ifdef ENABLE_FAILSIM IS_SET(ENABLE_FAILSIM); #else NOT_SET(ENABLE_FAILSIM); #endif #ifdef ENABLE_UDEV IS_SET(ENABLE_UDEV); #else NOT_SET(ENABLE_UDEV); #endif #ifdef USE_X11 IS_SET(USE_X11); #else NOT_SET(USE_X11); #endif #ifdef USE_LIBDRM IS_SET(USE_LIBDRM); #else NOT_SET(USE_LIBDRM); #endif #ifdef ENABLE_USB IS_SET(ENABLE_USB); #else NOT_SET(ENABLE_USB); #endif #ifdef UNUSED #ifdef ENABLE_TRACE IS_SET(ENABLE_TRACE); #else NOT_SET(ENABLE_TRACE); #endif #endif #ifdef WITH_ASAN IS_SET(WITH_ASAN); #else NOT_SET(WITH_ASAN); #endif rpt_nl(); rpt_label(depth, "Private Build Options:"); #ifdef TARGET_LINUX IS_SET(TARGET_LINUX); #else NOT_SET(TARGET_LINUX); #endif #ifdef TARGET_BSD IS_SET(TARGET_BSD); #else NOT_SET(TARGET_BSD); #endif #ifdef INCLUDE_TESTCASES IS_SET(INCLUDE_TESTCASES); #else NOT_SET(INCLUDE_TESTCASES); #endif #ifdef STATIC IS_SET(STATIC); #else NOT_SET(STATIC); #endif rpt_nl(); } ddcutil-2.2.0/src/base/build_details.h0000664000175000001440000000007414754576332013321 // Dummy include file to force rebuilding built_timestamp.c ddcutil-2.2.0/src/base/build_timestamp.c0000644000175000001440000000074514754153540013665 /** \file build_timestamp.c * * Timestamp generated at each build. */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include "base/build_details.h" // created by Makefile #include "base/build_timestamp.h" #ifdef BUILD_TIMESTAMP const char * BUILD_DATE = __DATE__; const char * BUILD_TIME = __TIME__; #else const char * BUILD_DATE = "Not set"; const char * BUILD_TIME = "Not set"; #endif ddcutil-2.2.0/src/base/core.c0000644000175000001440000012164414754153540011435 /** @file core.c * Core functions and global variables. * * File core.c provides a collection of inter-dependent services at the core * of the **ddcutil** application. * * These include * - message destination redirection * - abnormal termination * - standard function call options * - timestamp generation * - message level control * - debug and trace messages */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" //* \cond */ #include #include #include #include #include #include #include // #include // requires glibc 2.28, apparently unused #ifdef TARGET_BSD #include #else #include #include #include #endif #include /** \endcond */ #include "util/common_printf_formats.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/error_info.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/glib_string_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/timestamp.h" #include "util/traced_function_stack.h" #include "base/build_info.h" #include "base/core_per_thread_settings.h" #include "base/ddc_errno.h" #include "base/linux_errno.h" #include "base/trace_control.h" #include "base/core.h" bool tracing_initialized = false; bool library_disabled = false; // // Standard call options // Value_Name_Table callopt_bitname_table2 = { VN(CALLOPT_ERR_MSG), // VN(CALLOPT_ERR_ABORT), VN(CALLOPT_RDONLY), VN(CALLOPT_WARN_FINDEX), VN(CALLOPT_WAIT), VN(CALLOPT_FORCE_SLAVE_ADDR), VN(CALLOPT_NONE), // special entry VN_END }; /** Interprets a **Call_Options** byte as a printable string. * The returned value is valid until the next call of this function in * the current thread. * * @param calloptions **Call_Options** byte * * @return interpreted value */ char * interpret_call_options_t(Call_Options calloptions) { static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&buf_key, 200); char * buftemp = vnt_interpret_flags(calloptions, callopt_bitname_table2, false, "|"); g_strlcpy(buf, buftemp, 200); // n. this is a debug msg, truncation benign free(buftemp); return buf; } // Local definitions and functions shared by all message control categories #define SHOW_REPORTING_TITLE_START 0 #define SHOW_REPORTING_MIN_TITLE_SIZE 28 static void print_simple_title_value(int offset_start_to_title, const char * title, int offset_title_start_to_value, const char * value) { if (redirect_reports_to_syslog) { syslog(LOG_NOTICE, "%.*s%-*s%s\n", offset_start_to_title,"", offset_title_start_to_value, title, value); } else { f0printf(fout(), "%.*s%-*s%s\n", offset_start_to_title,"", offset_title_start_to_value, title, value); fflush(fout()); } } /** Reports the output level for the current thread * The report is written to the current **FOUT** device. * * \ingroup msglevel */ void show_output_level() { Thread_Output_Settings * settings = get_thread_settings(); print_simple_title_value(SHOW_REPORTING_TITLE_START, "Output level: ", SHOW_REPORTING_MIN_TITLE_SIZE, output_level_name(settings->output_level)); } // // Debug and trace message control // /** defgroup dbgtrace Debug and Trace Messages * */ #ifdef UNUSED static char * trace_destination = NULL; void show_trace_destination() { print_simple_title_value(SHOW_REPORTING_TITLE_START, "Trace destination:", SHOW_REPORTING_MIN_TITLE_SIZE, (trace_destination) ? trace_destination : "sysout"); } #endif #ifdef UNUSED void set_libddcutil_output_destination(const char * filename, const char * trace_unit) { bool debug = false; if (debug) printf("(%s) filename = %s, trace_unit = %s\n", __func__, filename, trace_unit); if (filename) { trace_destination = strdup(filename); FILE * f = fopen(filename, "a"); if (f) { time_t trace_start_time = time(NULL); char * trace_start_time_s = asctime(localtime(&trace_start_time)); if (trace_start_time_s[strlen(trace_start_time_s)-1] == 0x0a) trace_start_time_s[strlen(trace_start_time_s)-1] = 0; fprintf(f, "%s tracing started %s\n", trace_unit, trace_start_time_s); fclose(f); if (debug) fprintf(stdout, "Writing %s trace output to %s\n", trace_unit, filename); } else { fprintf(stderr, "Unable to write %s trace output to %s: %s\n", trace_unit, filename, strerror(errno)); } } } #endif #ifdef FUTURE void init_syslog(const char * ddcutil_component) { openlog(ddcutil_component, LOG_CONS | LOG_PID, LOG_USER); void close_syslog() { closelog(); } #endif // // Error_Info reporting // /** If true, report #Error_Info instances before they are freed. */ bool report_freed_exceptions = false; // // Report DDC data errors // static bool report_ddc_errors = false; static GMutex report_ddc_errors_mutex; bool enable_report_ddc_errors(bool onoff) { g_mutex_lock(&report_ddc_errors_mutex); bool old_val = report_ddc_errors; report_ddc_errors = onoff; g_mutex_unlock(&report_ddc_errors_mutex); return old_val; } bool is_report_ddc_errors_enabled() { bool old_val = report_ddc_errors; return old_val; } /** Checks if DDC data errors are to be reported. This is the case if any of the * following hold: * - DDC error reporting has been explicitly enabled * - The trace group specified by the calling function is currently active. * - The value of **trace_group** is 0xff, which is the convention used for debug messages * - The file name specified is currently being traced * - The function name specified is currently being traced. * * @param trace_group trace group of caller, if 0xff then always output * @param filename file name to check * @param funcname function name to check * @return **true** if message is to be output, **false** if not * * @remark * This function is normally wrapped in function **IS_REPORTING_DDC()** */ bool is_reporting_ddc(DDCA_Trace_Group trace_group, const char * filename, const char * funcname) { bool result = (is_tracing(trace_group,filename, funcname) || report_ddc_errors); return result; } /* Submits a message regarding a DDC data error for possible output. * * @param trace_group group to check, 0xff to always output * @param funcname function name to check * @param lineno line number in file * @param filename file name to check * @param format message format string * @param ... arguments for message format string * * @return **true** if message was output, **false** if not * * Normally, invocation of this function is wrapped in macro DDCMSG. */ bool ddcmsg(DDCA_Trace_Group trace_group, const char * funcname, const int lineno, const char * filename, char * format, ...) { bool result = false; bool debug_or_trace = is_tracing(trace_group, filename, funcname); if (debug_or_trace || is_report_ddc_errors_enabled()) { result = true; char buffer[200]; va_list(args); va_start(args, format); vsnprintf(buffer, 200, format, args); if (debug_or_trace) { // use dbgtrc() for consistent handling of timestamp and thread id prefixes dbgtrc(0xff, DBGTRC_OPTIONS_NONE, funcname, lineno, filename, "DDC: %s", buffer); } else { f0printf(fout(), "DDC: %s\n", buffer); // printf("trace_to_syslog = %s\n", sbool(trace_to_syslog)); if (test_emit_syslog(DDCA_SYSLOG_WARNING)) { syslog(LOG_WARNING, "%s", buffer); } } fflush(fout()); va_end(args); } return result; } bool logable_msg(DDCA_Syslog_Level log_level, const char * funcname, const int lineno, const char * filename, char * format, ...) { bool result = true; // char buffer[500]; va_list(args); va_start(args, format); char * buffer = g_strdup_vprintf(format, args); // vsnprintf(buffer, 500, format, args); if (redirect_reports_to_syslog) { syslog(LOG_NOTICE, "%s", buffer); } else { f0printf(fout(), "%s\n", buffer); if (test_emit_syslog(log_level)) { int importance = syslog_importance_from_ddcutil_syslog_level(log_level); syslog(importance, "%s", buffer); } } fflush(fout()); va_end(args); free(buffer); return result; } /** Tells whether DDC data errors are reported. * Output is written to the current **FOUT** device. */ static void show_ddcmsg() { print_simple_title_value(SHOW_REPORTING_TITLE_START, "Reporting DDC data errors: ", SHOW_REPORTING_MIN_TITLE_SIZE, SBOOL(report_ddc_errors)); } void show_ddcutil_version() { print_simple_title_value(SHOW_REPORTING_TITLE_START, "ddcutil version: ", SHOW_REPORTING_MIN_TITLE_SIZE, get_full_ddcutil_version()); } /** Reports output levels for: * - general output level (terse, verbose, etc) * - DDC data errors * * Output is written to the current **FOUT** device. */ void show_reporting() { show_output_level(); show_ddcmsg(); } // // Issue messages of various types // #define MAX_TRACE_CALLSTACK_CALL_DEPTH 100 // trace_callstack is per thread __thread int trace_api_call_depth = 0; __thread unsigned int trace_callstack_call_depth = 0; /** Checks if tracing is to be performed. * * Tracing is enabled if any of the following tests pass: * - trace group * - file name * - function name * * @param trace_group group to check * @param filename file from which check is occurring * @param funcname function name * * @return **true** if tracing enabled, **false** if not * * @remark * - Multiple trace group bits can be set in **trace_group**. If any of those * group are currently being traced, the function returns **true**. That is, * a given trace location in the code can be activated by multiple trace groups. * - If trace_group == TRC_ALWAYS (0xff), the function returns **true**. * Commonly, if debugging is active in a given location, the trace_group value * being checked can be set to TRC_ALWAYS, so a site can have a single debug/trace * function call. * * @ingroup dbgtrace * */ bool is_tracing(DDCA_Trace_Group trace_group, const char * filename, const char * funcname) { bool debug = false; //str_starts_with(funcname, "ddca_"); DBGF(debug, "Starting. trace_group=0x%04x, filename=%s, funcname=%s", trace_group, filename, funcname); bool result = false; result = (trace_group == DDCA_TRC_ALL) || (trace_levels & trace_group); // is trace_group being traced? result = result || is_traced_function(funcname) || is_traced_file(filename) || trace_api_call_depth > 0; DBGF(debug, "Done. trace_group=0x%04x, filename=%s, funcname=%s, trace_levels=0x%04x, returning %d\n", trace_group, filename, funcname, trace_levels, result); return result; } #ifdef UNUSED #define INIT_CALLSTACK() \ if (!trace_callstack) { \ trace_callstack = g_ptr_array_sized_new(100); \ g_ptr_array_set_free_func(trace_callstack, g_free); \ } static void report_callstack() { // INIT_CALLSTACK(); printf("Current callstack, trace_callstack_call_depth=%d\n", trace_callstack_call_depth); for (int ndx = 0; ndx < trace_callstack_call_depth; ndx++) { printf(" trace_callstack[%d] = %s\n", ndx, trace_callstack[ndx]); } } static void push_callstack(const char * funcname) { // INIT_CALLSTACK(); bool debug = false; if (debug) printf("(%s) Starting. funcname=%s, trace_callstack_call_depth=%d\n", __func__, funcname, trace_callstack_call_depth); assert(trace_callstack_call_depth < (MAX_TRACE_CALLSTACK_CALL_DEPTH-1)); trace_callstack[trace_callstack_call_depth++] = strdup(funcname); if (debug) printf("(%s) Done. New trace_callstack_call_depth = %d\n", __func__, trace_callstack_call_depth); } static void pop_callstack(const char * funcname) { // INIT_CALLSTACK(); bool debug = false; if (debug) printf("(%s) Starting. funcname=%s, trace_callstack_call_depth=%d\n", __func__, funcname, trace_callstack_call_depth); if (trace_callstack_call_depth == 0) { printf("(%s) ======> Error. Popping %s off of empty call stack\n", __func__, funcname); assert(false); } else { int last = trace_callstack->len - 1; char * popped = g_ptr_array_remove_index(trace_callstack, last); if (!(streq(funcname, popped))) { printf("(%s) ======> Error. Popped %s, expected %s\n", __func__, popped, funcname); report_callstack(); show_backtrace(2); assert(streq(funcname, popped)); } if (debug) printf("(%s) Done. Popped: %s, new callstack->len=%d\n", __func__, popped, trace_callstack->len); free(popped); } } #endif /** Core function for emitting debug and trace messages. * Used by the dbgtrc*() function variants. * * The message is output if any of the following are true: * - the trace_group specified is currently active * - the value is trace group is 0xff * - funcname is the name of a function being traced * - filename is the name of a file being traced * - api stack call depth > 0 * * The message is written to the fout() or ferr() device for the current thread * and optionally, depending on the syslog setting, to the system log. * * @param trace_group trace group of caller, 0xff to always output * @param options execution option flags * @param funcname function name of caller * @param lineno line number in caller * @param filename file name of caller * @param retval_info return value description * @param format format string for message * @param ap arguments for format string * * @return **true** if message was output, **false** if not */ static bool vdbgtrc( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * filename, const char * retval_info, char * format, va_list ap) { bool debug = false; if (debug) { printf("(vdbgtrc) Starting. trace_group=0x%04x, options=0x%02x, funcname=%s, filename=%s," " lineno=%d, thread=%jd, fout() %s sysout, pre_prefix=|%s|, format=|%s|\n", trace_group, options, funcname, filename, lineno, get_thread_id(), (fout() == stdout) ? "==" : "!=", retval_info, format); printf("trace_api_call_depth=%d\n", trace_api_call_depth); printf("traced_function_stack_enabled = %s\n", sbool(traced_function_stack_enabled)); } bool msg_emitted = false; if (trace_api_call_depth > 0 || trace_callstack_call_depth > 0) trace_group = DDCA_TRC_ALL; if (debug) printf("Adjusted trace_group == 0x%02x\n", trace_group); bool perform_emit = true; // #ifndef ENABLE_TRACE // if (!(options & DBGTRC_OPTIONS_SEVERE)) // perform_emit = false; // #endif if (perform_emit) { Thread_Output_Settings * thread_settings = get_thread_settings(); // n. trace_group == DDCA_TRC_ALL for SEVEREMSG() or API call tracing if ( is_tracing(trace_group, filename, funcname) ) { char * base_msg = g_strdup_vprintf(format, ap); if (debug) { printf("base_msg=%p->|%s|\n", base_msg, base_msg); printf("retval_info=%p->|%s|\n", retval_info, retval_info); } char elapsed_prefix[20] = ""; char walltime_prefix[20] = ""; char thread_prefix[15] = ""; char process_prefix[15] = ""; if (dbgtrc_show_time && !(options & DBGTRC_OPTIONS_SEVERE)) g_snprintf(elapsed_prefix, 20, "[%s]", formatted_elapsed_time_t(4)); if (dbgtrc_show_wall_time && !(options & DBGTRC_OPTIONS_SEVERE)) g_snprintf(walltime_prefix, 20, "[%s]", formatted_wall_time()); if (dbgtrc_show_thread_id && !(options & DBGTRC_OPTIONS_SEVERE) ) { // intmax_t tid = get_thread_id(); // assert(tid == thread_settings->tid); snprintf(thread_prefix, 15, PRItid, thread_settings->tid); } if (dbgtrc_show_process_id && !(options & DBGTRC_OPTIONS_SEVERE) ) { intmax_t pid = get_process_id(); // assert(pid == thread_settings->pid); snprintf(process_prefix, 15, "{%7jd}", pid); } char * decorated_msg = (options & DBGTRC_OPTIONS_SEVERE) ? g_strdup_printf("%s%s", retval_info, base_msg) : g_strdup_printf("%s%s%s%s(%-30s) %s%s", process_prefix, thread_prefix, walltime_prefix, elapsed_prefix, funcname, retval_info, base_msg); if (debug) printf("decorated_msg=%p->|%s|\n", decorated_msg, decorated_msg); #ifdef NO if (trace_destination) { FILE * f = fopen(trace_destination, "a"); if (f) { int status = fputs(decorated_msg, f); if (status < 0) { // per doc it's -1 = EOF fprintf(stderr, "Error writing to %s: %s\n", trace_destination, strerror(errno)); free(trace_destination); trace_destination = NULL; } else { fflush(f); } fclose(f); } else { fprintf(stderr, "Error opening %s: %s\n", trace_destination, strerror(errno)); trace_destination = NULL; } } if (!trace_destination) { f0puts(decorated_msg, fout()); // no automatic terminating null fflush(fout()); } free(pre_prefix_buffer); free(decorated_msg); msg_emitted = true; #endif // if (trace_to_syslog || (options & DBGTRC_OPTIONS_SYSLOG)) { if (test_emit_syslog(DDCA_SYSLOG_DEBUG) || dbgtrc_trace_to_syslog_only) { #ifdef PREV char * syslog_msg = g_strdup_printf("%s%s(%-30s) %s%s%s", thread_prefix, elapsed_prefix, funcname, retval_info, base_msg, (tag_output) ? " (J)" : ""); #endif char * syslog_msg = g_strdup_printf("%s(%-30s) %s%s%s", thread_prefix, funcname, retval_info, base_msg, (tag_output) ? " (J)" : ""); syslog(LOG_DEBUG, "%s", syslog_msg); free(syslog_msg); } else if ( (options & DBGTRC_OPTIONS_SEVERE) && test_emit_syslog(DDCA_SYSLOG_ERROR)) { char * syslog_msg = g_strdup_printf("%s(%-30s) %s%s%s", thread_prefix, funcname, retval_info, base_msg, (tag_output) ? " (K)" : "" ); syslog(LOG_ERR, "%s", syslog_msg); free(syslog_msg); } else if (redirect_reports_to_syslog) { syslog(LOG_NOTICE, "%s(%-30s) %s%s%s", thread_prefix, funcname, retval_info, base_msg, (tag_output) ? " (L)" : "" ); } if (!dbgtrc_trace_to_syslog_only && !stdout_stderr_redirected && !redirect_reports_to_syslog) { FILE * where = (options & DBGTRC_OPTIONS_SEVERE) ? thread_settings->ferr : thread_settings->fout; f0printf(where, "%s%s\n", decorated_msg, (tag_output) ? " (M)" : "" ); // f0puts(decorated_msg, where); // f0putc('\n', where); fflush(where); } free(decorated_msg); free(base_msg); msg_emitted = true; } } if (debug) printf("(%s) Done. Returning %s\n", __func__, sbool(msg_emitted)); return msg_emitted; } bool check_callstack(Dbgtrc_Options options, const char * funcname) { bool debug = false; // debug = debug || trace_callstack_call_depth > 0 || is_traced_callstack_call(funcname); if (debug) printf("\n(%s) Starting. options=0x%04x, funcname=%s, trace_callstack_call_depth=%d\n", __func__, options, funcname, trace_callstack_call_depth); if (options & DBGTRC_OPTIONS_STARTING) { if (trace_callstack_call_depth > 0) { trace_callstack_call_depth++; } else { if (is_traced_callstack_call(funcname)) { trace_callstack_call_depth = 1; } } DBGF(debug, " trace_callstack_call_depth=%d", trace_callstack_call_depth); } if ((options & DBGTRC_OPTIONS_DONE) && trace_callstack_call_depth > 0) { trace_callstack_call_depth--; } DBGF(debug, "Done. trace_callstack_call_depth=%d, returning %s", trace_callstack_call_depth, sbool(trace_callstack_call_depth > 0)); return trace_callstack_call_depth > 0; } /** Basic function for emitting debug or trace messages. * Normally wrapped in a DBGMSG or DBGTRC macro to simplify calling. * * The message is output if any of the following are true: * - the trace_group specified is currently active * - the value is trace group is 0xff * - funcname is the name of a function being traced * - filename is the name of a file being traced * * The message is output to the current FERR device and optionally, * depending on the syslog setting, to the system log. * * @param trace_group trace group of caller, DDCA_TRC_ALL = 0xffff to always output * @param options execution options * @param funcname function name of caller * @param lineno line number in caller * @param filename file name of caller * @param format format string for message * @param ... arguments for format string * * @return **true** if message was output, **false** if not */ bool dbgtrc( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * filename, char * format, ...) { bool debug = false; DBGF(debug, PRItid" Starting. trace_group=0x%04x, options=0x%02x, funcname=%s," " filename=%s, lineno=%d, thread=%jd, trace_callstack_call_depth=%d, fout() %s sysout", TID(), trace_group, options, funcname, filename, lineno, get_thread_id(), trace_callstack_call_depth, (fout() == stdout) ? "==" : "!="); bool msg_emitted = false; bool in_callstack = check_callstack(options, funcname); if ( in_callstack || is_tracing(trace_group, filename, funcname) ) { va_list(args); va_start(args, format); // DBGF(debug, "&args=%p, args=%p", &args, args); msg_emitted = vdbgtrc(trace_group, options, funcname, lineno, filename, "", format, args); va_end(args); } DBGF(debug, "Done. trace_callstack_call_depth=%d, Returning %s", trace_callstack_call_depth, sbool(msg_emitted)); return msg_emitted; } /** dbgtrc() variant that reports a numeric return code (normally of * type #DDCA_Status), in a standardized form. */ bool dbgtrc_ret_ddcrc( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * filename, int rc, char * format, ...) { bool debug = false; DBGF(debug, "Starting. trace_group = 0x%04x, funcname=%s," " filename=%s, lineno=%d, thread=%jd, fout() %s sysout, rc=%d, format=|%s|", trace_group, funcname, filename, lineno, get_thread_id(), (fout() == stdout) ? "==" : "!=", rc, format); bool msg_emitted = false; bool in_callstack = check_callstack(options, funcname); if ( in_callstack || is_tracing(trace_group, filename, funcname) ) { char pre_prefix[60]; g_snprintf(pre_prefix, 60, "Done Returning: %s. ", psc_name_code(rc)); DBGF(debug, "pre_prefix=|%s|", pre_prefix); va_list(args); va_start(args, format); // arm7l, aarch64: "on error: cannot convert to a pointer type" // DBGF(debug, "&args=%p, args=%p\n", (void*)&args, (void*)args); msg_emitted = vdbgtrc(trace_group, options, funcname, lineno, filename, pre_prefix, format, args); va_end(args); } DBGF(debug, "Done. Returning %s", sbool(msg_emitted)); return msg_emitted; } #ifdef UNTESTED // unnecessary, use dbgtrc_returning_expression() bool dbgtrc_ret_bool( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * filename, bool result, char * format, ...) { bool debug = false; if (debug) printf("(%s) Starting. trace_group = 0x%04x, funcname=%s" " filename=%s, lineno=%d, thread=%jd, fout() %s sysout, result=%s, format=|%s|\n", __func__, trace_group, funcname, filename, lineno, get_thread_id(), (fout() == stdout) ? "==" : "!=", sbool(result), format); bool msg_emitted = false; bool in_callstack = check_callstack(options, funcname); if ( in_callstack || is_tracing(trace_group, filename, funcname) ) { char pre_prefix[60]; g_snprintf(pre_prefix, 60, "Done Returning: %s. ", sbool(result)); if (debug) printf("(%s) pre_prefix=|%s|\n", __func__, pre_prefix); va_list(args); va_start(args, format); // arm7l, aarch64: "on error: cannot convert to a pointer type" // if (debug) // printf("(%s) &args=%p, args=%p\n", __func__, (void*)&args, (void*)args); msg_emitted = vdbgtrc(trace_group, options, funcname, lineno, filename, pre_prefix, format, args); va_end(args); } if (debug) printf("(%s) Done. Returning %s\n", __func__, sbool(msg_emitted)); return msg_emitted; } #endif /** dbgtrc() variant that reports a return code of type #Error_Info in a * standardized form. */ bool dbgtrc_returning_errinfo( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * filename, Error_Info * errs, char * format, ...) { bool debug = false; DBGF(debug, "Starting. trace_group = 0x%04x, funcname=%s, filename=%s," " lineno=%d, thread=%jd, fout() %s sysout, errs=%p, format=|%s|", trace_group, funcname, filename, lineno, get_thread_id(), (fout() == stdout) ? "==" : "!=", (void*)errs, format); bool msg_emitted = false; bool in_callstack = check_callstack(options, funcname); if ( in_callstack || is_tracing(trace_group, filename, funcname) ) { char * pre_prefix = g_strdup_printf("Done Returning: %s. ", errinfo_summary(errs)); if (debug) printf("(%s) pre_prefix=|%s|\n", __func__, pre_prefix); va_list(args); va_start(args, format); // arm7l, aarch64: "on error: cannot convert to a pointer type" // if (debug) // printf("(%s) &args=%p, args=%p\n", __func__, (void*)&args, (void*)args); msg_emitted = vdbgtrc(trace_group, options, funcname, lineno, filename, pre_prefix, format, args); va_end(args); g_free(pre_prefix); } DBGF(debug, "Done. Returning %s", sbool(msg_emitted)); return msg_emitted; } /** dbgtrc() variant that reports a return value specified as a string. */ bool dbgtrc_returning_string( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * filename, const char * retval, char * format, ...) { bool debug = false; DBGF(debug, "Starting. trace_group = 0x%04x, funcname=%s, filename=%s," "lineno=%d, thread=%jd, fout() %s sysout, retval=%s, format=|%s|", trace_group, funcname, filename, lineno, get_thread_id(), (fout() == stdout) ? "==" : "!=", retval, format); bool msg_emitted = false; bool in_callstack = check_callstack(options, funcname); if ( in_callstack || is_tracing(trace_group, filename, funcname) ) { char * pre_prefix = g_strdup_printf("Done Returning: %s. ", retval); if (debug) printf("(%s) pre_prefix=|%s|\n", __func__, pre_prefix); va_list(args); va_start(args, format); // arm7l, aarch64: "on error: cannot convert to a pointer type" // if (debug) // printf("(%s) &args=%p, args=%p\n", __func__, (void*)&args, (void*)args); msg_emitted = vdbgtrc(trace_group, options, funcname, lineno, filename, pre_prefix, format, args); va_end(args); free(pre_prefix); } DBGF(debug, "Done. Returning %s", sbool(msg_emitted)); return msg_emitted; } // // Standardized handling of exceptional conditions, including // error messages and possible program termination. // /** Called when a condition that should be impossible has been detected. * Issues messages to the current **FERR** device and the system log. * * This function is normally invoked using macro PROGRAM_LOGIC_ERROR() * * @param funcname function name * @param lineno line number in source file * @param fn source file name * @param format format string, as in printf() * @param ... one or more substitution values for the format string * * @ingroup output_redirection */ void program_logic_error( const char * funcname, const int lineno, const char * fn, char * format, ...) { // assemble the error message char buffer[200]; va_list(args); va_start(args, format); vsnprintf(buffer, 200, format, args); va_end(args); // assemble the location message: char buf2[250]; snprintf(buf2, 250, "Program logic error in function %s at line %d in file %s:", funcname, lineno, fn); // don't combine into 1 line, might be very long. just output 2 lines: FILE * f = ferr(); f0printf(f, "%s\n", buf2); f0printf(f, "%s\n", buffer); fflush(f); SYSLOG2(DDCA_SYSLOG_ERROR, "%s", buf2); SYSLOG2(DDCA_SYSLOG_ERROR, "%s", buffer); } #ifdef UNUSED void core_errmsg_emitter( GPtrArray* errmsgs, GPtrArray * errinfo_accum, bool verbose, int rc, const char * func, const char * msg, ...) { char buffer[200]; va_list(args); va_start(args, msg); vsnprintf(buffer, 100, msg, args); va_end(args); if (verbose || (!errmsgs && !errinfo_accum)) fprintf(ferr(), "%s\n", buffer); if (errinfo_accum) { Error_Info * erec = errinfo_new(rc, func, buffer); g_ptr_array_add(errinfo_accum, erec); } if (errmsgs) { g_ptr_array_add(errmsgs, g_strdup(buffer)); } } #endif // // Use system log // bool msg_to_syslog_only = false; DDCA_Syslog_Level syslog_level = DDCA_SYSLOG_NOT_SET; bool enable_syslog = true; Value_Name_Title_Table syslog_level_table = { VNT(DDCA_SYSLOG_DEBUG, "DEBUG"), VNT(DDCA_SYSLOG_VERBOSE, "VERBOSE"), VNT(DDCA_SYSLOG_INFO, "INFO"), VNT(DDCA_SYSLOG_NOTICE, "NOTICE"), VNT(DDCA_SYSLOG_WARNING, "WARN"), VNT(DDCA_SYSLOG_ERROR, "ERROR"), VNT(DDCA_SYSLOG_NEVER, "NEVER"), VNT_END }; const int syslog_level_ct = (ARRAY_SIZE(syslog_level_table)-1); const char * valid_syslog_levels_string = "DEBUG, VERBOSE, INFO, NOTICE, WARN, ERROR, NEVER"; const char * syslog_level_name(DDCA_Syslog_Level level) { char * result = "DDCA_SYSLOG_NOT_SET"; if (level != DDCA_SYSLOG_NOT_SET) result = vnt_name(syslog_level_table, level); return result; } DDCA_Syslog_Level syslog_level_name_to_value(const char * name) { return (DDCA_Syslog_Level) vnt_find_id(syslog_level_table, name, true, // search title field true, // ignore-case DDCA_SYSLOG_NOT_SET); } /** Given a message severity level, test whether it should be * written to the system log. * * @param msg_level severity of message * @return true if msg should be written to system log, false if not */ bool test_emit_syslog(DDCA_Syslog_Level msg_level) { bool result = (syslog_level != DDCA_SYSLOG_NOT_SET && syslog_level != DDCA_SYSLOG_NEVER && msg_level <= syslog_level); // DBG("syslog_level=%d=%s, msg_level=%d=%s, returning %s", // syslog_level, syslog_level_name(syslog_level), msg_level, syslog_level_name(msg_level), sbool(result)); return result; } /** Given a ddcutil severity level for messages written to the system log, * returns the syslog priority level to be used in a syslog() call. * * @param level ddcutil severity level * @return priority for syslog() call, * -1 for msg that should never be output */ int syslog_importance_from_ddcutil_syslog_level(DDCA_Syslog_Level level) { int priority = -1; switch(level) { case DDCA_SYSLOG_NOT_SET: priority = -1; break; case DDCA_SYSLOG_NEVER: priority = -1; break; case DDCA_SYSLOG_ERROR: priority = LOG_ERR; break; // 3 case DDCA_SYSLOG_WARNING: priority = LOG_WARNING; break; // 4 case DDCA_SYSLOG_NOTICE: priority = LOG_NOTICE; break; // 5 case DDCA_SYSLOG_INFO: priority = LOG_INFO; break; // 6 case DDCA_SYSLOG_VERBOSE: priority = LOG_INFO; break; // 6 case DDCA_SYSLOG_DEBUG: priority = LOG_DEBUG; break; // 7 } return priority; } // // Output capture - convenience functions // typedef struct { FILE * in_memory_file; char * in_memory_bufstart; ; size_t in_memory_bufsize; DDCA_Capture_Option_Flags flags; bool in_memory_capture_active; bool saved_rpt_to_syslog; } In_Memory_File_Desc; static In_Memory_File_Desc * get_thread_capture_buf_desc() { static GPrivate in_memory_key = G_PRIVATE_INIT(g_free); In_Memory_File_Desc* fdesc = g_private_get(&in_memory_key); // GThread * this_thread = g_thread_self(); // printf("(%s) this_thread=%p, fdesc=%p\n", __func__, this_thread, fdesc); if (!fdesc) { fdesc = g_new0(In_Memory_File_Desc, 1); g_private_set(&in_memory_key, fdesc); } // printf("(%s) Returning: %p\n", __func__, fdesc); return fdesc; } void start_capture(DDCA_Capture_Option_Flags flags) { bool debug = false; DBGF(debug,"Starting. flags=0x%02x", flags); In_Memory_File_Desc * fdesc = get_thread_capture_buf_desc(); // traced_function_stack_suspended = true; msg_decoration_suspended = true; if (!fdesc->in_memory_file) { fdesc->in_memory_file = open_memstream(&fdesc->in_memory_bufstart, &fdesc->in_memory_bufsize); } fdesc->saved_rpt_to_syslog = redirect_reports_to_syslog; redirect_reports_to_syslog = false; set_fout(fdesc->in_memory_file); // n. ddca_set_fout() is thread specific fdesc->flags = flags; if (flags & DDCA_CAPTURE_STDERR) set_ferr(fdesc->in_memory_file); fdesc->in_memory_capture_active = true; // DBGF(debug, "Done."); } char * end_capture(void) { bool debug = false; // DBGF(debug, "Starting"); In_Memory_File_Desc * fdesc = get_thread_capture_buf_desc(); assert(fdesc->in_memory_capture_active); char * result = NULL; // printf("(%s) Starting.\n", __func__); assert(fdesc->in_memory_file); if (fflush(fdesc->in_memory_file) < 0) { set_ferr_to_default(); SEVEREMSG("flush() failed. errno=%d", errno); // return g_strdup(result); result = g_strdup("\0"); } else { // n. open_memstream() maintains a null byte at end of buffer, not included in in_memory_bufsize result = g_strdup(fdesc->in_memory_bufstart); if (fclose(fdesc->in_memory_file) < 0) { set_ferr_to_default(); SEVEREMSG("fclose() failed. errno=%d", errno); result = g_strdup("\0"); } else { free(fdesc->in_memory_bufstart); fdesc->in_memory_file = NULL; } } set_fout_to_default(); if (fdesc->flags & DDCA_CAPTURE_STDERR) set_ferr_to_default(); redirect_reports_to_syslog = fdesc->saved_rpt_to_syslog; fdesc->in_memory_capture_active = false; // traced_function_stack_suspended = false; msg_decoration_suspended = false; DBGF(debug, "Done. result=%p", result); return result; } Null_Terminated_String_Array end_capture_as_ntsa() { char * result = end_capture(); Null_Terminated_String_Array lines = strsplit(result, "\n"); free(result); return lines; } #ifdef UNUSED /** Returns the current size of the in-memory capture buffer. * * @return number of characters in current buffer, plus 1 for * terminating null * @retval -1 no capture buffer on current thread * * @remark defined and tested but does not appear useful */ int captured_size() { // printf("(%s) Starting.\n", __func__); In_Memory_File_Desc * fdesc = get_thread_capture_buf_desc(); int result = -1; // n. open_memstream() maintains a null byte at end of buffer, not included in in_memory_bufsize if (fdesc->in_memory_file) { fflush(fdesc->in_memory_file); result = fdesc->in_memory_bufsize + 1; // +1 for trailing \0 } // printf("(%s) Done. result=%d\n", __func__, result); return result; } #endif /** Releases a #Error_Info instance, including all instances it points to. * Optionally reports the instance before freeing it, taking into account * syslog redirection. * * \param erec pointer to #Error_Info instance, * do nothing if NULL * \param report if true, report the instance * \param func name of calling function */ void base_errinfo_free_with_report( Error_Info * erec, bool report, const char * func) { if (erec) { if (report || report_freed_exceptions) { if ( dbgtrc_trace_to_syslog_only || redirect_reports_to_syslog) { GPtrArray * collector = g_ptr_array_new_with_free_func(g_free); rpt_vstring_collect(0, collector, "(%s) Freeing exception:", func); for (int ndx = 0; ndx < collector->len; ndx++) { syslog(LOG_NOTICE, "%s", (char*) g_ptr_array_index(collector, ndx)); } g_ptr_array_free(collector, true); } else { rpt_vstring(0, "(%s) Freeing exception:", func); errinfo_report(erec, 1); } } errinfo_free(erec); } } void detect_stdout_stderr_redirection() { bool debug = false; DBGF(debug, "Starting"); // syslog(LOG_ERR, "(%s)",msg); // msg_to_syslog_only = true; // MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "msg_to_syslog_only = true"); // msg_to_syslog_only = false; // MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "msg_to_syslog_only = false"); char * s = realpath("/sbin/init", NULL); char * initsys = NULL; if (!s) { // pathological initsys = g_strdup_printf("UNKNOWN"); } else { initsys = g_path_get_basename(s); free(s); } DBGF(debug, "Init system: %s", initsys); free(initsys); char * stdout_fn = NULL; filename_for_fd(1, &stdout_fn); DBGF(debug, "stdout file name: %s", stdout_fn); stdout_stderr_redirected = (str_contains(stdout_fn, "socket") >= 0); free(stdout_fn); DBGF(debug, "set stdout_stderr_redirected = %s", SBOOL(stdout_stderr_redirected)); // stdout_stderr_redirected = false; // *** TEMP **** // DBG("Forced stdout_stderr_redirected = false for testing"); #ifdef OLD char * initsys = execute_shell_cmd_one_line_result("ps -p 1 -o comm="); DBGF(debug, "Using init system: %s", initsys); // need to check if initsys is a symbolic link and if so what it points to, use stat command free(initsys); #endif // shows nothing // show_backtrace(1); // syslog(LOG_ERR, "stdout file name: %s", filename_for_fd_t(1)); char * journalstream = getenv("JOURNAL_STREAM"); // do not free DBGF(debug, "$JOURNAL_STREAM = %s", journalstream); // MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "$JOURNAL_STREAM = %s", journalstream); // char * s = getenv("INVOCATION_ID"); // do not free // DBG("$INVOCATION_ID = %s", s); // MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "$INVOCATION_ID = %s", s); DBGF(debug, "Done"); } void init_core() { bool debug = false; DBGF(debug, "Starting"); // detect_sysout_syserr_redirection(); DBGF(debug, "Done"); } ddcutil-2.2.0/src/base/core_per_thread_settings.c0000644000175000001440000002054214754576332015555 /** \f core_per_thread_settings.c */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include /** \endcond */ #include "util/debug_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "ddcutil_types.h" #include "core_per_thread_settings.h" // // Global SDTOUT and STDERR redirection, for controlling message output in API // /** @defgroup output_redirection Basic Output Redirection */ #ifdef OVERKILL #define FOUT_STACK_SIZE 8 static FILE* fout_stack[FOUT_STACK_SIZE]; static int fout_stack_pos = -1; #endif // controls access to default_thread_output_settings static GMutex default_thread_output_settings_mutex; static Thread_Output_Settings * default_thread_output_settings = NULL; static void allocate_default_thread_output_settings() { default_thread_output_settings = g_new0(Thread_Output_Settings, 1); default_thread_output_settings->fout = stdout; default_thread_output_settings->ferr = stderr; default_thread_output_settings->output_level = DDCA_OL_NORMAL; } /** Gets all settings to be used for new threads */ static Thread_Output_Settings * get_default_thread_output_settings() { g_mutex_lock(&default_thread_output_settings_mutex); if ( !default_thread_output_settings ) allocate_default_thread_output_settings(); // return a copy so that struct is in a consistent state when used by the caller Thread_Output_Settings * result = g_new0(Thread_Output_Settings, 1); memcpy(result, default_thread_output_settings, sizeof(Thread_Output_Settings)); g_mutex_unlock(&default_thread_output_settings_mutex); return result; } /** Sets the fout and ferr values to be used for newly created threads * * \param fout destination for output that would normally be directed to **stdout** * \param ferr destination for output that would normally be directed to **stderr** */ void set_default_thread_output_settings(FILE * fout, FILE * ferr) { bool debug = false; DBGF(debug, "fout=%p, ferr=%p, stdout=%p, stderr=%p", (void*)fout, (void*)ferr, (void*)stdout, (void*)stderr); g_mutex_lock(&default_thread_output_settings_mutex); if ( !default_thread_output_settings ) allocate_default_thread_output_settings(); if (fout) default_thread_output_settings->fout = fout; if (ferr) default_thread_output_settings->ferr = ferr; g_mutex_unlock(&default_thread_output_settings_mutex); } /** Sets the output_level to be used for newly created threads * * \param ol output level */ void set_default_thread_output_level(DDCA_Output_Level ol) { bool debug = false; DBGF(debug, "ol=%s", output_level_name(ol)); g_mutex_lock(&default_thread_output_settings_mutex); if ( !default_thread_output_settings ) allocate_default_thread_output_settings(); default_thread_output_settings->output_level = ol; g_mutex_unlock(&default_thread_output_settings_mutex); } /** Gets Thread_Output_Settings struct for the current thread * * \return pointer to Thread_Output_Settings struct */ Thread_Output_Settings * get_thread_settings() { static GPrivate per_thread_dests_key = G_PRIVATE_INIT(g_free); bool debug = false; Thread_Output_Settings *settings = g_private_get(&per_thread_dests_key); // GThread * this_thread = g_thread_self(); // printf("(%s) this_thread=%p, settings=%p\n", __func__, this_thread, settings); if (!settings) { settings = get_default_thread_output_settings(); settings->tid = get_thread_id(); g_private_set(&per_thread_dests_key, settings); DBGF(debug, "Allocated settings=%p for thread %jd," " fout=%p, ferr=%p, stdout=%p, stderr=%p", (void*)settings, settings->tid, (void*)settings->fout, (void*)settings->ferr, (void*)stdout, (void*)stderr); } // printf("(%s) Returning: %p\n", __func__, settings); return settings; } // Issue: How to specify that output should be discarded vs reset to stdout? // Issue: Will resetting report dest cause conflicts? // Note: The obvious solution of using constant stdout in studio.h to reset // output to STDOUT screws up rpt_util /** Redirect output on the current thread that would normally be directed to **stdout**. * * @param fout pointer to output stream * * @ingroup output_redirection */ void set_fout(FILE * fout) { bool debug = false; Thread_Output_Settings * dests = get_thread_settings(); dests->fout = fout; DBGF(debug, "tid=%jd, dests=%p, fout=%p, stdout=%p", dests->tid, (void*)dests, (void*)fout, (void*)stdout); rpt_change_output_dest(fout); } /** Redirect output that would normally be directed to **stdout** back to **stdout**. * @ingroup output_redirection */ void set_fout_to_default() { // FOUT = stdout; Thread_Output_Settings * default_settings = get_default_thread_output_settings(); Thread_Output_Settings * dests = get_thread_settings(); dests->fout = default_settings->fout; free(default_settings); rpt_change_output_dest(dests->fout); } /** Redirect output that would normally be directed to **stderr**.. * * @param ferr pointer to output stream * * @ingroup output_redirection */ void set_ferr(FILE * ferr) { Thread_Output_Settings * dests = get_thread_settings(); dests->ferr = ferr; } /** Redirect output that would normally be directed to **stderr** back to **stderr**. * @ingroup output_redirection */ void set_ferr_to_default() { Thread_Output_Settings * default_settings = get_default_thread_output_settings(); Thread_Output_Settings * dests = get_thread_settings(); dests->ferr = default_settings->ferr; free(default_settings); } /** Gets the "stdout" destination for the current thread * * @return output destination * * @ingroup output_redirection */ FILE * fout() { Thread_Output_Settings * dests = get_thread_settings(); // printf("(%s) tid=%ld, dests=%p, dests->fout=%p, stdout=%p\n", // __func__, get_thread_id(), dests, dests->fout, stdout); return dests->fout; } /** Gets the "stderr" destination for the current thread * * @return output destination * * @ingroup output_redirection */ FILE * ferr() { Thread_Output_Settings * dests = get_thread_settings(); return dests->ferr; } #ifdef OVERKILL // Functions that allow for temporarily changing the output destination. void push_fout(FILE* new_dest) { assert(fout_stack_pos < FOUT_STACK_SIZE-1); fout_stack[++fout_stack_pos] = new_dest; } void pop_fout() { if (fout_stack_pos >= 0) fout_stack_pos--; } void reset_fout_stack() { fout_stack_pos = 0; } FILE * cur_fout() { // special handling for unpushed case because can't statically initialize // output_dest_stack[0] to stdout return (fout_stack_pos < 0) ? stdout : fout_stack[fout_stack_pos]; } #endif // // Message level control for normal output // /** \defgroup msglevel Message Level Management * * Functions and variables to manage and query output level settings. */ /** Returns the output level for the current thread * * @return output level * * \ingroup msglevel */ DDCA_Output_Level get_output_level() { Thread_Output_Settings * settings = get_thread_settings(); return settings->output_level; } /** Sets the output level for the current thread * * @param newval output level to set * @return old output level * * \ingroup msglevel */ DDCA_Output_Level set_output_level(DDCA_Output_Level newval) { Thread_Output_Settings * settings = get_thread_settings(); DDCA_Output_Level old_level = settings->output_level; settings->output_level = newval; return old_level; } /** Gets the printable name of an output level. * * @param val output level * @return printable name for output level * * \ingroup msglevel */ // const adding "const" causes api change ddca_output_level_name(), defer until next api change char * output_level_name(DDCA_Output_Level val) { char * result = NULL; switch (val) { case DDCA_OL_TERSE: result = "Terse"; break; case DDCA_OL_NORMAL: result = "Normal"; break; case DDCA_OL_VERBOSE: result = "Verbose"; break; case DDCA_OL_VV: result = "Very Vebose"; // default unnecessary, case exhausts enum } return result; } ddcutil-2.2.0/src/base/ddc_command_codes.c0000644000175000001440000000420114634171455014101 /** \file ddc_command_codes.c * DDC/CI command codes */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "ddc_command_codes.h" #include #include #include #include "util/string_util.h" // // DDC Command and Response Codes // typedef struct { Byte cmd_code; char * name; } Cmd_Code_Table_Entry; Cmd_Code_Table_Entry cmd_code_table[] = { {CMD_VCP_REQUEST , "VCP Request" }, {CMD_VCP_RESPONSE , "VCP Response" }, {CMD_VCP_SET , "VCP Set" }, {CMD_TIMING_REPLY , "Timing Reply "}, {CMD_TIMING_REQUEST , "Timing Request" }, {CMD_VCP_RESET , "VCP Reset" }, {CMD_SAVE_SETTINGS , "Save Settings" }, {CMD_SELF_TEST_REPLY , "Self Test Reply" }, {CMD_SELF_TEST_REQUEST , "Self Test Request" }, {CMD_ID_REPLY , "Identification Reply"}, {CMD_TABLE_READ_REQUST , "Table Read Request" }, {CMD_CAPABILITIES_REPLY , "Capabilities Reply" }, {CMD_TABLE_READ_REPLY , "Table Read Reply" }, {CMD_TABLE_WRITE , "Table Write" }, {CMD_ID_REQUEST , "Identification Request" }, {CMD_CAPABILITIES_REQUEST , "Capabilities Request" }, {CMD_ENABLE_APP_REPORT , "Enable Application Report" } }; static int ddc_cmd_code_count = sizeof(cmd_code_table)/sizeof(Cmd_Code_Table_Entry); static Cmd_Code_Table_Entry * get_ddc_cmd_struct_by_id(Byte cmd_id) { // DBGMSG("Starting. id=0x%02x ", id ); int ndx = 0; Cmd_Code_Table_Entry * result = NULL; for (;ndx < ddc_cmd_code_count; ndx++) { if (cmd_id == cmd_code_table[ndx].cmd_code) { result = &cmd_code_table[ndx]; break; } } // DBGMSG("Done. ndx=%d. returning %p", ndx, result); return result; } char * ddc_cmd_code_name(Byte command_id) { char * result = NULL; Cmd_Code_Table_Entry * cmd_entry = get_ddc_cmd_struct_by_id(command_id); if (cmd_entry) result = cmd_entry->name; else result ="Unrecognized operation code"; return result; } ddcutil-2.2.0/src/base/ddc_errno.c0000644000175000001440000001733114754153540012441 /** \file * Error codes internal to **ddcutil**. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include /** \endcond */ #include "util/debug_util.h" #include "util/glib_util.h" #include "util/string_util.h" #include "base/ddc_errno.h" // // DDCRC status code descriptions // // Keep in sync with status codes in ddcutil_status_codes.h // // TODO: Consider modifying EDENTRY generate doxygen comment as well using description field #define EDENTRY(id,desc) {id, #id, desc} // DDCRC_DOUBLE_BYTE probably not worth keeping, can only reliably check for // small subset of DDCRC_PACKET_SIZE, DDCRC_RESPONSE_ENVELOPE, DDCRC_CHECKSUM static Status_Code_Info ddcrc_info[] = { EDENTRY(DDCRC_OK , "success" ), EDENTRY(DDCRC_DDC_DATA , "DDC data error" ), EDENTRY(DDCRC_NULL_RESPONSE , "received DDC null response" ), EDENTRY(DDCRC_MULTI_PART_READ_FRAGMENT , "error in fragment" ), EDENTRY(DDCRC_ALL_TRIES_ZERO , "every try all response bytes 0x00" ), EDENTRY(DDCRC_REPORTED_UNSUPPORTED , "DDC reports facility unsupported" ), EDENTRY(DDCRC_READ_ALL_ZERO , "packet contents entirely 0x00" ), EDENTRY(DDCRC_RETRIES , "maximum retries exceeded" ), EDENTRY(DDCRC_EDID , "invalid EDID" ), EDENTRY(DDCRC_READ_EDID , "unable to read EDID" ), EDENTRY(DDCRC_INVALID_EDID , "unable to parse EDID" ), EDENTRY(DDCRC_ALL_RESPONSES_NULL , "all tries returned DDC Null Message"), EDENTRY(DDCRC_DETERMINED_UNSUPPORTED , "ddcutil determined that facility unsupported" ), // library errors EDENTRY(DDCRC_ARG , "illegal argument"), EDENTRY(DDCRC_INVALID_OPERATION , "invalid operation"), EDENTRY(DDCRC_UNIMPLEMENTED , "unimplemented"), EDENTRY(DDCRC_UNINITIALIZED , "library uninitialized"), EDENTRY(DDCRC_UNKNOWN_FEATURE , "feature not in feature table"), EDENTRY(DDCRC_INTERPRETATION_FAILED , "feature value interpretation function failed"), EDENTRY(DDCRC_MULTI_FEATURE_ERROR , "at least 1 error occurred on a multi-feature request"), EDENTRY(DDCRC_INVALID_DISPLAY , "invalid display"), EDENTRY(DDCRC_INTERNAL_ERROR , "fatal error condition"), EDENTRY(DDCRC_OTHER , "other error"), // for use during development EDENTRY(DDCRC_VERIFY , "VCP read after write failed"), EDENTRY(DDCRC_NOT_FOUND , "not found"), EDENTRY(DDCRC_LOCKED , "display locked"), EDENTRY(DDCRC_ALREADY_OPEN , "already open in current thread"), EDENTRY(DDCRC_BAD_DATA , "invalid data"), EDENTRY(DDCRC_CONFIG_ERROR , "invalid configuration arg or config file error"), EDENTRY(DDCRC_DISCONNECTED , "display no longer connected"), EDENTRY(DDCRC_DPMS_ASLEEP , "display is in a DPMS sleep mode"), EDENTRY(DDCRC_FLOCKED , "another process holds flock"), EDENTRY(DDCRC_QUIESCED , "library operations temporarily unavailable"), // EDENTRY(DDCRC_CAP_FATAL , "incorrect, unusable capabilities string"), // EDENTRY(DDCRC_CAP_WARNING , "errors in capabilities string, but usable") }; #undef EDENTRY static int ddcrc_desc_ct = sizeof(ddcrc_info)/sizeof(Status_Code_Info); /** Returns the #Status_Code_Info struct for a **ddcutil** status code. * * @param rc ddcutil status code * @return pointer to #Status_Code_Info, NULL if not found * * @remark * Returns a pointer into a struct compiled into the executable. * Do not deallocate. * @remark * **ddcutil** status codes are always modulated. */ Status_Code_Info * ddcrc_find_status_code_info(int rc) { Status_Code_Info * result = NULL; for (int ndx=0; ndx < ddcrc_desc_ct; ndx++) { if (rc == ddcrc_info[ndx].code) { result = &ddcrc_info[ndx]; break; } } return result; } /* Status code classification DDCRC_NULL_RESPONSE DDCRC_ALL_TRIES_ZERO DDCRC_REPORTED_UNSUPPORTED DDCRC_DETERMINED_UNSUPPORTED DDCRC_REPORTED_UNSUPPORTED is a primary error, but reports a state, not really an error Derived codes are set after function has examined a primary code Do not count as DDC errors. Derived: DDCRC_ALL_TRIES_ZERO DDCRC_RETRIES DDCRC_DETERMINED_UNSUPPORTED DDCRC NULL_RESPONSE is ambiguous can be expected (DDC detection) no answer to give, e.g. because not ready, not expected (protocol error) but also is used by some monitors to indicate invalid request (e.g. unsupported VCP code) All others indicate real, primary errors Issues: - DDCRC_REPORTED_UNSUPPORTED should not be a fatal failure in try_stats, it is a successful try, it's just that the response is "unsupported" * */ /** Certain **ddcutil** status codes (e.g. DDCRC_DETERMINED_UNSUPPORTED) * are "derived" at higher levels from primary **ddcutil** status codes * in lower level routines. These should be excluded from certain error * counts as otherwise an error would be double counted. * * @param gsc status code * @return true/false */ bool ddcrc_is_derived_status_code(Public_Status_Code gsc) { return (gsc == DDCRC_ALL_TRIES_ZERO || gsc == DDCRC_RETRIES || gsc == DDCRC_DETERMINED_UNSUPPORTED ); } /** Certain **ddcutil** status codes, (e.g. DDCRC_REPORTED_UNSUPPORTED) * report states that should not be considered to be DDC protocol errors. */ bool ddcrc_is_not_error(Public_Status_Code gsc) { return (gsc == DDCRC_REPORTED_UNSUPPORTED); } /* Returns a sting description of a **ddcutil** status code. * This description is intended for use in error messages. * * @param rc ddcutil status code * @return status code description * * @remark * The result is built in an internal thread-specific buffer. The contents * will be valid until the next call to this function in the current thread. * @remark * A generic message is returned if the status code is unrecognized. */ char * ddcrc_desc_t(int rc) { static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * workbuf = get_thread_fixed_buffer(&buf_key, 200); Status_Code_Info * pdesc = ddcrc_find_status_code_info(rc); if (pdesc) { g_snprintf(workbuf, 200, "%s(%d): %s", pdesc->name, rc, pdesc->description); } else { g_snprintf(workbuf, 200, "Unexpected status code %d", rc); } return workbuf; } /** Gets the (unmodulated) ddcutil error number for a symbolic name. * * @param error_name symbolic name, e.g. DDCRC_CHECKSUM * @param errnum_loc where to return error number * * Returns: true if found, false if not * * @remark * Since **ddcutil** specific error numbers are always modulated, * the return value for this function is always identical to * ddc_error_name_to_modulated_number(). */ bool ddc_error_name_to_number(const char * error_name, Status_DDC * errnum_loc) { bool debug = false; DBGF(debug, "Starting. error_name=%s", error_name); int found = false; *errnum_loc = 0; for (int ndx = 0; ndx < ddcrc_desc_ct; ndx++) { if ( streq(ddcrc_info[ndx].name, error_name) ) { *errnum_loc = ddcrc_info[ndx].code; found = true; break; } } DBGF(debug, "Done. Returning: %s, *errnum_loc = %d", SBOOL(found), *errnum_loc); return found; } ddcutil-2.2.0/src/base/ddc_packets.c0000644000175000001440000013016414754153540012746 /** @file ddc_packets.c * * Functions for creating DDC packets and interpreting DDC response packets. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include "util/report_util.h" #include "util/string_util.h" #include "util/utilrpt.h" /** \endcond */ #include "base/core.h" #include "base/ddc_errno.h" #include "base/execution_stats.h" #include "base/rtti.h" #include "base/ddc_packets.h" // // Trace control // static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDCIO; // // Utilities // /* Tests if a byte is equal to the preceding byte * * Arguments: pb pointer to byte (test this byte and *(pb-1) * * Returns: * true/false */ bool is_double_byte(Byte * pb) { Byte * pb0 = pb-1; // DBGMSG("pb=%p, pb0=%p, *pb=0x%02x *pb0=0x%02x ", pb, pb0, *pb, *pb0 ); bool result = (*pb == *pb0); // DBGMSG("Returning: %d ", result ); return result; } // // Checksums // #ifdef OLD Byte xor_bytes(Byte * bytes, int len) { Byte result = 0x00; int ndx; for (ndx=0; ndx < len; ndx++) { result = result ^ bytes[ndx]; } return result; } #endif /** Calculates the checksum of a DDC message. * \param bytes pointer to bytes of message * \param len length of message * \param altmode if true, use x50 as the value of bytes[0], * which is the destination address */ Byte ddc_checksum(Byte * bytes, int len, bool altmode) { // DBGMSG("bytes=%p, len=%d, altmode=%s", bytes, len, SBOOL(altmode)); assert(len >= 1); Byte checksum = bytes[0]; if (altmode) checksum = 0x50; for (int ndx = 1; ndx < len; ndx++) { checksum ^= bytes[ndx]; } return checksum; } #ifdef TESTCASES void test_one_checksum(Byte * bytes, int len, bool altmode, Byte expected, char * spec_section) { unsigned char actual = ddc_checksum(bytes, len, altmode); char * hs = hexstring(bytes, len); printf( "bytes=%s, altmode=%d, expected=0x%02x, actual=0x%02x, spec section=%s\n", hs, altmode, expected, actual, spec_section ); free(hs); } void test_checksum() { puts("\ntest_checksum\n"); Byte bytes[] = {0x6e, 0x51, 0x82, 0xf5, 0x01}; test_one_checksum( bytes, 5, false, 0x49, "6.2" ); test_one_checksum( (Byte[]) {0x6e, 0x51, 0x81, 0xb1}, 4, false, 0x0f, "6.3" ); test_one_checksum( (Byte[]) {0x6f, 0x6e, 0x82, 0xa1, 0x00}, 5, true, 0x1d, "6.3" ); test_one_checksum( (Byte[]) {0x6f, 0x6e, 0x80}, 3, true, 0xbe, "6.4" ); test_one_checksum( (Byte[]) {0xf0, 0xf1, 0x81, 0xb1}, 4, false, 0x31, "7.4" ); test_one_checksum( (Byte[]) {0x6e, 0xf1, 0x81, 0xb1}, 4, false, 0xaf, "7.4" ); test_one_checksum( (Byte[]) {0xf1, 0xf0, 0x82, 0xa1, 0x00}, 5, true, 0x83, "7.4"); test_one_checksum( (Byte[]) {0x6f, 0xf0, 0x82, 0xa1, 0x00}, 5, true, 0x83, "7.4"); } #endif #ifdef UNUSED bool valid_ddc_packet_checksum(Byte * readbuf) { bool debug = false; bool result = false; int data_size = (readbuf[2] & 0x7f); if (data_size > MAX_DDCCI_PACKET_SIZE) { // correct constant? DDCMSG(debug, "Invalid data_size = %d", data_size); } else { int response_size_wo_checksum = 3 + data_size; readbuf[1] = 0x51; // dangerous unsigned char expected_checksum = ddc_checksum(readbuf, response_size_wo_checksum, false); unsigned char actual_checksum = readbuf[response_size_wo_checksum]; DBGMSF(debug, "data_size=%d, actual checksum = 0x%02x, expected = 0x%02x", data_size, actual_checksum, expected_checksum); result = (expected_checksum == actual_checksum); } DBGMSF(debug, "Returning: %d", result); return result; } #endif // // Packet general functions // /** Returns a pointer to the raw bytes of a #DDC_Packet. * \param pointer to packet * \return pointer to raw bytes of the packet */ Byte * get_packet_start(DDC_Packet * packet) { Byte * result = NULL; if (packet) result = packet->raw_bytes->bytes; return result; } /** Returns the total length of the raw bytes of a #DDC_Packet * \param pointer to packet * \param packet length */ int get_packet_len(DDC_Packet * packet) { return (packet) ? packet->raw_bytes->len : 0; } /** Returns the length of the data portion of a #DDC_Packet * \param pointer to packet * \return length of data portion */ int get_data_len(DDC_Packet * packet) { return (packet) ? packet->raw_bytes->len - 4 : 0; } /** Returns the start of the data portion of a #DDC_Packet * \param pointer to packet * \return pointer to the data portion */ Byte * get_data_start(DDC_Packet * packet) { return (packet) ? packet->raw_bytes->bytes+3 : NULL; } /** Returns the maximum size of the raw bytes buffer in a #DDC_Packet * \param pointer to packet * \return maximum data size */ int get_packet_max_size(DDC_Packet * packet) { return packet->raw_bytes->buffer_size; } /** Checks if a packet contains a DDC Null Message. * A null message has 0 length. * \param pointer to packet * \return true if the packet contains a DDC Null Message, false if not * * Per the DDC/CI spec, Section 6.4 Definition and use of the "Null Message": * * The NULL message is used in the following cases: * - To detect that the display is DDC/CI capable (by reading it at the 0x6F slave address) * - To tell the host that the display does not have any answer to give the host * (not ready or not expected) * - The "Enable Application Report" has not been sent before using Application Messages * * From various NEC monitor manuals: * * The NULL messages returned from the monitor is used in the following cases: * - To tell the host that the display does not have any answer to give the host * (not ready or not expected) * - Following operations need a certain time for to (sic) execute, so the monitor * will return this message when another message is received during execution. * - Power ON, Power OFF, Auto Setup, Input, PIP Input, Auto Setup and Factory reset. */ bool isNullPacket(DDC_Packet * packet) { return (get_data_len(packet) == 0); } /** Frees a #DDC_Packet * * \param packet pointer to packet to free */ void free_ddc_packet(DDC_Packet * packet) { bool debug = false; DBGMSF(debug, "packet=%p", packet); // dump_packet(packet); if (packet) { if (packet->parsed.raw_parsed) { DBGMSF(debug, "freeing packet->parsed.raw_parsed=%p", packet->parsed.raw_parsed); free(packet->parsed.raw_parsed); } DBGMSF(debug, "calling free_buffer() for packet->buf=%p", packet->raw_bytes); buffer_free(packet->raw_bytes, "free DDC packet"); DBGMSF(debug, "freeing packet=%p", packet); free(packet); } DBGMSF(debug, "Done" ); } /** Base function for creating any DDC packet * * \param max_size size of buffer allocated for packet bytes * \param tag debug string (may be NULL) * \return pointer to newly allocated #DDC_Packet */ DDC_Packet * create_empty_ddc_packet(int max_size, const char * tag) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "max_size=%d, tag=%s", max_size, (tag) ? tag : "(nil)"); DDC_Packet * packet = malloc(sizeof(DDC_Packet)); packet->raw_bytes = buffer_new(max_size, "empty DDC packet"); if (tag) { strncpy(packet->tag, tag, sizeof(packet->tag)); // no need to check if packet->tag truncated packet->tag[sizeof(packet->tag)-1] = '\0'; } else packet->tag[0] = '\0'; // DBGMSG("packet->tag=%s", packet->tag); packet->type = DDC_PACKET_TYPE_NONE; packet->parsed.raw_parsed = NULL; DBGTRC_RET_STRUCT(debug, TRACE_GROUP, DDC_Packet, dbgrpt_packet, packet); return packet; } // // Request Packets // /** Creates a generic DDC request packet * * \param data_bytes data bytes of packet * \param data_bytect number of data bytes * \param tag debug string (may be NULL) * \return pointer to created packet */ DDC_Packet * create_ddc_base_request_packet( Byte source_addr, Byte * data_bytes, int data_bytect, const char* tag) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "source_addr=0x%02x, data_bytes=%s, tag=%s", source_addr, hexstring_t(data_bytes,data_bytect), tag); assert( data_bytect <= 32 ); DDC_Packet * packet = create_empty_ddc_packet(3+data_bytect+1, tag); buffer_set_byte( packet->raw_bytes, 0, 0x6e); // x37<<1 + 0 destination address, write buffer_set_byte( packet->raw_bytes, 1, source_addr); // x28<<1 + 1 source address buffer_set_byte( packet->raw_bytes, 2, data_bytect | 0x80); buffer_set_bytes(packet->raw_bytes, 3, data_bytes, data_bytect); int packet_size_wo_checksum = 3 + data_bytect; Byte checksum = ddc_checksum(packet->raw_bytes->bytes, packet_size_wo_checksum, false); buffer_set_byte(packet->raw_bytes, packet_size_wo_checksum, checksum); buffer_set_length(packet->raw_bytes, 3 + data_bytect + 1); if (data_bytect > 0) packet->type = data_bytes[0]; else packet->type = 0x00; // dump_buffer(packet->buf); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "DDC_Packet", dbgrpt_packet, packet); return packet; } /** Creates a DDC VCP table read request packet * * \param request_type DDC_PACKET_TYPE_CAPABILITIES_REQUEST or * DDC_PACKET_TYPE_TABLE_READ_REQUEST * \param request_subtype VCP code if reading table type feature, ignored for capabilities * \param offset offset value * \param tag debug string (may be null) * \return pointer to created capabilities request packet */ DDC_Packet * create_ddc_multi_part_read_request_packet( Byte request_type, Byte request_subtype, int offset, const char* tag) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "request_type=0x%02x, request_subtype=0x%02x, offset=%d, tag=%s", request_type, request_subtype, offset, tag); assert (request_type == DDC_PACKET_TYPE_CAPABILITIES_REQUEST || request_type == DDC_PACKET_TYPE_TABLE_READ_REQUEST ); DDC_Packet * packet_ptr = NULL; Byte ofs_hi_byte = (offset >> 16) & 0xff; Byte ofs_lo_byte = offset & 0xff; if (request_type == DDC_PACKET_TYPE_CAPABILITIES_REQUEST) { Byte data_bytes[] = { DDC_PACKET_TYPE_CAPABILITIES_REQUEST , ofs_hi_byte, ofs_lo_byte }; packet_ptr = create_ddc_base_request_packet(0x51, data_bytes, 3, tag); } else { Byte data_bytes[] = { DDC_PACKET_TYPE_TABLE_READ_REQUEST, request_subtype, // VCP code ofs_hi_byte, ofs_lo_byte }; packet_ptr = create_ddc_base_request_packet(0x51, data_bytes, 4, tag); } // DBGMSG("Done. packet_ptr=%p", packet_ptr); // dump_packet(packet_ptr); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "DDC_Packet", dbgrpt_packet, packet_ptr); return packet_ptr; } /** Updates the offset in a multi part read request packet * * \param packet address of packet * \offset offset new offset value */ void update_ddc_multi_part_read_request_packet_offset( DDC_Packet * packet, int new_offset) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "packet=%p, new_offset=%d", packet, new_offset); assert (packet->type == DDC_PACKET_TYPE_CAPABILITIES_REQUEST || packet->type == DDC_PACKET_TYPE_TABLE_READ_REQUEST ); // update offset Byte ofs_hi_byte = (new_offset >> 8) & 0xff; // ofs_hi_byte = 0x00; // *** TEMP *** INSERT BUG Byte ofs_lo_byte = new_offset & 0xff; Byte * data_bytes = get_data_start(packet); if (packet->type == DDC_PACKET_TYPE_CAPABILITIES_REQUEST) { data_bytes[1] = ofs_hi_byte; data_bytes[2] = ofs_lo_byte; } else { data_bytes[2] = ofs_hi_byte; // changed from update_ddc_capabilities_request_offset data_bytes[3] = ofs_lo_byte; // changed ... } // DBGMSG("offset=%d, ofs_hi_byte=0x%02x, ofs_lo_byte=0x%02x", new_offset, ofs_hi_byte, ofs_lo_byte ); // update checksum Byte * bytes = get_packet_start(packet); int packet_size_wo_checksum = get_packet_len(packet)-1; bytes[packet_size_wo_checksum] = ddc_checksum(bytes, packet_size_wo_checksum, false); // DBGMSG("Done."); // dump_packet(packet); DBGTRC_DONE(debug, TRACE_GROUP, ""); if (IS_DBGTRC(debug, TRACE_GROUP)) { dbgrpt_packet(packet, 2); } } /** Creates a DDC VCP table write request packet * * \param request_type always DDC_PACKET_TYPE_WRITE_REQUEST * \param request_subtype VCP code * \param offset offset value * \param bytes_to_write pointer to bytes to write * \param bytect number of bytes to write * \param tag debug string * \return pointer to newly created created multi-part-write request packet */ DDC_Packet * create_ddc_multi_part_write_request_packet( Byte request_type, // always DDC_PACKET_TYPE_WRITE_REQUEST Byte request_subtype, // VCP code int offset, Byte * bytes_to_write, int bytect, const char * tag) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "request_type=0x%02x, request_subtype=0x%02x, offset=%d, bytect=%d, bytes_to_write=%p->%s", request_type, request_subtype, offset, bytect, bytes_to_write, hexstring_t(bytes_to_write, bytect)); assert (request_type == DDC_PACKET_TYPE_TABLE_WRITE_REQUEST ); assert (bytect + 4 <= 35); // is this the right limit?, spec unclear DDC_Packet * packet_ptr = NULL; Byte ofs_hi_byte = (offset >> 16) & 0xff; Byte ofs_lo_byte = offset & 0xff; Byte data_bytes[40] = { DDC_PACKET_TYPE_TABLE_WRITE_REQUEST, request_subtype, // VCP code ofs_hi_byte, ofs_lo_byte }; memcpy(data_bytes+4, bytes_to_write, bytect); packet_ptr = create_ddc_base_request_packet(0x51, data_bytes, 4+bytect, tag); // DBGMSG("Done. packet_ptr=%p", packet_ptr); // dump_packet(packet_ptr); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "DDC_Packet", dbgrpt_packet, packet_ptr); return packet_ptr; } Byte alt_source_addr = 0x00; /** Creates a Get VCP request packet * * \param vcp_code VCP feature code * \param tag debug string * \return pointer to created DDC packet */ DDC_Packet * create_ddc_getvcp_request_packet(Byte vcp_code, const char * tag) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "vcp_code = 0x%02x, tag = %s", vcp_code, tag); Byte cmd_code = DDC_PACKET_TYPE_QUERY_VCP_REQUEST; // 0x01 // if (alt_cmd_code) // cmd_code = alt_cmd_code; Byte data_bytes[] = { cmd_code, vcp_code // VCP opcode }; DDC_Packet * pkt = create_ddc_base_request_packet(0x51, data_bytes, 2, tag); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "DDC_Packet",dbgrpt_packet,pkt); return pkt; } /** Creates a Set VCP request packet * * \param vcp_code VCP feature code * \param int new value * \param tag debug string * \return pointer to created DDC packet */ DDC_Packet * create_ddc_setvcp_request_packet(Byte vcp_code, int new_value, const char * tag) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "vcp_code=0x%02x, new_value=%d, tag=%s", vcp_code, new_value, tag); Byte cmd_code = DDC_PACKET_TYPE_SET_VCP_REQUEST; // 0x03 Byte source_addr = 0x51; if (alt_source_addr) source_addr = alt_source_addr; Byte data_bytes[] = { cmd_code, vcp_code, // VCP opcode (new_value >> 8) & 0xff, new_value & 0xff }; DDC_Packet * pkt = create_ddc_base_request_packet(source_addr, data_bytes, 4, tag); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "DDC_Packet",dbgrpt_packet,pkt); return pkt; } /** Creates a request packet for Save Settings command. * * \param tag debug string * \return pointer to created DDC packet */ DDC_Packet * create_ddc_save_settings_request_packet(const char * tag) { Byte data_bytes[] = { DDC_PACKET_TYPE_SAVE_CURRENT_SETTINGS // 0x0C }; DDC_Packet * pkt = create_ddc_base_request_packet(0x51, data_bytes, 1, tag); // DBGMSG("Done. rc=%d, packet_ptr=%p, *packet_ptr=%p", rc, packet_ptr, *packet_ptr); return pkt; } // // Response Packets // /** Performs tasks common to creating any DDC response packet. * Checks for malformed packet, but not packet contents. * * \param i2c_response_bytes pointer to raw packet bytes * \param response_bytes_buffer_size size of buffer pointed to by **i2c_response_bytes**, * (used for debug hex dump) * \param tag debug string (may be NULL) * \param packet_ptr_loc where to return pointer to newly allocated #DDC_Packet * * \retval 0 * \retval DDCRC_DDC_DATA * \retval DDCRC_RESPONSE_ENVELOPE (deprecated) * \retval DDCRC_DOUBLE_BYTE (deprecated) * \retval DDCRC_PACKET_SIZE (deprecated) * \retval DDCRC_CHECKSUM (deprecated) * * The pointer returned at packet_ptr_loc is non-null iff the status code is 0. */ Status_DDC create_ddc_base_response_packet( Byte * i2c_response_bytes, int response_bytes_buffer_size, const char * tag, DDC_Packet ** packet_ptr_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "response_bytes_buffer_size=%d, i2c_response_bytes=%p->|%s|", response_bytes_buffer_size, i2c_response_bytes, hexstring_t(i2c_response_bytes, response_bytes_buffer_size)); int result = DDCRC_OK; DDC_Packet * packet = NULL; if (i2c_response_bytes[0] != 0x6e ) { DDCMSG(debug, "Unexpected source address 0x%02x, should be 0x6e", i2c_response_bytes[0]); result = DDCRC_DDC_DATA; // was DDCRC_RESPONSE_ENVELOPE } else { int data_ct = i2c_response_bytes[1] & 0x7f; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "data_ct=%d", data_ct); if (data_ct > MAX_DDC_DATA_SIZE) { if ( is_double_byte(&i2c_response_bytes[1])) { result = DDCRC_DDC_DATA; // was DDCRC_DOUBLE_BYTE DDCMSG(debug, "Double byte in packet."); } else { result = DDCRC_DDC_DATA; // was DDCRC_PACKET_SIZE DDCMSG(debug,"Invalid data length in packet: %d exceeds MAX_DDC_DATA_SIZE", data_ct); } } else { packet = create_empty_ddc_packet(3 + data_ct + 1, tag); // DBGMSG("create_empty_ddc_packet() returned %p", packet); if (data_ct > 0) packet->type = i2c_response_bytes[2]; Byte * packet_bytes = packet->raw_bytes->bytes; buffer_set_byte( packet->raw_bytes, 0, 0x6f); // implicit, would be 0x50 on access bus buffer_set_byte( packet->raw_bytes, 1, 0x6e); // i2c_response_bytes[0] // DBGMSG("packet->raw_bytes+2=%p, i2c_response_bytes+1=%p, 1+data_ct+1=%d", // packet->raw_bytes+2, i2c_response_bytes+1, 1+data_ct+1); buffer_set_bytes( packet->raw_bytes, 2, i2c_response_bytes+1, 1 + data_ct + 1); buffer_set_length(packet->raw_bytes, 3 + data_ct + 1); Byte calculated_checksum = ddc_checksum(packet_bytes, 3 + data_ct, true); // replacing right byte? Byte actual_checksum = packet_bytes[3+data_ct]; if (calculated_checksum != actual_checksum) { DDCMSG(debug, "Actual checksum 0x%02x, expected 0x%02x", actual_checksum, calculated_checksum); result = DDCRC_DDC_DATA; // was DDCRC_CHECKSUM free_ddc_packet(packet); } } } if (result != DDCRC_OK) { DDCMSG(debug, "i2c_response_bytes: %s", hexstring_t(i2c_response_bytes, response_bytes_buffer_size)); } if (result == DDCRC_OK) *packet_ptr_loc = packet; else *packet_ptr_loc = NULL; ASSERT_IFF(result==DDCRC_OK, *packet_ptr_loc); DBGTRC_RET_DDCRC2(debug, TRACE_GROUP, result, *packet_ptr_loc, "*packet_ptr_loc=%p", *packet_ptr_loc); if (*packet_ptr_loc && IS_DBGTRC(debug,TRACE_GROUP)) dbgrpt_packet(*packet_ptr_loc, 2); return result; } /** Creates a DDC response packet, checking for expected type and DDC Null Response * * \param i2c_response_bytes pointer to raw packet bytes * \param response_bytes_buffer_size size of buffer pointed to by **i2c_response_bytes** * \param expected_type expected packet type * \param tag debug string (may be NULL) * \param packet_ptr_addr where to return pointer to newly allocated #DDC_Packet * * \return 0 for success\n * as from create_ddc_base_response_packet, indicating malformed response * \retval DDCRC_NULL_RESPONSE * \retval DDCRC_RESPONSE_TYPE (deprecated) * \retval DDCRC_DDC_DATA * * The pointer returned at packet_ptr_addr is non-null iff the status code is 0. */ Status_DDC create_ddc_response_packet( Byte * i2c_response_bytes, int response_bytes_buffer_size, DDC_Packet_Type expected_type, const char * tag, DDC_Packet ** packet_ptr_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "response_bytes_buffer_size=%d, i2c_response_bytes=%p->|%s|", response_bytes_buffer_size, i2c_response_bytes, hexstring_t(i2c_response_bytes, response_bytes_buffer_size)); if (response_bytes_buffer_size > 2 && i2c_response_bytes[0] == 0x6e && i2c_response_bytes[1] == 0x6e) { DDCMSG(debug, "Quirk: response packet starts with double 0x6e"); i2c_response_bytes++; response_bytes_buffer_size--; } Status_DDC result = create_ddc_base_response_packet( i2c_response_bytes, response_bytes_buffer_size, tag, packet_ptr_loc); DBGMSF(debug, "create_ddc_base_response_packet() returned %d, *packet_ptr_loc=%p", result, *packet_ptr_loc); if (result == 0) { if (isNullPacket(*packet_ptr_loc)) { result = DDCRC_NULL_RESPONSE; } else if ( get_data_start(*packet_ptr_loc)[0] != expected_type) { result = DDCRC_DDC_DATA; // was: DDCRC_RESPONSE_TYPE } } if (result != DDCRC_OK && *packet_ptr_loc) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "failure, freeing response packet at %p", *packet_ptr_loc); // does this cause the free(readbuf) failure in try_read? free_ddc_packet(*packet_ptr_loc); *packet_ptr_loc = NULL; } if (result < 0) { log_status_code(result, __func__); } ASSERT_IFF( result==DDCRC_OK, *packet_ptr_loc); DBGTRC_RET_DDCRC2(debug, TRACE_GROUP, result, *packet_ptr_loc, "*packet_ptr_loc=%p", *packet_ptr_loc); if (*packet_ptr_loc && IS_DBGTRC(debug,TRACE_GROUP)) dbgrpt_packet(*packet_ptr_loc, 2); return result; } // // Packet data parsers // // Capabilities and table response data /** Interprets the bytes of a multi part read response. * * \param response_type * \param data_bytes * \param bytect * \param aux_data pointer to #Interpreted_Multi_Part_Read_Fragment to fill in * \retval 0 success * \retval DDCRC_INVALID_DATA (deprecated) * \retval DDCRC_DDC_DATA */ Status_DDC interpret_multi_part_read_response( DDC_Packet_Type response_type, Byte* data_bytes, int bytect, Interpreted_Multi_Part_Read_Fragment* aux_data) // Interpreted_Capabilities_Fragment * aux_data, { bool debug = false; int result = DDCRC_OK; // not needed, already checked if (bytect < 3 || bytect > 35) { // if (debug) DDCMSG(debug, "Invalid response data length: %d", bytect); result = COUNT_STATUS_CODE(DDCRC_DDC_DATA); // was DDCRC_INVALID_DATA } else { assert( data_bytes[0] == response_type); // table read reply opcode // CHANGED Byte offset_hi_byte = data_bytes[1]; Byte offset_lo_byte = data_bytes[2]; int read_data_length = bytect-3; // max 32 // CHANGED Byte * read_data_start = data_bytes+3; // CHANGED // DBGMSG("offset_hi_byte = 0x%02x, offset_lo_byte = 0x%02x", offset_hi_byte, offset_lo_byte ); aux_data->fragment_type = response_type; // set in caller? would make response_type parm unnecessary aux_data->fragment_offset = offset_hi_byte << 8 | offset_lo_byte; aux_data->fragment_length = read_data_length; // changed assert(read_data_length <= MAX_DDC_MULTI_PART_FRAGMENT_SIZE); // ??? memcpy(aux_data->bytes, read_data_start, read_data_length); // CHANGED // aux_data->text[text_length] = '\0'; // CHANGED } if (debug) DBGMSG("returning %s", ddcrc_desc_t(result)); return result; } void dbgrpt_interpreted_multi_read_fragment( Interpreted_Multi_Part_Read_Fragment * interpreted, int depth) { int d1 = depth+1; rpt_vstring(depth, "Multi-read response contents:"); rpt_vstring(d1, "fragment type: 0x%02x", interpreted->fragment_type); rpt_vstring(d1, "offset: %d", interpreted->fragment_offset); rpt_vstring(d1, "fragment length: %d", interpreted->fragment_length); rpt_vstring(d1, "data addr: %p", interpreted->bytes); if (interpreted->fragment_type == DDC_PACKET_TYPE_CAPABILITIES_RESPONSE) rpt_vstring(d1, "text: |%.*s|", interpreted->fragment_length, interpreted->bytes); else { char * hs = hexstring(interpreted->bytes, interpreted->fragment_length); rpt_vstring(d1, "data: 0x%s", hs); free(hs); } } // VCP feature response data // overlay the standard 8 byte VCP feature response typedef // no benefit to union here // union /* Vcp_Response */ { // Byte bytes[8]; struct { Byte feature_reply_op_code; // always 0x02 Byte result_code; // 0x00=no error, 0x01=Unsupported op code Byte vcp_opcode; // VCP opcode from feature request message Byte vcp_typecode; // 0x00=set parameter, 0x01=momentary Byte mh; Byte ml; Byte sh; Byte sl; // } fields; } /*__attribute__((packed)) */ Vcp_Response; /** Interprets the standard 8 byte VCP feature response. * * The response is checked for validity, and a * Interpreted_Nontable_Vcp_Response struct is filled in. * * \param vcp_data_bytes pointer to data bytes * \param bytect number of bytes in response, must be 8 * \param requested_vcp_code must be in the vcp_code field of he response bytes * \param parsed_response pointer to #Parsed_Nontable_Vcp_Response struct to be filled in * * \retval 0 success * \retval DDCRC_DDC_DATA * * \remark * It is not an error if the supported_opcode byte is set false in an * otherwise well constructed response. */ Status_DDC interpret_vcp_feature_response_std( Byte* vcp_data_bytes, int bytect, Byte requested_vcp_code, Parsed_Nontable_Vcp_Response* parsed_response) // to be filled in { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "requested_vcp_code: 0x%02x, vcp_data_bytes: %s", requested_vcp_code, hexstring3_t(vcp_data_bytes, bytect, " ", 4, false)); int result = DDCRC_OK; // set initial values for failure case: memset(parsed_response, 0, sizeof(Parsed_Nontable_Vcp_Response)); // parsed_response->vcp_code = 0x00; // parsed_response->valid_response = false; // parsed_response->supported_opcode = false; // parsed_response->max_value = 0; // parsed_response->cur_value = 0; if (bytect != 8) { DDCMSG(debug, "Invalid response data length: %d, should be 8, response data bytes: %s", bytect, hexstring3_t(vcp_data_bytes, bytect, " ", 4, false)); result = COUNT_STATUS_CODE(DDCRC_DDC_DATA); // was DDCRC_INVALID_DATA } else { // overlay Vcp_Response on the data bytes of the response Vcp_Response * vcpresp = (Vcp_Response *) vcp_data_bytes; assert( sizeof(*vcpresp) == 8); assert(vcpresp->result_code == vcp_data_bytes[1]); // validate the overlay parsed_response->vcp_code = vcpresp->vcp_opcode; bool valid_response = true; if (vcpresp->vcp_opcode != requested_vcp_code){ DDCMSG(debug, "Unexpected VCP opcode 0x%02x, should be 0x%02x, response data bytes: %s", vcpresp->vcp_opcode, requested_vcp_code, hexstring3_t(vcp_data_bytes, bytect, " ", 4, false)); result = COUNT_STATUS_CODE(DDCRC_DDC_DATA); // was DDCRC_INVALID_DATA } else if (vcpresp->result_code != 0) { if (vcpresp->result_code == 0x01) { // Do not report as DDC error if VCP code is 0x00, since that value is used // for probing. // bool msg_emitted = DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Unsupported VCP Code: 0x%02x", vcpresp->vcp_opcode); // if (requested_vcp_code != 0x00 && !msg_emitted) // DDCMSG(debug, "Unsupported VCP Code: 0x%02x", vcpresp->vcp_opcode); parsed_response->valid_response = true; } else { DDCMSG(debug, "Unexpected result code: 0x%02x, response_data_bytes: %s", vcpresp->result_code, hexstring3_t(vcp_data_bytes, bytect, " ", 4, false)); result = COUNT_STATUS_CODE(DDCRC_DDC_DATA); // was DDCRC_INVALID_DATA } } else { if (debug) { int max_val = (vcpresp->mh << 8) | vcpresp->ml; int cur_val = (vcpresp->sh << 8) | vcpresp->sl; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "vcp_opcode = 0x%02x, vcp_type_code=0x%02x, max_val=%d (0x%04x), cur_val=%d (0x%04x)", vcpresp->vcp_opcode, vcpresp->vcp_typecode, max_val, max_val, cur_val, cur_val); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "valid_response=%s", sbool(valid_response)); } parsed_response->valid_response = true; parsed_response->supported_opcode = true; // aux_data->max_value = max_val; // valid only for continuous features // aux_data->cur_value = cur_val; // valid only for continuous features // for new way parsed_response->mh = vcpresp->mh; parsed_response->ml = vcpresp->ml; parsed_response->sh = vcpresp->sh; parsed_response->sl = vcpresp->sl; } } // result = DDCRC_DDC_DATA; // force error for testing DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } void dbgrpt_interpreted_nontable_vcp_response( Parsed_Nontable_Vcp_Response * interpreted, int depth) { rpt_vstring(depth,"VCP code: 0x%02x", interpreted->vcp_code); rpt_vstring(depth,"valid_response: %d", interpreted->valid_response); rpt_vstring(depth,"supported_opcode: %d", interpreted->supported_opcode); rpt_vstring(depth,"max_value: %d", RESPONSE_MAX_VALUE(interpreted)); rpt_vstring(depth,"cur_value: %d", RESPONSE_CUR_VALUE(interpreted)); rpt_vstring(depth,"mh: 0x%02x", interpreted->mh); rpt_vstring(depth,"ml: 0x%02x", interpreted->ml); rpt_vstring(depth,"sh: 0x%02x", interpreted->sh); rpt_vstring(depth,"sl: 0x%02x", interpreted->sl); } void dbgrpt_parsed_vcp_response(Parsed_Vcp_Response * response, int depth) { rpt_vstring(depth, "Parsed_Vcp_Reponse at %p:", response); rpt_vstring(depth, "response_type: %d", response->response_type); if (response->response_type == DDCA_NON_TABLE_VCP_VALUE) { rpt_vstring(depth, "non_table_response at %p:", response->non_table_response); dbgrpt_interpreted_nontable_vcp_response(response->non_table_response, depth+1); } else { rpt_vstring(depth, "table_response at %p", response->table_response); } } // // Response packets // /** Creates a #DDC_Packet from a raw DDC response. * * \param i2c_response_bytes pointer to raw packet bytes * \param response_bytes_buffer_size size of buffer pointed to by **i2c_response_bytes** * \param expected_type expected packet type * \param expected_subtype depends on expected_type * \param tag debug string (may be NULL) * \param packet_ptr_loc where to return pointer to newly allocated #DDC_Packet * * \retval 0 * \return as from #create_ddc_response_packet() * \retval DDCRC_INVALID_DATA may be set by function that fills in aux_data struct * * The pointer returned at packet_ptr_addr is non-null iff the status code is 0. * * The contents of **expected_subtype** depends on the value of **expected_type**. * For DDC_PACKET_TYPE_QUERY_VCP_RESPONSE it is the VCP feature code. */ Status_DDC create_ddc_typed_response_packet( Byte* i2c_response_bytes, int response_bytes_buffer_size, DDC_Packet_Type expected_type, Byte expected_subtype, const char* tag, DDC_Packet** packet_ptr_loc) { bool debug = false; assert(i2c_response_bytes); DBGTRC_STARTING(debug, TRACE_GROUP, "response_bytes_buffer_size=%d, i2c_response_bytes=%p -> |%s|", response_bytes_buffer_size, i2c_response_bytes, hexstring_t(i2c_response_bytes, response_bytes_buffer_size) ); *packet_ptr_loc = NULL; // DBGMSG("before create_ddc_response_packet(), *packet_ptr_addr=%p", *packet_ptr_loc); // n. may return DDC_NULL_RESPONSE?? (old note) Status_DDC rc = create_ddc_response_packet( i2c_response_bytes, response_bytes_buffer_size, expected_type, tag, packet_ptr_loc); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Create_ddc_response_packet() returned %s, *packet_ptr_loc=%p", psc_desc(rc), *packet_ptr_loc); if (rc == 0) { DDC_Packet * packet = *packet_ptr_loc; assert(packet); switch (expected_type) { case DDC_PACKET_TYPE_CAPABILITIES_RESPONSE: case DDC_PACKET_TYPE_TABLE_READ_RESPONSE: { Interpreted_Multi_Part_Read_Fragment * aux_data = calloc(1, sizeof(Interpreted_Multi_Part_Read_Fragment)); assert(packet); packet->parsed.multi_part_read_fragment = aux_data; rc = interpret_multi_part_read_response( expected_type, get_data_start(packet), get_data_len(packet), aux_data); } break; case DDC_PACKET_TYPE_QUERY_VCP_RESPONSE: { Parsed_Nontable_Vcp_Response * aux_data = calloc(1, sizeof(Parsed_Nontable_Vcp_Response)); assert(packet); packet->parsed.nontable_response = aux_data; rc = interpret_vcp_feature_response_std( get_data_start(packet), get_data_len(packet), expected_subtype, aux_data); } break; default: rc = DDCRC_INTERNAL_ERROR; DBGMSG("Unhandled case. expected_type=%d", expected_type); SYSLOG2(DDCA_SYSLOG_ERROR, "Unhandled case in %s. expected_type=%d", __func__, expected_type); break; } } if (rc != DDCRC_OK && *packet_ptr_loc) { free_ddc_packet(*packet_ptr_loc); *packet_ptr_loc = NULL; } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "*packet_ptr_loc=%p", *packet_ptr_loc); if ( (debug || IS_TRACING()) && rc >= 0) dbgrpt_packet(*packet_ptr_loc, 2); ASSERT_IFF(rc == 0, *packet_ptr_loc); return rc; } #ifdef UNUSED Status_DDC create_ddc_multi_part_read_response_packet( Byte response_type, Byte * i2c_response_bytes, int response_bytes_buffer_size, const char * tag, DDC_Packet ** packet_ptr) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "response_type=0x%02x, tag=%s, packet_ptr=%p"); DDC_Packet * packet = NULL; Status_DDC rc = create_ddc_response_packet(i2c_response_bytes, response_bytes_buffer_size, DDC_PACKET_TYPE_TABLE_READ_RESPONSE, tag, &packet); if (rc != 0) { // DBGMSG("create_ddc_response_packet() returned %s, packet=%p", ddcrc_description(rc), packet); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "create_ddc_response_packet() returned %s, packet=%p", psc_name_code(rc), packet); } if (rc == 0) { // dump_packet(packet); int min_data_len = 3; int max_data_len = 35; int data_len = get_data_len(packet); if (data_len < min_data_len || data_len > max_data_len) { DDCMSG(debug, "Invalid data fragment_length_wo_null: %d", data_len); if (IS_REPORTING_DDC()) dbgrpt_packet(packet, 2); rc = COUNT_STATUS_CODE(DDCRC_DDC_DATA); // was DDCRC_INVALID_DATA } else { Interpreted_Multi_Part_Read_Fragment * aux_data = calloc(1, sizeof(Interpreted_Multi_Part_Read_Fragment)); packet->parsed.multi_part_read_fragment = aux_data; rc = interpret_multi_part_read_response( response_type, get_data_start(packet), get_data_len(packet), aux_data); } } if (rc != 0 && packet) { free_ddc_packet(packet); } if (rc == 0) *packet_ptr = packet; DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "*packet_ptr=%p", *packet_ptr); return rc; } #endif // VCP Feature response // 4/2017: used only in ddc_vcp_tests.c: Status_DDC create_ddc_getvcp_response_packet( Byte * i2c_response_bytes, int response_bytes_buffer_size, Byte expected_vcp_opcode, const char * tag, DDC_Packet ** packet_ptr) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "expected_vcp_opcode=0x%02x, packet_ptr=%p", expected_vcp_opcode, packet_ptr); DDC_Packet * packet = NULL; Status_DDC rc = create_ddc_response_packet( i2c_response_bytes, response_bytes_buffer_size, DDC_PACKET_TYPE_QUERY_VCP_RESPONSE, tag, &packet); if (rc != 0) { // DBGMSG("create_ddc_response_packet() returned %s, packet=%p", ddcrc_description(rc), packet); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "create_ddc_response_packet() returned %s, packet=%p", ddcrc_desc_t(rc), packet); } if (rc == 0) { // dump_packet(packet); int data_len = get_data_len(packet); if (data_len != 8) { // DBGMSG("Invalid data length: %d, should be 8", data_len); // dump_packet(packet); DDCMSG(debug, "Invalid data length: %d, should be 8", data_len); if ( IS_REPORTING_DDC() ) dbgrpt_packet(packet, 2); rc = COUNT_STATUS_CODE(DDCRC_DDC_DATA); // was DDCRC_INVALID_DATA } else { Parsed_Nontable_Vcp_Response * aux_data = calloc(1, sizeof(Parsed_Nontable_Vcp_Response)); packet->parsed.nontable_response = aux_data; rc = interpret_vcp_feature_response_std( get_data_start(packet), get_data_len(packet), expected_vcp_opcode, aux_data); } } if (rc != 0 && packet) { free_ddc_packet(packet); } if (rc == 0) *packet_ptr = packet; DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "*packet_ptr=%p", *packet_ptr); return rc; } // // Operations on response packets // // VCP Feature Code /** Extracts the interpretation of a non-table VCP response from a #DDC_Packet. * * \param packet pointer to digested packet (not raw bytes) * \param make_copy if true, make a copy of the aux_data field,\n * if false, just return a pointer to it * \param interpreted_loc where to return pointer to #Parsed_Nontable_Vcp_Response * \retval 0 success * \retval DDCRC_RESPONSE_TYPE not a VCP response packet (deprecated) * \retval DDCRC_DDC_DATA not a VCP response packet * * The value pointed to by **interpreted_loc** is non-null iff the returned status code is 0. */ Status_DDC get_interpreted_vcp_code( DDC_Packet * packet, bool make_copy, Parsed_Nontable_Vcp_Response ** interpreted_loc) { bool debug = false; DBGMSF(debug, "Starting"); Status_DDC rc = DDCRC_OK; if (packet->type != DDC_PACKET_TYPE_QUERY_VCP_RESPONSE) { rc = COUNT_STATUS_CODE(DDCRC_DDC_DATA); // was DDCRC_RESPONSE_TYPE *interpreted_loc = NULL; } else { if (make_copy) { Parsed_Nontable_Vcp_Response * copy = malloc(sizeof(Parsed_Nontable_Vcp_Response)); memcpy(copy, packet->parsed.nontable_response, sizeof(Parsed_Nontable_Vcp_Response)); *interpreted_loc = copy; } else { *interpreted_loc = packet->parsed.nontable_response; } } DBGMSF(debug, "Returning %d: %s\n", rc, psc_desc(rc) ); ASSERT_IFF(rc == 0, *interpreted_loc); return rc; } /** Emits a debug report of a #DDC_Packet * \param packet pointer to packet * \param depth logical indentation depth */ void dbgrpt_packet(DDC_Packet * packet, int depth) { assert(packet); // make clang analyzer happy int d0 = depth; // printf("DDC_Packet dump. Addr: %p, Type: 0x%02x, Tag: |%s|, buf: %p, aux_data: %p\n", // packet, packet->type, packet->tag, packet->raw_bytes, packet->aux_data); rpt_vstring(depth, "DDC_Packet dump. Addr: %p, Type: 0x%02x, Tag: |%s|, buf: %p, parsed: %p", packet, packet->type, packet->tag, packet->raw_bytes, packet->parsed.raw_parsed); dbgrpt_buffer(packet->raw_bytes, d0); // TODO show interpreted aux_data if (packet->parsed.raw_parsed) { switch(packet->type) { case (DDC_PACKET_TYPE_CAPABILITIES_RESPONSE): case (DDC_PACKET_TYPE_TABLE_READ_RESPONSE): dbgrpt_interpreted_multi_read_fragment(packet->parsed.multi_part_read_fragment, d0); break; case (DDC_PACKET_TYPE_QUERY_VCP_RESPONSE): dbgrpt_interpreted_nontable_vcp_response(packet->parsed.nontable_response, d0); break; default: // PROGRAM_LOGIC_ERROR("Unexpected packet type: -x%02x", packet->type); rpt_vstring(d0, "PROGRAM_LOGIC_ERROR: Unexpected packet type: -x%02x", packet->type); } } } #ifdef UNUSED // 12/23/2015: not currently used Status_DDC get_vcp_cur_value(DDC_Packet * packet, int * value_ptr) { Parsed_Nontable_Vcp_Response * aux_ptr; Status_DDC rc = get_interpreted_vcp_code(packet, false, &aux_ptr); if (rc == 0) { // *value_ptr = aux_ptr->sh<<8 | aux_ptr->sl; // aux_ptr->cur_value; *value_ptr = RESPONSE_CUR_VALUE(aux_ptr); } return rc; } #endif void init_ddc_packets() { RTTI_ADD_FUNC(create_empty_ddc_packet); RTTI_ADD_FUNC(update_ddc_multi_part_read_request_packet_offset); RTTI_ADD_FUNC(create_ddc_base_request_packet); RTTI_ADD_FUNC(create_ddc_base_response_packet); RTTI_ADD_FUNC(create_ddc_getvcp_request_packet); RTTI_ADD_FUNC(create_ddc_getvcp_response_packet); // RTTI_ADD_FUNC(create_ddc_multi_part_read_response_packet); // unused RTTI_ADD_FUNC(create_ddc_response_packet); RTTI_ADD_FUNC(create_ddc_setvcp_request_packet); RTTI_ADD_FUNC(create_ddc_typed_response_packet); RTTI_ADD_FUNC(interpret_vcp_feature_response_std); } ddcutil-2.2.0/src/base/display_lock.c0000644000175000001440000004747614754153540013174 /** \f display_lock.c * Provides locking for displays to ensure that a given display is not * opened simultaneously from multiple threads. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /* #ifdef TOO_MANY_EDGE_CASES * It is conceivable that there are multiple paths to the same monitor, e.g. * multiple cables from different video card outputs, or USB as well as I2c * connections. Therefore, this module checks the manufacturer id, model string, * and ascii serial number fields in the EDID when comparing monitors. * * (Note that comparing the full 128 byte EDIDs will not work, as a monitor can * return different EDIDs on different inputs, e.g. VGA vs DVI. #endif * * Only the io path to the display is checked. */ /* 5/2023: * * This method of locking is vestigial from the time that there could be more * than one Display_Ref for a display, which could be held in different threads. * * The code could be simplified, or eliminated almost entirely, e.g. by recording * in the Display_Ref which thread has opened the display. * * Given the imminent release of 2.0.0-rc1, such changes are left to a future release. */ #include #include #include #include #include "util/debug_util.h" #include "util/error_info.h" #include "util/glib_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "ddcutil_types.h" #include "ddcutil_status_codes.h" #include "base/displays.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/status_code_mgt.h" #ifdef ALT_LCOK_REC #include "usb/usb_displays.h" // forward ref, need to split out usb_displays_base.h #endif #include "base/display_lock.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDCIO; char * interpret_display_lock_flags_t(Display_Lock_Flags lock_flags) { static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&buf_key, 200); if (lock_flags & DDISP_WAIT) strcpy(buf, "DDISP_WAIT"); else strcpy(buf, "DDISP_NONE"); return buf; } static bool lock_rec_matches_io_path(Display_Lock_Record * dlr, DDCA_IO_Path path) { bool result = false; // i2c_busno and hiddev are same size, to following works for DDCA_IO_USB if (dlr->io_path.io_mode == path.io_mode && dlr->io_path.path.i2c_busno == path.path.i2c_busno) result = true; return result; } #ifdef UNUSED static bool lock_rec_matches_dref(Display_Lock_Record * dlr, Display_Ref * dref) { bool result = false; if (dpath_eq(dlr->io_path, dref->io_path)) result = true; return result; } #endif static GPtrArray * lock_records = NULL; // array of Diaplay_Lock_Record * static GMutex descriptors_mutex; // single threads access to lock records static GMutex master_display_lock_mutex; // must be called when lock not held by current thread, o.w. deadlock static char * lockrec_repr_t(Display_Lock_Record * ref) { static GPrivate repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&repr_key, 100); g_mutex_lock(&descriptors_mutex); assert(memcmp(ref->marker, DISPLAY_LOCK_MARKER, 4) == 0); g_snprintf(buf, 100, "Display_Lock_Record[%s tid=%jd @%p]", dpath_repr_t(&ref->io_path), ref->linux_thread_id, ref); g_mutex_unlock(&descriptors_mutex); return buf; } Display_Lock_Record * create_display_lock_record(DDCA_IO_Path io_path) { Display_Lock_Record * new_desc = calloc(1, sizeof(Display_Lock_Record)); memcpy(new_desc->marker, DISPLAY_LOCK_MARKER, 4); new_desc->io_path = io_path; g_mutex_init(&new_desc->display_mutex); return new_desc; } static Display_Lock_Record * get_display_lock_record_by_dpath(DDCA_IO_Path io_path) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "io_path=%s", dpath_repr_t(&io_path)); Display_Lock_Record * result = NULL; g_mutex_lock(&descriptors_mutex); for (int ndx=0; ndx < lock_records->len; ndx++) { Display_Lock_Record * cur = g_ptr_array_index(lock_records, ndx); if (lock_rec_matches_io_path(cur, io_path) ) { result = cur; break; } } if (!result) { Display_Lock_Record * new_desc = create_display_lock_record(io_path); g_ptr_array_add(lock_records, new_desc); result = new_desc; } g_mutex_unlock(&descriptors_mutex); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p -> %s", result, lockrec_repr_t(result)); return result; } #ifdef UNUSED static Display_Lock_Record * get_display_lock_record_by_dref(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s", dref_repr_t(dref)); Display_Lock_Record * result = get_display_lock_record_by_dpath(dref->io_path); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p -> %s", result, lockrec_repr_t(result)); return result; } #endif #define EMIT_BACKTRACE(_ddcutil_severity, _format, ...) \ do { \ if (!msg_to_syslog_only) { \ DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, _format, ##__VA_ARGS__); \ if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { \ show_backtrace(0); \ debug_current_traced_function_stack(false); \ } \ } \ if (test_emit_syslog(_ddcutil_severity)) { \ int syslog_priority = syslog_importance_from_ddcutil_syslog_level(_ddcutil_severity); \ if (syslog_priority >= 0) { \ char * body = g_strdup_printf(_format, ##__VA_ARGS__); \ syslog(syslog_priority, PRItid" %s%s", (intmax_t) tid(), body, (tag_output) ? " (R)" : "" ); \ free(body); \ backtrace_to_syslog(syslog_priority, 2); \ current_traced_function_stack_to_syslog(syslog_priority, false); \ } \ } \ } while(0) /** Locks a distinct display. * * \param dlr Display_Lock_Record distinct display identifier * \param flags if **DDISP_WAIT** set, wait for locking * \retval NULL success * \retval Error_Info(DDCRC_LOCKED) locking failed, display already locked by another * thread and DDISP_WAIT not set * \retval Error_Info(DDCRC_ALREADY_OPEN) display already locked in current thread */ Error_Info * lock_display( Display_Lock_Record * dlr, Display_Lock_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dlr->io_path=%s, dlr->linux_thread_id=%jd flags=%s", dpath_short_name_t(&dlr->io_path), dlr->linux_thread_id, interpret_display_lock_flags_t(flags)); Error_Info * err = NULL; // TODO: If this function is exposed in API, change assert to returning illegal argument status code TRACED_ASSERT(memcmp(dlr->marker, DISPLAY_LOCK_MARKER, 4) == 0); bool self_thread = false; bool locked = false; g_mutex_lock(&master_display_lock_mutex); if (dlr->display_mutex_thread == g_thread_self() ) self_thread = true; g_mutex_unlock(&master_display_lock_mutex); if (self_thread) { EMIT_BACKTRACE(DDCA_SYSLOG_ERROR, "Attempting to lock display already locked by current thread, tid=%jd", TID()); err = errinfo_new(DDCRC_ALREADY_OPEN, __func__, // is there a better status code? "Attempting to lock display already locked by current thread"); // poor goto bye; } if (flags & DDISP_WAIT) { g_mutex_lock(&dlr->display_mutex); locked = true; } else { int lock_max_wait_millisec = DEFAULT_OPEN_MAX_WAIT_MILLISEC; int lock_wait_interval_millisec = DEFAULT_OPEN_WAIT_INTERVAL_MILLISEC; int total_wait_millisec = 0; int tryctr = 0; while (!locked && total_wait_millisec < lock_max_wait_millisec) { tryctr++; locked = g_mutex_trylock(&dlr->display_mutex); if (!locked) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "g_mutex_trylock() failed, dref=%s", dpath_short_name_t(&dlr->io_path)); sleep_millis(lock_wait_interval_millisec); } } if (locked) { // note that this thread owns the lock if (tryctr > 1) { EMIT_BACKTRACE(DDCA_SYSLOG_NOTICE, PRItid"Locked %s after %d tries", TID(), dpath_short_name_t(&dlr->io_path), tryctr); } } else { EMIT_BACKTRACE(DDCA_SYSLOG_ERROR, PRItid"Failed to Lock %s after %d tries. Locked by thread"PRItid, TID(), dpath_short_name_t(&dlr->io_path), tryctr, dlr->linux_thread_id); err = errinfo_new(DDCRC_LOCKED, __func__, "Locking failed for %s after %d tries. Locked by thread"PRItid, dpath_short_name_t(&dlr->io_path), tryctr, dlr->linux_thread_id); } } bye: if (locked) { // note that this thread owns the lock dlr->display_mutex_thread = g_thread_self(); dlr->linux_thread_id = get_thread_id(); } // need a new DDC status code // DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, "dlr->io_path=%s", dpath_short_name_t(&dlr->io_path)); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, ""); return err; } #ifdef UNUSED // For future use? n. coverity complains int lockrec_poll_millisec = DEFAULT_FLOCK_POLL_MILLISEC; // *** TEMP *** int lockrec_max_wait_millisec = DEFAULT_FLOCK_MAX_WAIT_MILLISEC; Error_Info * lock_display2( Display_Lock_Record * dlr, Display_Lock_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "device %s, flags=%s", dpath_repr_t(&dlr->io_path), interpret_display_lock_flags_t(flags)); Error_Info * err = NULL; TRACED_ASSERT(memcmp(dlr->marker, DISPLAY_LOCK_MARKER, 4) == 0); uint64_t lockrec_poll_microsec = 1000 * (uint64_t) lockrec_poll_millisec; //DBGTRC_STARTING(debug, TRACE_GROUP, "dlr=%p -> %s, flags=%s", // dlr, lockrec_repr_t(dlr), interpret_display_lock_flags_t(flags)); if (dlr->display_mutex_thread == g_thread_self() ) { char buf[80]; g_snprintf(buf, 80, "Attempting to lock device %s already locked by current thread %jd", dpath_repr_t(&dlr->io_path), get_thread_id()); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "%s", buf); err = ERRINFO_NEW(DDCRC_ALREADY_OPEN, "%s", buf); goto bye; } int total_wait_millisec = 0; uint64_t max_wait_millisec = (flags & DDISP_WAIT) ? lockrec_max_wait_millisec : 0; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "flock_poll_millisec=%d, flock_max_wait_millisec=%d ", lockrec_poll_millisec, lockrec_max_wait_millisec); int lock_call_ctr = 0; bool locked = false; while(!locked && total_wait_millisec <= max_wait_millisec) { lock_call_ctr++; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling g_mutex_trylcock(), mutex=%p, device=%s, lock_call_ctr=%d, total_wait_millisec %d", dlr->display_mutex, dpath_repr_t(&dlr->io_path), lock_call_ctr, total_wait_millisec); bool locked = g_mutex_trylock(&dlr->display_mutex); if (locked) { continue; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Sleeping for %d millisec", lockrec_poll_millisec); g_usleep(lockrec_poll_microsec); total_wait_millisec += lockrec_poll_millisec; } if (locked) { DBGTRC(debug, DDCA_TRC_NONE, "Lock succeeded after %d tries and %d millisec", lock_call_ctr, total_wait_millisec); dlr->display_mutex_thread = g_thread_self(); dlr->linux_thread_id = get_thread_id(); } else { // living dangerously, but it's an error msg MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Max wait time for %s exceeded after %d g_mutex_lock() calls", dpath_repr_t(&dlr->io_path), lock_call_ctr); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Lock currently held by thread %jd", dlr->linux_thread_id); err = ERRINFO_NEW(DDCRC_LOCKED, "Locking failed for %s. Apparently held by thread %jd", dpath_repr_t(&dlr->io_path), dlr->linux_thread_id); } bye: DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, ""); return err; } #endif #ifdef UNUSED /** Locks a display. * * \param dref display reference * \param flags if **DDISP_WAIT** set, wait for locking * \retval NULL success * \retval Error_Info(DDCRC_LOCKED) locking failed, display already locked by another * thread and DDISP_WAIT not set * \retval Error_Info(DDCRC_ALREADY_OPEN) display already locked in current thread */ Error_Info * lock_display_by_dref( Display_Ref * dref, Display_Lock_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s, flags=0x%02x", dref_repr_t(dref), flags); Display_Lock_Record * lockid = get_display_lock_record_by_dref(dref); Error_Info * result = lock_display(lockid, flags); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, "dref=%s", dref_repr_t(dref)); return result; } #endif /** Locks a display, specified by its io path * * \param dpath display path * \param flags if **DDISP_WAIT** set, wait for locking * \retval NULL success * \retval Error_Info(DDCRC_LOCKED) locking failed, display already locked by another * thread and DDISP_WAIT not set * \retval Error_Info(DDCRC_ALREADY_OPEN) display already locked in current thread */ Error_Info * lock_display_by_dpath( DDCA_IO_Path dpath, Display_Lock_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dpath=%s, flags=0x%02x=%s", dpath_repr_t(&dpath), flags, interpret_display_lock_flags_t(flags)); Display_Lock_Record * lockid = get_display_lock_record_by_dpath(dpath); Error_Info * result = lock_display(lockid, flags); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, "dpath=%s", dpath_repr_t(&dpath)); return result; } #ifdef UNUSED Error_Info * unlock_display2(Display_Lock_Record * dlr) { bool debug = false; assert(dlr); DBGTRC_STARTING(debug, TRACE_GROUP, "dlr->io_path=%s, dlr->linux_thread_id=%jd ", dpath_short_name_t(&dlr->io_path), dlr->linux_thread_id); Error_Info * err = NULL; // TODO: If this function is exposed in API, change assert to returning illegal argument status code TRACED_ASSERT(memcmp(dlr->marker, DISPLAY_LOCK_MARKER, 4) == 0); char buf[80]; intmax_t lock_tid = dlr->linux_thread_id; if (lock_tid != get_thread_id()) { if (lock_tid == 0) { g_snprintf(buf, 80, "Attempting to unlock device %s not currently locked", dpath_repr_t(&dlr->io_path)); } else { g_snprintf(buf, 80, "Attempting to unlock device %s locked by different thread %jd", dpath_repr_t(&dlr->io_path), lock_tid); } SYSLOG2(DDCA_SYSLOG_ERROR, "%s", buf); err = ERRINFO_NEW(DDCRC_LOCKED, "%s", buf); } else { dlr->display_mutex_thread = NULL; dlr->linux_thread_id = 0; g_mutex_unlock(&dlr->display_mutex); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, "dlr->io_path=%s", dpath_short_name_t(&dlr->io_path)); return err; } #endif /** Unlocks a distinct display. * * \param id distinct display identifier * \retval Error_Info(DDCRC_LOCKED) attempting to unlock a display owned by a different thread * \retval NULL no error */ Error_Info * unlock_display(Display_Lock_Record * dlr) { bool debug = false; // DBGTRC_STARTING(debug, TRACE_GROUP, "dlr=%p -> %s", dlr, lockrec_repr_t(dlr)); DBGTRC_STARTING(debug, TRACE_GROUP, "dlr->io_path=%s", dpath_short_name_t(&dlr->io_path)); Error_Info * err = NULL; // TODO: If this function is exposed in API, change assert to returning illegal argument status code TRACED_ASSERT(memcmp(dlr->marker, DISPLAY_LOCK_MARKER, 4) == 0); g_mutex_lock(&master_display_lock_mutex); intmax_t current_thread_id = dlr->linux_thread_id; // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "old linux_thread_id = %jd", dlr->linux_thread_id); if (dlr->display_mutex_thread != g_thread_self()) { SYSLOG2(DDCA_SYSLOG_ERROR, "Attempting to unlock display lock owned by different thread"); err = errinfo_new(DDCRC_LOCKED, __func__, "Attempting to unlock display lock owned by different thread"); } else { dlr->display_mutex_thread = NULL; dlr->linux_thread_id = 0; current_thread_id = 0; g_mutex_unlock(&dlr->display_mutex); } g_mutex_unlock(&master_display_lock_mutex); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, "dlr->io_path=%s, final linux_thread_id=%d", dpath_repr_t(&dlr->io_path), current_thread_id); return err; } #ifdef UNUSED /** Unlocks a display. * * \param dref display reference * \retval NULL success * \retval Error_Info(DDCRC_LOCKED) locking failed, display already locked by another thread */ Error_Info * unlock_display_by_dref( Display_Ref * dref) { Display_Lock_Record * lockid = get_display_lock_record_by_dref(dref); return unlock_display(lockid); } #endif /** Unlocks a display, specified by its io path * * \param dpath io path * \retval NULL success * \retval Error_Info(DDCRC_LOCKED) locking failed, display already locked by another thread */ Error_Info * unlock_display_by_dpath( DDCA_IO_Path dpath) { Display_Lock_Record * lockid = get_display_lock_record_by_dpath(dpath); return unlock_display(lockid); } #ifdef BAD /** Unlocks all distinct displays. * * The function is used during reinitialization. * * BUG: DO NOT USE */ void unlock_all_distinct_displays() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); g_mutex_lock(&master_display_lock_mutex); // are both locks needed? g_mutex_lock(&descriptors_mutex); for (int ndx=0; ndx < lock_records->len; ndx++) { Display_Lock_Record * cur = g_ptr_array_index(lock_records, ndx); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%2d - %p %-28s", ndx, cur, dpath_repr_t(&cur->io_path) ); // WRONG: Attempt to unlock mutex that was not locked // Aborted (core dumped) // Calling g_mutex_unlock() on a mutex that is not locked by the current thread leads to undefined behaviour. g_mutex_unlock(&cur->display_mutex); } g_mutex_unlock(&descriptors_mutex); g_mutex_unlock(&master_display_lock_mutex); DBGTRC_DONE(debug, TRACE_GROUP, ""); } #endif /** Emits a report of all distinct display descriptors. * * \param depth logical indentation depth */ void dbgrpt_display_locks(int depth) { rpt_vstring(depth, "display_descriptors@%p", lock_records); g_mutex_lock(&descriptors_mutex); int d1 = depth+1; rpt_label(depth,"index lock-record-ptr dpath display_mutex_thread"); for (int ndx=0; ndx < lock_records->len; ndx++) { Display_Lock_Record * cur = g_ptr_array_index(lock_records, ndx); rpt_vstring(d1, "%2d - %p %-28s thread ptr=%p, thread id=%jd", ndx, cur, dpath_repr_t(&cur->io_path), (void*) &cur->display_mutex_thread, cur->linux_thread_id ); } g_mutex_unlock(&descriptors_mutex); } /** Initializes this module */ void init_i2c_display_lock(void) { lock_records= g_ptr_array_new_with_free_func(g_free); RTTI_ADD_FUNC(get_display_lock_record_by_dpath); RTTI_ADD_FUNC(lock_display); #ifdef UNUSED RTTI_ADD_FUNC(lock_display2); RTTI_ADD_FUNC(unlock_display2); #endif RTTI_ADD_FUNC(lock_display_by_dpath); RTTI_ADD_FUNC(unlock_display); RTTI_ADD_FUNC(unlock_display_by_dpath); #ifdef UNUSED RTTI_ADD_FUNC(get_display_lock_record_by_dref); RTTI_ADD_FUNC(lock_display_by_dref); RTTI_ADD_FUNC(unlock_display_by_dref); #endif } void terminate_i2c_display_lock() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDCIO, ""); g_ptr_array_free(lock_records, true); DBGTRC_DONE(debug, DDCA_TRC_DDCIO, ""); } ddcutil-2.2.0/src/base/displays.c0000644000175000001440000014270314754153540012334 /** @file displays.c Monitor identifier, reference, handle */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include /** \cond */ #include #include #include #include #include #include #include "util/data_structures.h" #include "util/debug_util.h" #include "util/glib_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_i2c_util.h" #include "util/timestamp.h" #ifdef ENABLE_UDEV #include "util/udev_util.h" #include "util/udev_usb_util.h" #endif /** \endcond */ #include "public/ddcutil_types.h" #include "public/ddcutil_status_codes.h" #include "core.h" #include "i2c_bus_base.h" #include "monitor_model_key.h" #include "per_display_data.h" #include "rtti.h" #include "vcp_version.h" #include "displays.h" GPtrArray * all_display_refs = NULL; // all detected displays, array of Display_Ref * GMutex all_display_refs_mutex; bool debug_locks = false; bool terminate_watch_thread = false; // *** DDCA_IO_Path *** /** Tests 2 #DDCA_IO_Path instances for equality * * \param p1 first instance * \param p2 second instance * \return true/false */ bool dpath_eq(DDCA_IO_Path p1, DDCA_IO_Path p2) { bool result = false; if (p1.io_mode == p2.io_mode) { switch(p1.io_mode) { case DDCA_IO_I2C: result = (p1.path.i2c_busno == p2.path.i2c_busno); break; case DDCA_IO_USB: result = p1.path.hiddev_devno == p2.path.hiddev_devno; } } return result; } /** Creates a unique integer number from a #DDCA_IO_Path, suitable * for use as a hash key. * * \param path io path * \return integer value */ int dpath_hash(DDCA_IO_Path path) { return path.io_mode * 100 + path.path.i2c_busno; } // *** Display_Identifier *** static char * Display_Id_Type_Names[] = { "DISP_ID_BUSNO", "DISP_ID_MONSER", "DISP_ID_EDID", "DISP_ID_DISPNO", "DISP_ID_USB", "DISP_ID_HIDDEV" }; /** Returns symbolic name of display identifier type * \param val display identifier type * \return symbolic name */ char * display_id_type_name(Display_Id_Type val) { return Display_Id_Type_Names[val]; } static Display_Identifier* common_create_display_identifier(Display_Id_Type id_type) { Display_Identifier* pIdent = calloc(1, sizeof(Display_Identifier)); memcpy(pIdent->marker, DISPLAY_IDENTIFIER_MARKER, 4); pIdent->id_type = id_type; pIdent->busno = -1; pIdent->usb_bus = -1; pIdent->usb_device = -1; memset(pIdent->edidbytes, '\0', 128); *pIdent->model_name = '\0'; *pIdent->serial_ascii = '\0'; return pIdent; } /** Creates a #Display_Identifier using a **ddcutil** display number * * \param dispno display number (1 based) * \return pointer to newly allocated #Display_Identifier * * \remark * It is the responsibility of the caller to free the allocated * #Display_Identifier using #free_display_identifier(). */ Display_Identifier* create_dispno_display_identifier(int dispno) { Display_Identifier* pIdent = common_create_display_identifier(DISP_ID_DISPNO); pIdent->dispno = dispno; return pIdent; } /** Creates a #Display_Identifier using an I2C bus number * * \param busno O2C bus number * \return pointer to newly allocated #Display_Identifier * * \remark * It is the responsibility of the caller to free the allocated * #Display_Identifier using #free_display_identifier(). */ Display_Identifier* create_busno_display_identifier(int busno) { Display_Identifier* pIdent = common_create_display_identifier(DISP_ID_BUSNO); pIdent->busno = busno; return pIdent; } /** Creates a #Display_Identifier using an EDID value * * \param edidbytes pointer to 128 byte EDID value * \return pointer to newly allocated #Display_Identifier * * \remark * It is the responsibility of the caller to free the allocated * #Display_Identifier using #free_display_identifier(). */ Display_Identifier* create_edid_display_identifier(const Byte* edidbytes) { Display_Identifier* pIdent = common_create_display_identifier(DISP_ID_EDID); memcpy(pIdent->edidbytes, edidbytes, 128); return pIdent; } /** Creates a #Display_Identifier using one or more of * manufacturer id, model name, and/or serial number string * as recorded in the EDID. * * \param mfg_id manufacturer id * \param model_name model name * \param serial_ascii string serial number * \return pointer to newly allocated #Display_Identifier * * \remark * Unspecified parameters can be either NULL or strings of length 0. * \remark * At least one parameter must be non-null and have length > 0. * \remark * It is the responsibility of the caller to free the allocated * #Display_Identifier using #free_display_identifier(). */ Display_Identifier* create_mfg_model_sn_display_identifier( const char* mfg_id, const char* model_name, const char* serial_ascii) { assert(!mfg_id || strlen(mfg_id) < EDID_MFG_ID_FIELD_SIZE); assert(!model_name || strlen(model_name) < EDID_MODEL_NAME_FIELD_SIZE); assert(!serial_ascii || strlen(serial_ascii) < EDID_SERIAL_ASCII_FIELD_SIZE); Display_Identifier* pIdent = common_create_display_identifier(DISP_ID_MONSER); if (mfg_id) strcpy(pIdent->mfg_id, mfg_id); else pIdent->model_name[0] = '\0'; if (model_name) strcpy(pIdent->model_name, model_name); else pIdent->model_name[0] = '\0'; if (serial_ascii) strcpy(pIdent->serial_ascii, serial_ascii); else pIdent->serial_ascii[0] = '\0'; assert( strlen(pIdent->mfg_id) + strlen(pIdent->model_name) + strlen(pIdent->serial_ascii) > 0); return pIdent; } /** Creates a #Display_Identifier using a USB /dev/usb/hiddevN device number * * \param hiddev_devno hiddev device number * \return pointer to newly allocated #Display_Identifier * * \remark * It is the responsibility of the caller to free the allocated * #Display_Identifier using #free_display_identifier(). */ Display_Identifier* create_usb_hiddev_display_identifier(int hiddev_devno) { Display_Identifier* pIdent = common_create_display_identifier(DISP_ID_HIDDEV); pIdent->hiddev_devno = hiddev_devno; return pIdent; } /** Creates a #Display_Identifier using a USB bus number/device number pair. * * \param bus USB bus number * \param device USB device number * \return pointer to newly allocated #Display_Identifier * * \remark * It is the responsibility of the caller to free the allocated * #Display_Identifier using #free_display_identifier(). */ Display_Identifier* create_usb_display_identifier(int bus, int device) { Display_Identifier* pIdent = common_create_display_identifier(DISP_ID_USB); pIdent->usb_bus = bus; pIdent->usb_device = device; return pIdent; } /** Reports the contents of a #Display_Identifier in a format suitable * for debugging use. * * \param pdid pointer to #Display_Identifier instance * \param depth logical indentation depth */ void dbgrpt_display_identifier(Display_Identifier * pdid, int depth) { rpt_structure_loc("BasicStructureRef", pdid, depth ); int d1 = depth+1; rpt_mapped_int("ddc_io_mode", NULL, pdid->id_type, (Value_To_Name_Function) display_id_type_name, d1); rpt_int( "dispno", NULL, pdid->dispno, d1); rpt_int( "busno", NULL, pdid->busno, d1); rpt_int( "usb_bus", NULL, pdid->usb_bus, d1); rpt_int( "usb_device", NULL, pdid->usb_device, d1); rpt_int( "hiddev_devno", NULL, pdid->hiddev_devno, d1); rpt_str( "mfg_id", NULL, pdid->mfg_id, d1); rpt_str( "model_name", NULL, pdid->model_name, d1); rpt_str( "serial_ascii", NULL, pdid->serial_ascii, d1); char * edidstr = hexstring(pdid->edidbytes, 128); rpt_str( "edid", NULL, edidstr, d1); free(edidstr); } /** Returns a succinct representation of a #Display_Identifier for * debugging purposes. * * \param pdid pointer to #Display_Identifier * \return pointer to string description * * \remark * The returned pointer is valid until the #Display_Identifier is freed. */ char * did_repr(Display_Identifier * pdid) { char * result = NULL; if (pdid) { if (!pdid->repr) { char * did_type_name = display_id_type_name(pdid->id_type); switch (pdid->id_type) { case(DISP_ID_BUSNO): pdid->repr = g_strdup_printf( "Display Id[type=%s, bus=/dev/i2c-%d]", did_type_name, pdid->busno); break; case(DISP_ID_MONSER): pdid->repr = g_strdup_printf( "Display Id[type=%s, mfg=%s, model=%s, sn=%s]", did_type_name, pdid->mfg_id, pdid->model_name, pdid->serial_ascii); break; case(DISP_ID_EDID): { char * hs = hexstring(pdid->edidbytes, 128); pdid->repr = g_strdup_printf( "Display Id[type=%s, edid=%8s...%8s]", did_type_name, hs, hs+248); free(hs); break; } case(DISP_ID_DISPNO): pdid->repr = g_strdup_printf( "Display Id[type=%s, dispno=%d]", did_type_name, pdid->dispno); break; case DISP_ID_USB: pdid->repr = g_strdup_printf( "Display Id[type=%s, usb bus:device=%d.%d]", did_type_name, pdid->usb_bus, pdid->usb_device);; break; case DISP_ID_HIDDEV: pdid->repr = g_strdup_printf( "Display Id[type=%s, hiddev_devno=%d]", did_type_name, pdid->hiddev_devno); break; } // switch } // !pdid->repr result = pdid->repr; } return result; } /** Frees a #Display_Identifier instance * * \param pdid pointer to #Display_Identifier to free */ void free_display_identifier(Display_Identifier * pdid) { if (pdid) { assert( memcmp(pdid->marker, DISPLAY_IDENTIFIER_MARKER, 4) == 0); pdid->marker[3] = 'x'; free(pdid->repr); // may be null, that's ok free(pdid); } } // #ifdef FUTURE // *** Display Selector *** (future) Display_Selector * dsel_new() { Display_Selector * dsel = calloc(1, sizeof(Display_Selector)); memcpy(dsel->marker, DISPLAY_SELECTOR_MARKER, 4); dsel->dispno = -1; dsel->busno = -1; dsel->usb_bus = -1; dsel->usb_device = -1; return dsel; } void dsel_free(Display_Selector * dsel) { if (dsel) { assert(memcmp(dsel->marker, DISPLAY_SELECTOR_MARKER, 4) == 0); free(dsel->mfg_id); free(dsel->model_name); free(dsel->serial_ascii); free(dsel->edidbytes); } } // #endif // *** DDCA_IO_Mode and DDCA_IO_Path *** static char * IO_Mode_Names[] = { "DDCA_IO_I2C", "DDCA_IO_USB" }; /** Returns the symbolic name of a #DDCA_IO_Mode value. * * \param val #DDCA_IO_Mode value * \return symbolic name, e.g. "DDCA_IO_DEVI2C" */ char * io_mode_name(DDCA_IO_Mode val) { return (val >= 0 && val < 2) // protect against bad arg ? IO_Mode_Names[val] : NULL; } /** A simple function allowing for the assignment of a value to a * #DDCA_IO_Path instance in a single line of code. * * @parm busno I2C bus number * @return DDCA_IO_Path value */ DDCA_IO_Path i2c_io_path(int busno) { DDCA_IO_Path path; path.io_mode = DDCA_IO_I2C; path.path.i2c_busno = busno; return path; } /** A simple function allowing for the assignment of a value to a * #DDCA_IO_Path instance in a single line of code. * * @parm hiddev USB device number * @return DDCA_IO_Path value */ DDCA_IO_Path usb_io_path(int hiddev_devno) { DDCA_IO_Path path; path.io_mode = DDCA_IO_USB; path.path.hiddev_devno = hiddev_devno; return path; } /** Thread safe function that returns a brief string representation of a #DDCA_IO_Path. * The returned value is valid until the next call to this function on the current thread. * * \remark * A bus number of 255 represents a value that has not been set. The string * "NOT SET" is returned. * * \param dpath pointer to ##DDCA_IO_Path * \return string representation of #DDCA_IO_Path */ char * dpath_short_name_t(DDCA_IO_Path * dpath) { static GPrivate dpath_short_name_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&dpath_short_name_key, 100); switch(dpath->io_mode) { case DDCA_IO_I2C: if (dpath->path.i2c_busno == 255) g_strlcpy(buf, "NOT SET", 100); else g_snprintf(buf, 100, "bus /dev/i2c-%d", dpath->path.i2c_busno); break; case DDCA_IO_USB: g_snprintf(buf, 100, "usb /dev/usb/hiddev%d", dpath->path.hiddev_devno); } return buf; } /** Thread safe function that returns a string representation of a #DDCA_IO_Path * suitable for diagnostic messages. The returned value is valid until the * next call to this function on the current thread. * * \param dpath pointer to ##DDCA_IO_Path * \return string representation of #DDCA_IO_Path */ char * dpath_repr_t(DDCA_IO_Path * dpath) { static GPrivate dpath_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&dpath_repr_key, 100); switch(dpath->io_mode) { case DDCA_IO_I2C: if (dpath->path.i2c_busno == BUSNO_NOT_SET) snprintf(buf, 100, "Display Path not set"); else snprintf(buf, 100, "Display_Path[/dev/i2c-%d]", dpath->path.i2c_busno); break; case DDCA_IO_USB: snprintf(buf, 100, "Display_Path[/dev/usb/hiddev%d]", dpath->path.hiddev_devno); } return buf; } // *** Display_Ref *** static uint max_dref_id = 0; static GMutex max_dref_id_mutex; static GHashTable * published_dref_hash = NULL; static GMutex dref_hash_mutex; void init_published_dref_hash() { published_dref_hash = g_hash_table_new(g_direct_hash, NULL); } void reset_published_dref_hash() { if (published_dref_hash) g_hash_table_destroy(published_dref_hash); init_published_dref_hash(); } void dbgrpt_published_dref_hash(const char * msg, int depth) { if (msg) rpt_vstring(depth, "%s: dref_hash_contents:", msg); else rpt_label(depth, "dref_hash contents: "); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter, published_dref_hash); while (g_hash_table_iter_next (&iter, &key, &value)) { uint dref_id = GPOINTER_TO_UINT(key); Display_Ref * dref = (Display_Ref *) value; rpt_vstring(depth+1, "dref_id %d -> %s", dref_id, dref_reprx_t(dref)); } } static uint next_dref_id(Display_Ref * dref) { bool debug = false; g_mutex_lock (&max_dref_id_mutex); guint nextid = ++max_dref_id; g_mutex_unlock(&max_dref_id_mutex); DBGTRC_EXECUTED(debug, DDCA_TRC_NONE, "nextid = %u", nextid); return nextid; } void add_published_dref_id_by_dref(Display_Ref * dref) { bool debug = false; g_mutex_lock (&dref_hash_mutex); g_hash_table_insert(published_dref_hash, GUINT_TO_POINTER(dref->dref_id), dref); if (debug) { char msgbuf[100]; g_snprintf(msgbuf, 100, "After dref %s inserted", dref_reprx_t(dref)); dbgrpt_published_dref_hash(msgbuf, 0); } g_mutex_unlock(&dref_hash_mutex); DBGTRC_EXECUTED(debug, DDCA_TRC_NONE, "%s -> %d", dref_reprx_t(dref), dref->dref_id); } static void delete_published_dref_id(uint dref_id) { bool debug = false; g_mutex_lock (&dref_hash_mutex); g_hash_table_remove(published_dref_hash, GUINT_TO_POINTER(dref_id)); if (debug) { char msgbuf[50]; g_snprintf(msgbuf, 50, "After dref_id %d removed", dref_id); dbgrpt_published_dref_hash(msgbuf, 0); } g_mutex_unlock(&dref_hash_mutex); } #ifdef UNUSED Display_Ref * dref_id_to_ptr(guint dref_id) { bool debug = false; if (debug) dbgrpt_published_dref_hash("Before g_hash_table_lookup", 2); Display_Ref * dref = g_hash_table_lookup(published_dref_hash, GUINT_TO_POINTER(dref_id)); return dref; } #endif /** Given a DDCA_Display_Ref, looks up the corresponding Display_Ref* * in the hash table of external display refs that have been given * to the client. * * @param ddca_dref public opaque display ref * @result pointer to internal Display_Ref, NULL if not found */ Display_Ref * dref_from_published_ddca_dref(DDCA_Display_Ref ddca_dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "ddca_dref = %p", ddca_dref); #ifdef NUMERIC_DDCA_DISPLAY_REF // if (debug) // dbgrpt_published_dref_hash(__func__, 1); guint id = GPOINTER_TO_UINT(ddca_dref); Display_Ref * dref = g_hash_table_lookup(published_dref_hash, GUINT_TO_POINTER(id)); if (dref) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ddca_dref=%p -> %s", ddca_dref, dref_reprx_t(dref)); if (memcmp(dref->marker, DISPLAY_REF_MARKER, 4) != 0) dbgrpt_display_ref(dref, true, 2); assert(memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); } #else Display_Ref * dref = (Display_Ref*) ddca_dref; if (dref) { if (memcmp(dref->marker, DISPLAY_REF_MARKER, 4) != 0) dref = NULL; } #endif if (dref) DBGTRC_DONE(debug, DDCA_TRC_NONE, "ddca_dref=%p, returning %p -> %s", ddca_dref, dref, dref_reprx_t(dref)); else DBGTRC_DONE(debug, DDCA_TRC_NONE, "ddca_dref=%p, returning %p", ddca_dref, dref); return dref; } DDCA_Display_Ref dref_to_ddca_dref(Display_Ref * dref) { bool debug = false; DDCA_Display_Ref ddca_dref = (DDCA_Display_Ref*) GUINT_TO_POINTER(0); if (dref) { #ifdef NUMERIC_DDCA_DISPLAY_REF ddca_dref = (DDCA_Display_Ref*) GUINT_TO_POINTER(dref->dref_id); #else ddca_dref = (void*) dref; #endif DBGTRC_EXECUTED(debug, DDCA_TRC_NONE, "dref=%p, dref->dref_id=%d, returning %p", dref, dref->dref_id, ddca_dref); } else DBGTRC_EXECUTED(debug, DDCA_TRC_NONE, "dref=%p, returning %p", dref, ddca_dref); return ddca_dref; } Display_Ref * create_base_display_ref(DDCA_IO_Path io_path) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_BASE, "io_path=%s", dpath_repr_t(&io_path)); Display_Ref * dref = calloc(1, sizeof(Display_Ref)); memcpy(dref->marker, DISPLAY_REF_MARKER, 4); dref->io_path = io_path; dref->dref_id = next_dref_id(dref); dref->vcp_version_xdf = DDCA_VSPEC_UNQUERIED; dref->vcp_version_cmdline = DDCA_VSPEC_UNQUERIED; dref->creation_timestamp = cur_realtime_nanosec(); // Per_Display_Data * pdd = pdd_get_per_display_data(io_path, true); // dref->pdd = pdd; g_mutex_init(&dref->access_mutex); // DBGTRC_RET_STRUCT(debug, DDCA_TRC_BASE, "Display_Ref", dbgrpt_display_ref, dref); DBGTRC_DONE(debug, DDCA_TRC_BASE, "Returning %p", dref); return dref; } // PROBLEM: bus display ref getting created some other way /** Creates a #Display_Ref for IO mode #DDCA_IO_I2C * * @param busno /dev/i2c bus number * \return pointer to newly allocated #Display_Ref */ Display_Ref * create_bus_display_ref(int busno) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_BASE, "busno=%d", busno); DDCA_IO_Path io_path; io_path.io_mode = DDCA_IO_I2C; io_path.path.i2c_busno = busno; Display_Ref * dref = create_base_display_ref(io_path); #ifdef OLD dref->driver_name = get_i2c_sysfs_driver_by_busno(busno); #endif if (debug) { DBGMSG("Done. Constructed bus display ref %s:", dref_repr_t(dref)); dbgrpt_display_ref(dref, true, 0); } DBGTRC_RET_STRUCT(debug, DDCA_TRC_BASE, "Display_Ref", dbgrpt_display_ref0, dref); return dref; } #ifdef ENABLE_USB /** Creates a #Display_Ref for IO mode #DDCA_IO_USB * * @param usb_bus USB bus number * @param usb_device USB device number * @param hiddev_devname device name, e.g. /dev/usb/hiddev1 * \return pointer to newly allocated #Display_Ref */ Display_Ref * create_usb_display_ref(int usb_bus, int usb_device, char * hiddev_devname) { assert(hiddev_devname); bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_BASE, "usb_bus=%d, usb_device=%d, hiddev_devname=%s", usb_bus, usb_device, hiddev_devname); DDCA_IO_Path io_path; io_path.io_mode = DDCA_IO_USB; io_path.path.hiddev_devno = hiddev_name_to_number(hiddev_devname); Display_Ref * dref = create_base_display_ref(io_path); dref->usb_bus = usb_bus; dref->usb_device = usb_device; dref->usb_hiddev_name = g_strdup(hiddev_devname); DBGTRC_RET_STRUCT(debug, DDCA_TRC_BASE, "Display_Ref", dbgrpt_display_ref0, dref); // DBGTRC_DONE(debug, DDCA_TRC_BASE, "Returning %p", dref); return dref; } #endif Display_Ref * copy_display_ref(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_BASE, "dref=%p, iopath=%s", dref, (dref) ? dpath_repr_t(&dref->io_path) : NULL); Display_Ref * copy = NULL; if (dref) { DDCA_IO_Path iopath = dref->io_path; copy = create_base_display_ref(iopath); copy->usb_bus = dref->usb_bus; copy->dref_id = next_dref_id(copy); copy->usb_device = dref->usb_device; copy->usb_hiddev_name = g_strdup(dref->usb_hiddev_name); copy->vcp_version_xdf = dref->vcp_version_xdf; copy->vcp_version_cmdline = dref->vcp_version_cmdline; copy->flags = dref->flags & ~DREF_DYNAMIC_FEATURES_CHECKED; copy->capabilities_string = g_strdup(dref->capabilities_string); if (dref->pedid) { copy->pedid = copy_parsed_edid(dref->pedid); } if (dref->mmid) { copy->mmid = calloc(1, sizeof(Monitor_Model_Key)); memcpy(copy->mmid, dref->mmid, sizeof(Monitor_Model_Key)); } copy->dispno = dref->dispno; // do not set detail // do not set dfr // do not set actual_display copy->actual_display_path = dref->actual_display_path; #ifdef OLD copy->driver_name = g_strdup(dref->driver_name); #endif // dont set pdd copy->drm_connector = g_strdup(dref->drm_connector); copy->drm_connector_id = dref->drm_connector_id; } // DBGTRC_RET_STRUCT(debug, DDCA_TRC_BASE, "Display_Ref", dbgrpt_display_ref, copy); DBGTRC_DONE(debug, DDCA_TRC_BASE, "Returning %p", copy); return copy; } //#define CK_INVALIDATED_MARKER(_marker, _marker_name) ( (memcmp(_marker, _marker_name, 3) == 0) && (_marker[3] = 'x'))) // assert( !(INVALIDATED_MARKER(dref->marker, DISPLAY_REF_MARKER)); /** Frees a display reference. * * \param dref ptr to display reference to free, if NULL no operation is performed * \retval DDCRC_OK success * \retval DDCRC_LOCKED display reference not marked as transient */ DDCA_Status free_display_ref(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_BASE, "dref=%p", dref); DDCA_Status ddcrc = 0; if (dref) { assert ( memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); DBGTRC_NOPREFIX(debug, DDCA_TRC_BASE, "dref=%s, DREF_TRANSIENT=%s, DREF_OPEN=%s", dref_repr_t(dref), SBOOL(dref->flags & DREF_TRANSIENT), SBOOL(dref->flags&DREF_OPEN)); if (dref->flags & DREF_TRANSIENT) { if (dref->flags & DREF_OPEN) { ddcrc = DDCRC_LOCKED; } else { uint dref_id = dref->dref_id; free(dref->usb_hiddev_name); // private copy free(dref->capabilities_string); // private copy free(dref->mmid); // private copy if (dref->pedid) { DBGTRC(debug, DDCA_TRC_NONE, "Freeing dref->pedid = %p", dref->pedid); free_parsed_edid(dref->pedid); // private copy } dfr_free(dref->dfr); #ifdef OLD free(dref->driver_name); #endif free(dref->drm_connector); free(dref->communication_error_summary); g_mutex_clear(&dref->access_mutex); dref->marker[3] = 'x'; free(dref); delete_published_dref_id(dref_id); } } } DBGTRC_RET_DDCRC(debug, DDCA_TRC_BASE, ddcrc, ""); return ddcrc; } void dref_lock(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "locking dref %s ...", dref_reprx_t(dref)); bool was_locked = !g_mutex_trylock(&(dref->access_mutex)); if (was_locked ) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "dref %s is locked, waiting ... ", dref_reprx_t(dref)); g_mutex_lock(&(dref->access_mutex)); DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "obtained lock on %s", dref_reprx_t(dref)); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "dref %s", dref_reprx_t(dref)); } void dref_unlock(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "unlocking dref %s ...", dref_reprx_t(dref)); g_mutex_unlock(&dref->access_mutex); DBGTRC_DONE(debug, DDCA_TRC_NONE, "dref %s unlocked", dref_reprx_t(dref)); } #ifdef UNNEEDED // wraps free_display_ref() as GDestroyNotify() void gdestroy_display_ref(void * data) { free_display_ref((Display_Ref*) data); } #endif /** Tests if 2 #Display_Ref instances specify the same path to the * display. * * Note that if a display communicates MCCS over both I2C and USB * these are different paths to the display. * * \param this pointer to first #Display_Ref * \param that pointer to second Ddisplay_Ref * \retval true same display * \retval false different displays */ bool dref_eq(Display_Ref* this, Display_Ref* that) { return dpath_eq(this->io_path, that->io_path); } /** Gets the driver name for an I2C device. * * @param dref display reference * @return driver name, caller SHOULD NOT free * * Returns NULL if not a I2C device, or display ref is disconnected */ const char * dref_get_i2c_driver(Display_Ref* dref) { char * result = NULL; if (dref->io_path.io_mode == DDCA_IO_I2C) { I2C_Bus_Info* businfo = dref->detail; if (businfo) result = businfo->driver; } return result; } #ifdef UNUSED bool dref_set_alive(Display_Ref * dref, bool alive) { assert(dref); bool debug = false; bool old = dref->flags & DREF_ALIVE; if (old != alive) DBGTRC_EXECUTED(debug, DDCA_TRC_BASE, "dref=%s, alive changed: %s -> %s", dref_repr_t(dref), SBOOL(old), SBOOL(alive)); SETCLR_BIT(dref->flags, DREF_ALIVE, alive); return old; } bool dref_get_alive(Display_Ref * dref) { assert(dref); return dref->flags & DREF_ALIVE;; } #endif /** Reports the contents of a #Display_Ref in a format useful for debugging. * * \param dref pointer to #Display_Ref instance * \param depth logical indentation depth */ void dbgrpt_display_ref(Display_Ref * dref, bool include_businfo, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dref=%s", dref_repr_t(dref)); int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("Display_Ref", dref, depth); rpt_vstring(d1, "marker %.4s", dref->marker); rpt_vstring(d1, "dref_id %d", dref->dref_id); rpt_vstring(d1, "io_path: %s", dpath_repr_t(&(dref->io_path))); if (dref->io_path.io_mode == DDCA_IO_USB) { rpt_int("usb_bus", NULL, dref->usb_bus, d1); rpt_int("usb_device", NULL, dref->usb_device, d1); rpt_str("usb_hiddev_name", NULL, dref->usb_hiddev_name, d1); } rpt_vstring(d1, "vcp_version_xdf: %s", format_vspec(dref->vcp_version_xdf) ); rpt_vstring(d1, "vcp_version_cmdline: %s", format_vspec(dref->vcp_version_cmdline) ); rpt_vstring(d1, "flags: %s", interpret_dref_flags_t(dref->flags) ); rpt_vstring(d1, "capabilities_string: %s", dref->capabilities_string); rpt_vstring(d1, "mmid: %s", (dref->mmid) ? mmk_repr(*dref->mmid) : "NULL"); rpt_vstring(d1, "dispno: %d", dref->dispno); rpt_vstring(d1, "pedid: %p", dref->pedid); report_parsed_edid(dref->pedid, /*verbose*/ false, depth+1); #ifdef OLD rpt_vstring(d1, "driver: %s", dref->driver_name); #endif rpt_vstring(d1, "actual_display: %p", dref->actual_display); rpt_vstring(d1, "actual_display_path: %s", (dref->actual_display_path) ? dpath_repr_t(dref->actual_display_path) : "NULL"); rpt_vstring(d1, "detail: %p", dref->detail); if (dref->io_path.io_mode == DDCA_IO_I2C && include_businfo) { I2C_Bus_Info * businfo = dref->detail; if (businfo) { i2c_dbgrpt_bus_info(businfo, true, d2); } } rpt_vstring(d1, "drm_connector: %s", dref->drm_connector); rpt_vstring(d1, "drm_connector_id: %d", dref->drm_connector_id); rpt_vstring(d1, "creation_timestamp: %s", formatted_time_t(dref->creation_timestamp)); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } // for use by DBGTRC_RET_STRUCT() void dbgrpt_display_ref0(Display_Ref * dref, int depth) { dbgrpt_display_ref(dref, true, depth); } void dbgrpt_display_ref_summary(Display_Ref * dref, bool include_businfo, int depth) { bool debug = false; int d1 = depth+1; int d2 = depth+2; assert(dref); DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dref=%s", dref_reprx_t(dref)); rpt_vstring(depth, "%s", dref_reprx_t(dref)); rpt_vstring(d1, "dref_id %d", dref->dref_id); // rpt_vstring(d1, "io_path: %s", dpath_repr_t(&(dref->io_path))); rpt_vstring(d1, "flags: %s", interpret_dref_flags_t(dref->flags) ); rpt_vstring(d1, "mmid: %s", (dref->mmid) ? mmk_repr(*dref->mmid) : "NULL"); rpt_vstring(d1, "dispno: %d", dref->dispno); rpt_vstring(d1, "pedid: %p", dref->pedid); // report_parsed_edid(dref->pedid, /*verbose*/ false, depth+1); rpt_vstring(d1, "detail: %p", dref->detail); if (dref->io_path.io_mode == DDCA_IO_I2C && include_businfo) { I2C_Bus_Info * businfo = dref->detail; if (businfo) { i2c_dbgrpt_bus_info(businfo, false, d2); } } rpt_vstring(d1, "drm_connector: %s", dref->drm_connector); rpt_vstring(d1, "drm_connector_id: %d", dref->drm_connector_id); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } /** Thread safe function that returns a short description of a #Display_Ref. * The returned value is valid until the next call to this function on * the current thread. * * \param dref pointer to #Display_Ref * \return short description */ char * dref_short_name_t(Display_Ref * dref) { return dpath_short_name_t(&dref->io_path); } /** Thread safe function that returns a string representation of a #Display_Ref * suitable for diagnostic messages. The returned value is valid until the * next call to this function on the current thread. * * \param dref pointer to #Display_Ref * \return string representation of #Display_Ref */ char * dref_repr_t(Display_Ref * dref) { static GPrivate dref_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&dref_repr_key, 100); if (dref) #ifdef WITH_ADDR g_snprintf(buf, 100, "Display_Ref[%d:%s @%p]", dref->dref_id, dpath_short_name_t(&dref->io_path), (void*)dref); #else g_snprintf(buf, 100, "Display_Ref[%d:%s]", dref->dref_id, dpath_short_name_t(&dref->io_path)); #endif else strcpy(buf, "Display_Ref[NULL]"); return buf; } /** Thread safe function that returns an extended string representation * of a #Display_Ref, suitable for diagnostic messages. * The representation includes the address of the #Display_Ref and * an indication if the display reference is for a disconnected monitor. * * The returned value is valid until the next call to this function on * the current thread. * * \param dref pointer to #Display_Ref * \return string representation of #Display_Ref */ char * dref_reprx_t(Display_Ref * dref) { static GPrivate dref_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&dref_repr_key, 100); if (dref) g_snprintf(buf, 200, "Display_Ref[%s%d:%s @%p]", (dref->flags & DREF_REMOVED) ? "Disconnected: " : "", dref->dref_id, dpath_short_name_t(&dref->io_path), (void*) dref); else strcpy(buf, "Display_Ref[NULL]"); return buf; } char * ddci_dref_repr_t(DDCA_Display_Ref * ddca_dref) { static GPrivate dref_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&dref_repr_key, 100); #ifdef NUMERIC_DDCA_DISPLAY_REF g_snprintf(buf, 100, "DDCA_Display_Ref[%d]", GPOINTER_TO_INT(ddca_dref)); #else if (ddca_dref) { Display_Ref * dref = (Display_Ref*) ddca_dref; #ifdef WITH_ADDR g_snprintf(buf, 100, "DDCA_Display_Ref[%s @%p]", dpath_short_name_t(&dref->io_path), (void*)dref); #else g_snprintf(buf, 100, "DDCA_Display_Ref[%s]", dpath_short_name_t(&dref->io_path)); } #endif else strcpy(buf, "DDCA_Display_Ref[NULL]"); #endif return buf; } /** Locates the currently live Display_Ref for the specified bus. * Discarded display references, i.e. ones marked removed (flag DREF_REMOVED) * are ignored. There should be at most one non-removed Display_Ref. * * @param busno I2C_Bus_Number * @param connector * @param ignore_invalid * @return display reference, NULL if no live reference exists */ Display_Ref * get_dref_by_busno_or_connector( int busno, const char * connector, bool ignore_invalid) { ASSERT_IFF(busno >= 0, !connector); bool debug = false; debug = debug || debug_locks; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "busno = %d, connector = %s, ignore_invalid=%s", busno, connector, SBOOL(ignore_invalid)); assert(all_display_refs); Display_Ref * result = NULL; int non_removed_ct = 0; uint64_t highest_non_removed_creation_timestamp = 0; // lock entire function on the extremely rare possibility that recovery // will mark a display ref removed g_mutex_lock(&all_display_refs_mutex); for (int ndx = 0; ndx < all_display_refs->len; ndx++) { // If a display is repeatedly removed and added on a particular connector, // there will be multiple Display_Ref records. All but one should already // be flagged DDCA_DISPLAY_REMOVED, // ?? and should not have a pointer to an I2C_Bus_Info struct. Display_Ref * cur_dref = g_ptr_array_index(all_display_refs, ndx); // DBGMSG("Checking dref %s", dref_repr_t(cur_dref)); if (ignore_invalid && cur_dref->dispno <= 0) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "cur_dref=%s@%p dispno < 0, Ignoring", dref_repr_t(cur_dref), cur_dref); continue; } // I2C_Bus_Info * businfo = (I2C_Bus_Info*) cur_dref->detail; // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "DREF_REMOVED=%s, dref_detail=%p -> /dev/i2c-%d", // sbool(cur_dref->flags&DREF_REMOVED), cur_dref->detail, businfo->busno); if (ignore_invalid && (cur_dref->flags&DREF_REMOVED)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "cur_dref=%s@%p DREF_REMOVED set, Ignoring", dref_repr_t(cur_dref), cur_dref); continue; } if (cur_dref->io_path.io_mode != DDCA_IO_I2C) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "cur_dref=%s@%p io_mode != DDCA_IO_I2C, Ignoring", dref_repr_t(cur_dref), cur_dref); continue; } if (connector) { // consistency check I2C_Bus_Info * businfo = cur_dref->detail; if (businfo) { assert(streq(businfo->drm_connector_name, cur_dref->drm_connector)); } else { SEVEREMSG("active display ref has no bus info"); } } if ( (busno >= 0 && cur_dref->io_path.path.i2c_busno == busno) || (connector && streq(connector, cur_dref->drm_connector) ) ) { // the match should only happen once, but count matches as check non_removed_ct++; if (cur_dref->creation_timestamp > highest_non_removed_creation_timestamp) { highest_non_removed_creation_timestamp = cur_dref->creation_timestamp; result = cur_dref; } } } // assert(non_removed_ct <= 1); if (non_removed_ct > 1) { if (!ignore_invalid) { // don't try to recover from this very very very rare case assert(non_removed_ct <= 1); } SEVEREMSG("Multiple non-removed displays on device %s detected. " "All but the most recent are being marked DDC_REMOVED", dpath_repr_t(&result->io_path)); for (int ndx = 0; ndx < all_display_refs->len; ndx++) { Display_Ref * cur_dref = g_ptr_array_index(all_display_refs, ndx); if (ignore_invalid && cur_dref->dispno <= 0) continue; if (ignore_invalid && (cur_dref->flags&DREF_REMOVED)) continue; if (cur_dref->io_path.io_mode != DDCA_IO_I2C) continue; if ( (busno >= 0 && cur_dref->io_path.path.i2c_busno == busno) || (connector && streq(connector, cur_dref->drm_connector) ) ) { if (cur_dref->creation_timestamp < highest_non_removed_creation_timestamp) { SEVEREMSG("Marking dref %s removed", dref_reprx_t(cur_dref)); //ddc_mark_display_ref_removed(cur_dref); cur_dref->flags |= DREF_REMOVED; } } } } g_mutex_unlock(&all_display_refs_mutex); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: %p= %s", result, dref_repr_t(result)); return result; } #ifdef UNUSED Display_Ref * ddc_get_display_ref_by_drm_connector( const char * connector_name, bool ignore_invalid) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "connector_name=%s, ignore_invalid=%s", connector_name, sbool(ignore_invalid)); Display_Ref * result = NULL; TRACED_ASSERT(all_display_refs); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "all_displays->len=%d", all_display_refs->len); for (int ndx = 0; ndx < all_display_refs->len; ndx++) { Display_Ref * cur = g_ptr_array_index(all_display_refs, ndx); // ddc_dbgrpt_display_ref(cur, 4); bool pass_filter = true; if (ignore_invalid) { pass_filter = (cur->dispno > 0 || !(cur->flags&DREF_REMOVED)); } if (pass_filter) { if (cur->io_path.io_mode == DDCA_IO_I2C) { I2C_Bus_Info * businfo = cur->detail; if (!businfo) { SEVEREMSG("active display ref has no bus info"); continue; } // TODO: handle drm_connector_name not yet checked if (businfo->drm_connector_name && streq(businfo->drm_connector_name,connector_name)) { result = cur; break; } } } } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %s = %p", dref_repr_t(result), result); return result; } #endif // *** Display_Handle *** /** Creates a #Display_Handle for a #Display_Ref. * * \param fd Linux file descriptor of open display * \param dref pointer to #Display_Ref * \return newly allocated #Display_Handle * * \remark * This functions handles the boilerplate of creating a #Display_Handle. */ Display_Handle * create_base_display_handle(int fd, Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "fd=%d, dref=%s", fd, dref_reprx_t(dref)); if (debug) dbgrpt_display_ref(dref, false, 1); Display_Handle * dh = calloc(1, sizeof(Display_Handle)); memcpy(dh->marker, DISPLAY_HANDLE_MARKER, 4); dh->fd = fd; dh->dref = dref; if (dref->io_path.io_mode == DDCA_IO_I2C) { dh->repr = g_strdup_printf("Display_Handle[i2c-%d: fd=%d]", dh->dref->io_path.path.i2c_busno, dh->fd); dh->repr_p = g_strdup_printf("Display_Handle[i2c-%d: fd=%d @%p]", dh->dref->io_path.path.i2c_busno, dh->fd, (void*)dh); } #ifdef ENABLE_USB else if (dref->io_path.io_mode == DDCA_IO_USB) { dh->repr = g_strdup_printf( "Display_Handle[usb: %d:%d, %s/hiddev%d @%p]", // "Display_Handle[usb: %d:%d, %s/hiddev%d]", dh->dref->usb_bus, dh->dref->usb_device, usb_hiddev_directory(), dh->dref->io_path.path.hiddev_devno, (void*)dh); } #endif else { // DDCA_IO_USB if !ENABLE_USB PROGRAM_LOGIC_ERROR("Unimplemented io_mode = %d", dref->io_path.io_mode); dbgrpt_display_ref(dref, false, 1); dh->repr = NULL; } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning %p", dh); return dh; } /** Reports the contents of a #Display_Handle in a format useful for debugging. * * \param dh display handle * \param msg if non-null, output this string before the #Display_Handle detail * \param depth logical indentation depth */ void dbgrpt_display_handle(Display_Handle * dh, const char * msg, int depth) { int d1 = depth+1; if (msg) rpt_vstring(depth, "%s", msg); rpt_vstring(d1, "Display_Handle: %p", dh); if (dh) { if (memcmp(dh->marker, DISPLAY_HANDLE_MARKER, 4) != 0) { rpt_vstring(d1, "Invalid marker in struct: 0x%08x, |%.4s|\n", *dh->marker, (char *)dh->marker); } else { rpt_vstring(d1, "dref: %p", dh->dref); rpt_vstring(d1, "io mode: %s", io_mode_name(dh->dref->io_path.io_mode) ); switch (dh->dref->io_path.io_mode) { case (DDCA_IO_I2C): // rpt_vstring(d1, "ddc_io_mode = DDC_IO_DEVI2C"); rpt_vstring(d1, "fd: %d", dh->fd); rpt_vstring(d1, "busno: %d", dh->dref->io_path.path.i2c_busno); break; case (DDCA_IO_USB): // rpt_vstring(d1, "ddc_io_mode = USB_IO"); rpt_vstring(d1, "fd: %d", dh->fd); rpt_vstring(d1, "usb_bus: %d", dh->dref->usb_bus); rpt_vstring(d1, "usb_device: %d", dh->dref->usb_device); rpt_vstring(d1, "hiddev_device_name: %s", dh->dref->usb_hiddev_name); break; } rpt_vstring(d1, "testing_unsupported_feature_active: %s", sbool(dh->testing_unsupported_feature_active)); } // rpt_vstring(d1, "vcp_version: %d.%d", dh->vcp_version.major, dh->vcp_version.minor); } } /** Returns a string summarizing the specified #Display_Handle. * * \param dh display handle * \return string representation of handle * * \remark * The value is calculated when the Display_Handle is created. */ char * dh_repr(Display_Handle * dh) { if (!dh) return "Display_Handle[NULL]"; return dh->repr; } /** Returns a string summarizing the specified #Display_Handle, * including its address. * * \param dh display handle * \return string representation of handle * * \remark * The value is calculated when the Display_Handle is created. */ char * dh_repr_p(Display_Handle * dh) { if (!dh) return "Display_Handle[NULL]"; return dh->repr_p; } /** Frees a #Display_Handle struct. * * \param dh display handle to free */ void free_display_handle(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_BASE, "dh=%p -> %s", dh, dh_repr(dh)); if (dh && memcmp(dh->marker, DISPLAY_HANDLE_MARKER, 4) == 0) { dh->marker[3] = 'x'; free(dh->repr); free(dh->repr_p); free(dh); } DBGTRC_DONE(debug, DDCA_TRC_BASE, ""); } // *** Miscellaneous *** #ifdef ENABLE_USB /** Given a hiddev device name, e.g. /dev/usb/hiddev3, * extract its number, e.g. 3. * * \param hiddev_name device name * \return device number, -1 if error */ int hiddev_name_to_number(const char * hiddev_name) { assert(hiddev_name); char * p = strstr(hiddev_name, "hiddev"); int hiddev_number = -1; if (p) { p = p + strlen("hiddev"); if (strlen(p) > 0) { // hiddev_number unchanged if error // n str_to_int() allows leading whitespace, not worth checking bool ok = str_to_int(p, &hiddev_number, 10); if (!ok) hiddev_number = -1; // not necessary, but makes coverity happy } } // DBGMSG("hiddev_name = |%s|, returning: %d", hiddev_name, hiddev_number); return hiddev_number; } #ifdef UNUSED /** Given a hiddev device number, e.g. 3, return its name, e.g. /dev/usb/hiddev3 * * \param hiddev_number device number * \return device name * * \remark It the the responsibility of the caller to free the returned string. */ char * hiddev_number_to_name(int hiddev_number) { assert(hiddev_number >= 0); char * s = g_strdup_printf("%s/hiddev%d", usb_hiddev_directory(),hiddev_number); // DBGMSG("hiddev_number=%d, returning: %s", hiddev_number, s); return s; } #endif #endif // globals bool ddc_never_uses_null_response_for_unsupported = false; // bool ddc_always_uses_null_response_for_unsupported = false; Value_Name_Table dref_flags_table = { VN(DREF_DDC_COMMUNICATION_CHECKED), VN(DREF_DDC_COMMUNICATION_WORKING), VN(DREF_DDC_IS_MONITOR_CHECKED), VN(DREF_DDC_IS_MONITOR), VN(DREF_UNSUPPORTED_CHECKED), VN(DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED), VN(DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED), VN(DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED), VN(DREF_DDC_DOES_NOT_INDICATE_UNSUPPORTED), VN(DREF_TRANSIENT), VN(DREF_DYNAMIC_FEATURES_CHECKED), VN(DREF_OPEN), VN(DREF_DDC_BUSY), VN(DREF_REMOVED), VN(DREF_DDC_DISABLED), VN(DREF_DPMS_SUSPEND_STANDBY_OFF), // VN(CALLOPT_NONE), // special entry VN_END }; /** Interprets a **Dref_Flags** value as a printable string. * The returned value is valid until the next call of this function in * the current thread. * * @param flags value to interpret * * @return interpreted value */ char * interpret_dref_flags_t(Dref_Flags flags) { static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&buf_key, 300); char * buftemp = vnt_interpret_flags(flags, dref_flags_table, false, ", "); g_strlcpy(buf, buftemp, 300); // n. this is a debug msg, truncation benign free(buftemp); return buf; } const char * watch_mode_name(DDC_Watch_Mode mode) { char * result = NULL; switch (mode) { case Watch_Mode_Poll: result = "Watch_Mode_Poll"; break; case Watch_Mode_Xevent: result = "Watch_Mode_Xevent"; break; case Watch_Mode_Udev: result = "Watch_Mode_Udev"; break; case Watch_Mode_Dynamic: result = "Watch_Mode_Dynamic"; break; } return result; } void free_bus_open_error(Bus_Open_Error * boe) { free(boe->detail); free(boe); } // // Monitor models for which DDC is disabled // static GPtrArray * ddc_disabled_table = NULL; /** Adds a Monitor Model Id to the list of monitors for which DDC is disabled * * @param mmid monitor model key string * @return true if mmid is defined, false if not * * @remark * If the **ddc_disabled_table** does not already exist, it is created. */ bool add_disabled_display(Monitor_Model_Key * p_mmk) { bool debug = false; char * repr = NULL; if (debug) { repr = mmk_repr(*p_mmk); DBG("Starting. mmk=|%s|", repr); } bool result = false; bool missing = true; if (p_mmk->defined) { // if it's a valid monitor model id string DBGF(debug, "%s is valid:", repr); if (!ddc_disabled_table) ddc_disabled_table = g_ptr_array_new(); // n. g_ptr_array_find_with_equal_func() requires glib 2.54 for (int ndx = 0; ndx < ddc_disabled_table->len; ndx++) { Monitor_Model_Key* p = g_ptr_array_index(ddc_disabled_table, ndx); if (monitor_model_key_eq(*p_mmk, *p)) { missing = false; break; } } if (missing) g_ptr_array_add(ddc_disabled_table, p_mmk); result = true; } DBGF(debug, "Done. mmk=%s, missing=%s, returning: %s", repr, sbool(missing), sbool(result)); return result; } bool add_disabled_mmk_by_string(const char * mmid) { bool result = false; Monitor_Model_Key* p_mmk = mmk_new_from_string(mmid); if (p_mmk) { add_disabled_display(p_mmk); result = true; } return result; } void dbgrpt_ddc_disabled_table(int depth) { const char * table_name = "ddc_disabled_table"; GPtrArray* table = ddc_disabled_table; if (table) { if (table->len == 0) rpt_vstring(depth, "%s: empty", table_name); else { rpt_vstring(depth, "%s:", table_name); for (int ndx = 0; ndx < table->len; ndx++) { rpt_vstring(depth+1, mmk_repr(* (Monitor_Model_Key*) g_ptr_array_index(table, ndx))); } } } else { rpt_vstring(depth, "%s: NULL", table_name); } } /** Checks if DDC is disabled for a monitor model * * @param mmk monitor-model-id * @return **true** if the display type is disabled, **false** if not */ bool is_disabled_mmk(Monitor_Model_Key mmk) { bool debug = false; DBGF(debug, "Starting. mmk=%s", mmk_repr(mmk)); // dbgrpt_ddc_disabled_table(2); bool result = false; if (ddc_disabled_table) { for (int ndx = 0; ndx < ddc_disabled_table->len; ndx++) { Monitor_Model_Key* p = g_ptr_array_index(ddc_disabled_table, ndx); DBGF(debug, "Comparing vs p = %p -> %s", p, mmk_repr(*p)); if (monitor_model_key_eq(mmk, *p)) { result = true; break; } } } DBGF(debug, "mmid=|%s|, returning: %s", mmk_repr(mmk), SBOOL(result)); return result; } void init_displays() { RTTI_ADD_FUNC(copy_display_ref); RTTI_ADD_FUNC(create_base_display_handle); RTTI_ADD_FUNC(create_base_display_ref); RTTI_ADD_FUNC(create_bus_display_ref); #ifdef ENABLE_USB RTTI_ADD_FUNC(create_usb_display_ref); #endif RTTI_ADD_FUNC(dbgrpt_display_ref); RTTI_ADD_FUNC(free_display_handle); RTTI_ADD_FUNC(free_display_ref); RTTI_ADD_FUNC(dref_lock); RTTI_ADD_FUNC(dref_unlock); RTTI_ADD_FUNC(get_dref_by_busno_or_connector); init_published_dref_hash(); } void terminate_displays() { g_hash_table_destroy(published_dref_hash); } ddcutil-2.2.0/src/base/drm_connector_state.c0000644000175000001440000006173614754153540014546 /** @file drm_connector_state.c */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include // for all_displays_drm2() #include #include #include #include #include #include // for close() used by probe_dri_device_using_drm_api #include #include #include /** \endcond */ #include "util/coredefs_base.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/drm_common.h" #include "util/edid.h" #include "util/file_util.h" #include "util/libdrm_util.h" #include "util/subprocess_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_util.h" #include "base/core.h" #include "base/rtti.h" #include "base/drm_connector_state.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_BASE; static char * get_busid_from_fd(int fd) { int depth = 0; int d1 = depth+1; int d2 = depth+2; bool debug = false; DBGF(debug, "Starting. fd=%d", fd); char * busid = NULL; struct _drmDevice * ddev; // gets information about the opened DRM device // returns 0 on success, negative error code otherwise int rc = drmGetDevice(fd, &ddev); if (rc < 0) { rpt_vstring(depth, "drmGetDevice() returned %d", rc); // interpreted as error code: %s", rc, linux_errno_desc(-rc)); } else { if (debug) { rpt_vstring(d1, "Device information:"); rpt_vstring(d2, "bustype: %d - %s", ddev->bustype, drm_bus_type_name(ddev->bustype)); } busid = g_strdup_printf("%s:%04x:%02x:%02x.%d", drm_bus_type_name(ddev->bustype), // "PCI", ddev->businfo.pci->domain, ddev->businfo.pci->bus, ddev->businfo.pci->dev, ddev->businfo.pci->func); if (debug) { rpt_vstring(d2, "domain:bus:device.func: %s", busid); rpt_vstring(d2, "vendor vid:pid: 0x%04x:0x%04x", ddev->deviceinfo.pci->vendor_id, ddev->deviceinfo.pci->device_id); rpt_vstring(d2, "subvendor vid:pid: 0x%04x:0x%04x", ddev->deviceinfo.pci->subvendor_id, ddev->deviceinfo.pci->subdevice_id); rpt_vstring(d2, "revision id: 0x%04x", ddev->deviceinfo.pci->revision_id); } drmFreeDevice(&ddev); } DBGF(debug, "Returning: %s", busid); return busid; } typedef struct { char * name; int count; int * values; char ** value_names; } Enum_Metadata; static char * get_enum_value_name(Enum_Metadata * meta, int value) { char * result = "UNRECOGNIZED"; for (int i = 0; i < meta->count; i++) { if (meta->values[i] == value) { result = meta->value_names[i]; break; } } return result; } static const int EDID_PROP_ID = 1; static const int DPMS_PROP_ID = 2; static const int LINK_STATUS_PROP_ID = 5; static const int SUBCONNECTOR_PROP_ID = 69; // int type_prop_id = 0; // metadata, need only collect once static drmModePropertyRes * edid_metadata = NULL; static Enum_Metadata * subconn_metadata; static Enum_Metadata * dpms_metadata = NULL; static Enum_Metadata * link_status_metadata = NULL; #ifdef UNUSED static void free_enum_metadata(Enum_Metadata * meta) { if (meta) { free(meta->name); if (meta->values) { free(meta->values); } free(meta); } } #endif static void dbgrpt_enum_metadata(Enum_Metadata * meta, int depth) { rpt_structure_loc("Enum_Metadata", meta, depth); if (meta) { int d1 = depth+1; rpt_vstring(d1, "Name: %s", meta->name); for (int ndx = 0; ndx < meta->count; ndx++) rpt_vstring(d1, "%2d %s", meta->values[ndx], meta->value_names[ndx]); } } static Enum_Metadata * drmModePropertyRes_to_enum_metadata(drmModePropertyRes * prop) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "prop=%p", prop); assert(prop); Enum_Metadata * meta = calloc(1, sizeof(Enum_Metadata)); meta->name = strdup(prop->name); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "prop->name = %s", prop->name); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "prop->count_enums = %d", prop->count_enums); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "prop->count_values = %d", prop->count_values); meta->count = prop->count_enums; meta->values = calloc(prop->count_enums, sizeof(uint64_t)); meta->value_names = calloc(prop->count_enums, sizeof(char*)); for (int ndx = 0; ndx < meta->count; ndx++) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "prop->enums[%d].name = %s", ndx, prop->enums[ndx].name); meta->values[ndx] = prop->enums[ndx].value; meta->value_names[ndx] = strdup(prop->enums[ndx].name); } DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "Enum_Metadata", dbgrpt_enum_metadata, meta); return meta; } static void free_drm_connector_state(void * cs) { bool debug = false; Drm_Connector_State * cstate = (Drm_Connector_State*) cs; if (cstate) { DBGF(debug, "Freeing Drm_Connector_State at %p", cs); if (cstate->edid) free_parsed_edid(cstate->edid); free(cstate); } } static void store_property_value( int fd, Drm_Connector_State * connector_state, drmModePropertyRes * prop_ptr, uint64_t prop_value) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Starting. fd=%d. connector_state=%p, connector_state->connector_id=%d, prop_ptr=%p, prop_ptr->prop_id=%d, prop_value=%d", fd, connector_state, connector_state->connector_id, prop_ptr, prop_ptr->prop_id, prop_value); int d1 = 1; if (prop_ptr->prop_id == EDID_PROP_ID) { assert( prop_ptr->flags & DRM_MODE_PROP_BLOB); if (!edid_metadata) edid_metadata = prop_ptr; int blob_id = prop_value; drmModePropertyBlobPtr blob_ptr = drmModeGetPropertyBlob(fd, blob_id); if (!blob_ptr) { if (debug) rpt_vstring(d1, "Blob not found"); } else { if (debug) rpt_hex_dump(blob_ptr->data, blob_ptr->length, d1); if (blob_ptr->length >= 128) { connector_state->edid = create_parsed_edid2(blob_ptr->data, "DRM"); } else { rpt_vstring(d1, "invalid edid length: %d", blob_ptr->length); } drmModeFreePropertyBlob(blob_ptr); } } else if (prop_ptr->prop_id == SUBCONNECTOR_PROP_ID) { assert( prop_ptr->flags & DRM_MODE_PROP_ENUM); if (!subconn_metadata) subconn_metadata = drmModePropertyRes_to_enum_metadata(prop_ptr); connector_state->subconnector = prop_value; } else if (prop_ptr->prop_id == DPMS_PROP_ID) { assert( prop_ptr->flags & DRM_MODE_PROP_ENUM); if (!dpms_metadata) dpms_metadata = drmModePropertyRes_to_enum_metadata(prop_ptr); connector_state->dpms = prop_value; } else if (prop_ptr->prop_id == LINK_STATUS_PROP_ID) { assert( prop_ptr->flags & DRM_MODE_PROP_ENUM); if (!link_status_metadata) link_status_metadata = drmModePropertyRes_to_enum_metadata(prop_ptr); connector_state->link_status = prop_value; } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // Returns array of DRM_Connector_State for one card DDCA_Status get_connector_state_array(int fd, int cardno, GPtrArray* collector) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Starting. fd=%d, cardno=%d, collector=%p", fd, cardno, collector); int result = 0; // int depth = 0; int d1 = 1; int d2 = 2; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Retrieving DRM resources..."); drmModeResPtr res = drmModeGetResources(fd); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE,"res=%p", (void*)res); if (!res) { int errsv = errno; rpt_vstring(d1, "Failure retrieving DRM resources, errno=%d=%s", errsv, strerror(errsv)); if (errsv == EINVAL) rpt_vstring(d1,"Driver apparently does not provide needed DRM ioctl calls"); result = -errsv; } else { if (debug) report_drmModeRes(res, d2); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Scanning connectors for card %d ...", cardno); for (int i = 0; i < res->count_connectors; ++i) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "calling drmModeGetConnector for id %d", res->connectors[i]); /* Doc for drmModeGetConnector in xf86drmMode.h: * * Retrieve all information about the connector connectorId. This will do a * forced probe on the connector to retrieve remote information such as EDIDs * from the display device. */ drmModeConnector * conn = drmModeGetConnector(fd, res->connectors[i]); if (!conn) { rpt_vstring(d1, "Cannot retrieve DRM connector id %d errno=%s", res->connectors[i], linux_errno_name(errno)); continue; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "got drmModeConnector conn = %p", conn); if (debug) report_drmModeConnector(fd, conn, d1) ; Drm_Connector_State * connector_state = calloc(1,sizeof(Drm_Connector_State)); connector_state->cardno = cardno; connector_state->connector_id = res->connectors[i]; if (debug) { int depth=2; rpt_structure_loc("drmModeConnector", conn, depth); rpt_vstring(d1, "%-20s %d", "connector_id:", conn->connector_id); rpt_vstring(d1, "%-20s %d - %s", "connector_type:", conn->connector_type, drm_connector_type_name(conn->connector_type)); rpt_vstring(d1, "%-20s %d", "connector_type_id:", conn->connector_type_id); rpt_vstring(d1, "%-20s %d - %s", "connection:", conn->connection, connector_status_name(conn->connection)); } connector_state->connector_type = conn->connector_type;; connector_state->connector_type_id = conn->connector_type_id; connector_state->connection = conn->connection; drmModeConnector * p = conn; if (debug) rpt_vstring(d1, "%-20s %d", "count_props", p->count_props); for (int ndx = 0; ndx < p->count_props; ndx++) { uint64_t curval = p->prop_values[ndx]; // coverity workaround if (debug) { rpt_vstring(d2, "index=%d, property id (props)=%" PRIu32 ", property value (prop_values)=%" PRIu64 , ndx, p->props[ndx], curval); } int id = p->props[ndx]; if (id == EDID_PROP_ID || // 1 id == DPMS_PROP_ID || // 2 id == LINK_STATUS_PROP_ID || // 5 id == SUBCONNECTOR_PROP_ID) // 69 { drmModePropertyPtr metadata_ptr = drmModeGetProperty(fd, p->props[ndx]); if (metadata_ptr) { uint64_t prop_value = p->prop_values[ndx]; if (debug) report_property_value(fd, metadata_ptr, prop_value, d2); store_property_value(fd, connector_state, metadata_ptr, prop_value); drmModeFreeProperty(metadata_ptr); } } } // for DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "calling drmModeFreeConnector(%p)", conn); drmModeFreeConnector(conn); g_ptr_array_add(collector, connector_state); } drmModeFreeResources(res); result = 0; } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } void dbgrpt_connector_state(Drm_Connector_State * state, int depth) { rpt_structure_loc("Drm_Connector_State", state, depth); int d1 = depth+1; int d2 = depth+2; // int d3 = depth+3; rpt_vstring(d1, "%-20s %d", "cardno:", state->cardno); rpt_vstring(d1, "%-20s %d", "connector_id:", state->connector_id); rpt_vstring(d1, "%-20s %d - %s", "connector_type:", state->connector_type, drm_connector_type_name(state->connector_type)); rpt_vstring(d1, "%-20s %d", "connector_type_id:", state->connector_type_id); rpt_vstring(d1, "%-20s %d - %s", "connection:", state->connection, connector_status_name(state->connection)); rpt_vstring(d1, "Properties:"); char * vname = get_enum_value_name(dpms_metadata, state->dpms); rpt_vstring(d2, "dpms: %d - %s", (int) state->dpms, vname); vname = get_enum_value_name(link_status_metadata, state->link_status); rpt_vstring(d2, "link_status: %d - %s", (int) state->link_status, vname); vname = (subconn_metadata) ? get_enum_value_name(subconn_metadata, state->subconnector) : "UNK"; rpt_vstring(d2, "subconnector: %d - %s", (int) state->subconnector, vname); if (state->edid) { // rpt_vstring(d2, "edid:"); // report_parsed_edid(state->edid, true, d3); rpt_vstring(d2, "edid: %s, %s, %s", state->edid->mfg_id, state->edid->model_name, state->edid->serial_ascii); } else { rpt_label(d2,"edid: NULL"); } rpt_nl(); } void dbgrpt_connector_state_basic(Drm_Connector_State * state, int depth) { int d0 = depth; int d1 = depth+1; rpt_vstring(d0, "%-20s %d", "connector id:", state->connector_id); rpt_vstring(d1, "%-17s %s-%d", "connector:", drm_connector_type_name(state->connector_type), state->connector_type_id); rpt_vstring(d1, "%-17s %d - %s", "connection:", state->connection, connector_status_name(state->connection)); char * vname = get_enum_value_name(dpms_metadata, state->dpms); rpt_vstring(d1, "%-17s %d - %s", "dpms", (int) state->dpms, vname); vname = get_enum_value_name(link_status_metadata, state->link_status); rpt_vstring(d1, "%-17s %d - %s", "link-status:", (int) state->link_status, vname); if (state->edid) { rpt_vstring(d1, "%-17s %s, %s, %s", "edid:", state->edid->mfg_id, state->edid->model_name, state->edid->serial_ascii); } else { rpt_vstring(d1,"%-17s %s", "edid:", "NULL"); } rpt_nl(); } void dbgrpt_connector_states(GPtrArray* states) { bool debug = false; assert(states); if (debug) { rpt_label(1, "dpms_metadata:"); dbgrpt_enum_metadata(dpms_metadata, 2); rpt_label(1, "link_status_metadata:"); dbgrpt_enum_metadata(link_status_metadata, 2); rpt_label(1, "subconn_metadata:"); dbgrpt_enum_metadata(subconn_metadata, 2); rpt_nl(); } rpt_structure_loc("GPtrArray", states, 0); for (int ndx = 0; ndx < states->len; ndx++) { Drm_Connector_State * cur = g_ptr_array_index(states, ndx); dbgrpt_connector_state(cur, 1); } } DDCA_Status get_drm_connector_states_by_fd(int fd, int cardno, GPtrArray* collector) { bool debug = false; bool replace_fd = false; bool verbose = false; int result = 0; DBGTRC_STARTING(debug, TRACE_GROUP, "Starting. fd=%d, cardno=%d, collector=%p, replace_busid=%s", fd, cardno, collector, sbool(replace_fd)); // returns null string if open() instead of drmOpen(,busid) was used to to open // uses successive DRM_IOCTL_GET_UNIQUE calls char* busid = drmGetBusid(fd); if (busid) { if (verbose || debug) { rpt_vstring(1, "drmGetBusid() returned: |%s|", busid); } // drmFreeBusid(busid); // requires root free(busid); } else { if (verbose || debug) rpt_vstring(1, "Error calling drmGetBusid(). errno=%s", linux_errno_name(errno)); } if (replace_fd) { busid = get_busid_from_fd(fd); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "get_busid_from_fd() returned: %s", busid); close(fd); fd = drmOpen(NULL, busid); if (fd < 0) { result = -errno; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "drmOpen(NULL, %s) failed. fd=%d, errno=%d - %s", busid, fd, errno, strerror(errno)); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "drmOpen() succeeded"); } } if (fd >= 0) { #ifdef OUT // try to set master int rc = drmSetMaster(fd); // always fails, errno=13, but apparently not needed if (rc < 0 && (verbose || debug)) rpt_vstring(1,"(%s) drmSetMaster() failed, errno = %d - %s", __func__, errno, strerror(errno)); #endif get_connector_state_array(fd, cardno, collector); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } Drm_Connector_State * get_drm_connector_state_by_fd(int fd, int cardno, int connector_id) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Starting. fd=%d, connector_id=%d", fd, connector_id); GPtrArray * connector_state_array = g_ptr_array_new(); g_ptr_array_set_free_func(connector_state_array, free_drm_connector_state); get_drm_connector_states_by_fd(fd, cardno, connector_state_array); // todo report connector_state_array Drm_Connector_State * result = NULL; if (connector_state_array) { for (int ndx = 0; ndx < connector_state_array->len; ndx++) { Drm_Connector_State * cur = g_ptr_array_index(connector_state_array, ndx); if (cur->connector_id == connector_id) { result = cur; // TODO: copy, then free array g_ptr_array_remove_index(connector_state_array, ndx); break; } } g_ptr_array_free(connector_state_array, true); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", result); return result; } /** Extract the card number from a file name of the form ".../cardN". * * @param devname device name * @return card number, or -1 if not found */ int extract_cardno(const char * devname) { int cardno = -1; if (devname) { char * bn = g_path_get_basename(devname); if (!bn || strlen(bn) < 5 || memcmp(bn, "card", 4) != 0 || !g_ascii_isdigit(bn[4]) ) { // rpt_vstring(1, "Invalid device name: %s", devname); } else { cardno = g_ascii_digit_value(bn[4]); } free(bn); } // if (cardno < 0) { // MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Invalid device name: %s", devname); // } return cardno; } #ifdef UNUSED Drm_Connector_State * get_drm_connector_state_by_devname(const char * devname, int connector_id) { // validate that devmame looks like /dev/dri/cardN int cardno = extract_cardno(devname); if (cardno < 0) { rpt_vstring(1, "Invalid device name: %s", devname); return NULL; } int fd = open(devname,O_RDWR | O_CLOEXEC); if (fd < 0) { rpt_vstring(1, "Error opening device %s using open(), errno=%s", devname, linux_errno_name(errno)); return NULL; } return get_drm_connector_state_by_fd(fd, connector_id); } #endif #ifdef UNUSED // replaced by CLOSE_W_ERRMSG() void syslogged_close(int fd) { bool debug = false; DBGF(debug, "fd=%d, filename =%s", fd, filename_for_fd_t(fd)); int rc = close(fd); if (rc < 0) { int errsv = errno; syslog(LOG_ERR, "close() failed for fd=%d=%s. errno=%d", fd, filename_for_fd_t(fd), errsv); } } #endif static DDCA_Status get_drm_connector_states_by_devname( const char * devname, bool verbose, GPtrArray * collector) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Starting. devname=%s, verbose=%s, collector=%p", devname, sbool(verbose), collector); // validate that devmame looks like /dev/dri/cardN DDCA_Status result = 0; int cardno = extract_cardno(devname); if (cardno < 0) { SEVEREMSG("Invalid device name: %s", devname); result = -EINVAL; goto bye; } int fd = open(devname,O_RDWR | O_CLOEXEC); if (fd < 0) { int errsv = errno; SEVEREMSG("Error opening device %s using open(), errno=%s", devname, linux_errno_name(errsv)); result = -errsv; goto bye; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling get_drm_connector_states_by_fd():"); int rc = get_drm_connector_states_by_fd(fd, cardno, collector); if (rc == 0 && (verbose || IS_DBGTRC(debug, DDCA_TRC_NONE))) dbgrpt_connector_states(collector); CLOSE_W_ERRMSG(fd); bye: DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } /** Persistent array of Card_Connector_State records */ GPtrArray* all_card_connector_states = NULL; static GPtrArray * drm_get_all_connector_states() { bool verbose = false; GPtrArray * devnames = get_dri_device_names_using_filesys(); GPtrArray * allstates = g_ptr_array_new(); g_ptr_array_set_free_func(allstates, free_drm_connector_state); for (int ndx = 0; ndx < devnames->len; ndx++) { char * driname = g_ptr_array_index(devnames, ndx); get_drm_connector_states_by_devname(driname, verbose, allstates); } g_ptr_array_free(devnames, true); return allstates; } /** Remove all records from a GPtrArray of #Drm_Connector_State records, * but keep the array. * * @param cstates pointer to GPtrArray */ void empty_drm_connector_states(GPtrArray * cstates) { if (cstates) { g_ptr_array_remove_range(cstates, 0, cstates->len); } } /** Destroy a GPtrArray of #Drm_Connector_State records * * @param cstates pointer to GPtrArray */ void free_drm_connector_states(GPtrArray * cstates) { if (cstates) { g_ptr_array_free(cstates, true); } } /** Repopulate the #all_card_connector_states array. */ void redetect_drm_connector_states() { if (all_card_connector_states) free_drm_connector_states(all_card_connector_states); all_card_connector_states = drm_get_all_connector_states(); } /** Report on the DRM connector states array * * @param bool refresh, if the array currently exists, erase it * and repopulate it * @param depth logical indentation depth * * If #all_card_connector_states is not set on entry to this * function, it is not set on exit. */ void report_drm_connector_states(int depth) { bool debug = false; bool preexisting = true; if (!all_card_connector_states) { DBGF(debug, "all_card_connector_states == NULL, creating array..."); preexisting = false; all_card_connector_states = drm_get_all_connector_states(); } for (int ndx = 0; ndx < all_card_connector_states->len; ndx++) { dbgrpt_connector_state(g_ptr_array_index(all_card_connector_states, ndx), 0); } if (!preexisting) { DBGF(debug, "Freeing all_card_connector_states.."); free_drm_connector_states(all_card_connector_states); all_card_connector_states = NULL; } } /** Provide a simple report on the DRM connector states array * * @param bool refresh, if the array currently exists, erase it * and repopulate it * @param depth logical indentation depth * * If #all_card_connector_states is not set on entry to this * function, it is not set on exit. */ void report_drm_connector_states_basic(bool refresh, int depth) { if (refresh && all_card_connector_states) { free_drm_connector_states(all_card_connector_states); all_card_connector_states = NULL; } bool preexisting = true; if (!all_card_connector_states) { all_card_connector_states = drm_get_all_connector_states(); preexisting = false; } for (int ndx = 0; ndx < all_card_connector_states->len; ndx++) { Drm_Connector_State * cur = g_ptr_array_index(all_card_connector_states, ndx); if (cur->edid || cur->connection == DRM_MODE_CONNECTED ) { dbgrpt_connector_state_basic(cur, 0); } } if (!preexisting) { free_drm_connector_states(all_card_connector_states); all_card_connector_states = NULL; } } // Drm_Connector_Identifier drm_connector_identifier_from_state(Drm_Connector_State cstate); Drm_Connector_State * find_drm_connector_state(Drm_Connector_Identifier cid) { Drm_Connector_State * result = NULL; for (int ndx = 0; ndx < all_card_connector_states->len; ndx++) { Drm_Connector_State * cur = g_ptr_array_index(all_card_connector_states, ndx); if (cur->cardno == cid.cardno) { if (cid.connector_id >= 0) { if (cid.connector_id == cur->connector_id) { result = cur; break; } } else if (cid.connector_type >= 0 && cid.connector_type_id >= 0) { if (cid.connector_type == cur->connector_type && cid.connector_type_id == cur->connector_type_id) { result = cur; break; } } } } return result; } void init_drm_connector_state() { RTTI_ADD_FUNC(drmModePropertyRes_to_enum_metadata); RTTI_ADD_FUNC(store_property_value); RTTI_ADD_FUNC(get_connector_state_array); RTTI_ADD_FUNC(get_drm_connector_states_by_fd); RTTI_ADD_FUNC(get_drm_connector_state_by_fd); RTTI_ADD_FUNC(get_drm_connector_states_by_devname); } ddcutil-2.2.0/src/base/dsa2.c0000644000175000001440000015042414754153540011334 /** @file dsa2.c Dynamic sleep algorithm 2 */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include "util/coredefs.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/error_info.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/timestamp.h" #include "util/xdg_util.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/displays.h" #include "base/i2c_bus_base.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/status_code_mgt.h" #include "base/rtti.h" #include "dsa2.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SLEEP; // These were originally const integer etc., but when building on build.opensuse.com // use of these values causes a "initial element is not constant" error // Apparently sensitive to compiler optimization level, compiler version, -std c99 vs -std c11 // see: https://stackoverflow.com/questions/64058577/initialiser-element-is-not-constant-error-in-c-when-using-static-const-variab #define Default_DSA2_Enabled DEFAULT_ENABLE_DSA2 #define Default_Look_Back 5 #define Default_Initial_Step 7 // 1.0 #define Max_Recent_Values 100 #define Default_Interval 3 #define Default_Greatest_Tries_Upper_Bound 3 #define Default_Average_Tries_Upper_Bound 1.4 #define Default_Greatest_Tries_Lower_Bound 2 #define Default_Average_Tries_Lower_Bound 1.1 #define Default_Step_Floor 0 static bool dsa2_enabled = Default_DSA2_Enabled; int initial_step = Default_Initial_Step; int adjustment_interval = Default_Interval; int target_greatest_tries_upper_bound = Default_Greatest_Tries_Upper_Bound; int target_avg_tries_upper_bound_10 = Default_Average_Tries_Upper_Bound * 10; // multiply by 10 for integer arithmetic int target_greatest_tries_lower_bound = Default_Greatest_Tries_Lower_Bound; int target_avg_tries_lower_bound_10 = Default_Average_Tries_Lower_Bound * 10; int Min_Decrement_Lookback = 5; // lookback must be at least this size for step decrement int global_lookback = Default_Look_Back; int dsa2_step_floor = Default_Step_Floor; bool dsa2_is_enabled() { return dsa2_enabled; } void dsa2_enable(bool yesno) { dsa2_enabled = yesno; } bool dsa2_set_greatest_tries_upper_bound(int tries) { bool result = false; if ( 1 <= tries && tries <= MAX_MAX_TRIES) { // should get actual write/read maxtries target_greatest_tries_upper_bound = tries; result = true; } return result; } bool dsa2_set_average_tries_upper_bound(DDCA_Sleep_Multiplier avg_tries) { bool result = false; if (1.0 <= avg_tries && avg_tries <= MAX_MAX_TRIES) { target_avg_tries_upper_bound_10 = avg_tries * 10; result = true; } return result; } // // Utility Functions // #ifdef UNUSED int dpath_busno(DDCA_IO_Path dpath) { assert(dpath.io_mode == DDCA_IO_I2C); return dpath.path.i2c_busno; } #endif // // Successful Invocation Struct // typedef struct { time_t epoch_seconds; // timestamp to aid in development int tryct; // how many tries int required_step; // step level of successful invocation } Successful_Invocation; /** Returns a string representation of #Successful_Invocation instance. * The value is valid until the next call to this function in the * current thread. * * @param value of #Successful_Invocation (not a pointer) * @return string representation */ char * si_repr_t(Successful_Invocation si) { static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&buf_key, 40); g_snprintf(buf, 40, "{%2d,%2d,%s}", si.tryct, si.required_step, formatted_epoch_time_t(si.epoch_seconds)); return buf; } // // Circular_Invocation_Result_Buffer // typedef struct { Successful_Invocation * values; int size; // size of values[] int ct; // number of values used: 0..size int nextpos; // index to next write to } Circular_Invocation_Result_Buffer; /** Allocates a new #Circular_Invocation_Result_Buffer of * #Successful_Invocation structs * * @param size buffer size (number of entries) * @return newly allocated #Circular_Integer_Buffer */ static Circular_Invocation_Result_Buffer * cirb_new(int size) { Circular_Invocation_Result_Buffer * cirb = calloc(1, sizeof(Circular_Invocation_Result_Buffer)); cirb->values = calloc(size, sizeof(Successful_Invocation)); cirb->size = size; cirb->ct = 0; cirb->nextpos = 0; return cirb; } /** Frees a #Circular_Invocation_Result_Buffer * * @param cirb pointer to buffer */ static void cirb_free(Circular_Invocation_Result_Buffer * cirb) { free(cirb->values); free(cirb); } /** Appends a #Successful_Invocation struct to a #Circular_Invocation_Result_Buffer. * * @param cirb pointer to #Circular_Integer_Buffer * @param value value to append */ static void cirb_add(Circular_Invocation_Result_Buffer* cirb, Successful_Invocation value) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "cirb=%p, cirb->nextpos=%2d, cirb->ct=%2d, value=%s", cirb, cirb->nextpos, cirb->ct, si_repr_t(value)); cirb->values[cirb->nextpos] = value; cirb->nextpos = (cirb->nextpos+1) % cirb->size; if (cirb->ct < cirb->size) cirb->ct++; DBGTRC_DONE(debug, DDCA_TRC_NONE, "cirb=%p, cirb->nextpos=%2d, cirb->ct=%2d", cirb, cirb->nextpos, cirb->ct); } /** Given a logical index into a #Circular_Invocation_Result_Buffer returns the * physical index. * * @param cirb pointer to a #Circular_Invocation_Result_Buffer * @param logical logical index, 0 for the oldest entry in the buffer * @return physical physical index, -1 if < 0 or logical exceeds the number of * values in the buffer */ static int cirb_logical_to_physical_index(Circular_Invocation_Result_Buffer *cirb, int logical) { bool debug = false; int physical = -1; if (logical < cirb->ct) { physical = (cirb->ct < cirb->size) ? logical : (cirb->nextpos +logical) % cirb->size; } DBGTRC(debug, DDCA_TRC_NONE, "Executing logical=%2d, cirb->ct=%2d, cirb->size=%2d, cirb->nextpos=%2d, Returning: physical=%2d", logical, cirb->ct, cirb->size, cirb->nextpos, physical); return physical; } /** Returns the #Successful_Invocation value at the specified logical index * in a #Circular_Invocation_Result_Buffer. * * @param cirb pointer to a #Circular_Invocation_Result_Buffer * @param logical logical index, 0 based * @return #Successful_Invocation_Result value, {-1, -1, 0} if not found */ static Successful_Invocation cirb_get_logical(Circular_Invocation_Result_Buffer *cirb, int logical) { int physical = cirb_logical_to_physical_index(cirb, logical); Successful_Invocation result = {-1,-1,0}; if (physical >= 0) result = cirb->values[physical]; return result; } /** Returns an array of the most recent values in a #Circular_Invocation_Result_Buffer. * * @param cirb pointer to a #Circular_Invocation_Result_Buffer * @param ct number of values to retrieve, if < 0 retrieve all * @param latest_values[] pointer to suitably sized buffer in which to * return values */ static int cirb_get_latest(Circular_Invocation_Result_Buffer * cirb, int ct, Successful_Invocation latest_values[]) { if (ct < 0) ct = cirb->ct; int skipct = 0; if (ct <= cirb->ct) skipct = cirb->ct - ct; if (ct > cirb->ct) ct = cirb->ct; for (int ctr = 0; ctr < ct; ctr++) { latest_values[ctr] = cirb_get_logical(cirb, ctr+skipct); } return ct; } /** Output a debugging report of a #Circular_Invocation_Result_Buffer * * @param cirb pointer to buffer * @param depth logical indentation depth */ static void dbgrpt_circular_invocation_results_buffer(Circular_Invocation_Result_Buffer * cirb, int depth) { int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("Circular_Invocation_Result_Buffer", cirb, depth); rpt_int("size", NULL, cirb->size, d1); rpt_int("ct", NULL, cirb->ct, d1); rpt_label(d1, "Buffer contents:"); for (int ndx = 0; ndx < MIN(cirb->size, cirb->ct); ndx++) { rpt_vstring(d2, "values[%2d]: tryct = %d, required_step=%d, timestamp=%s", ndx, cirb->values[ndx].tryct, cirb->values[ndx].required_step, formatted_epoch_time_t(cirb->values[ndx].epoch_seconds)); } rpt_label(d1, "Values by latest: "); for (int ndx = 0; ndx < cirb->ct; ndx++) { int physical = cirb_logical_to_physical_index(cirb, ndx); Successful_Invocation si = cirb_get_logical(cirb, ndx); rpt_vstring(d2, "logical index: %2d, physical index: %2d, tryct = %d, required_step=%d, timestamp=%s", ndx, physical, si.tryct, si.required_step, formatted_epoch_time_t(si.epoch_seconds)); } } // // Results Tables // static int steps[] = {0, 5, 10, 20, 30, 50, 70, 100, 130, 160, 200}; // multiplier * 100 static int absolute_step_ct = ARRAY_SIZE(steps); // 11 static int step_last = ARRAY_SIZE(steps)-1; // 10 static int adjusted_step_ct = ARRAY_SIZE(steps)-1; // will be reset to absolute_step_ct - dsa2_step_floor #define RTABLE_FROM_CACHE 0x01 #define RTABLE_BUS_DETECTED 0x02 #define RTABLE_EDID_VERIFIED 0x04 Value_Name_Table rtable_status_flags_table = { VN(RTABLE_FROM_CACHE), VN(RTABLE_BUS_DETECTED), VN(RTABLE_EDID_VERIFIED), VN_END }; static int Target_Max_Tries = 3; typedef struct Results_Table { Circular_Invocation_Result_Buffer * recent_values; // use int rather than a smaller type to simplify use of str_to_int() int busno; int cur_step; int remaining_interval; int cur_retry_loop_step; int cur_retry_loop_null_msg_ct; int initial_step; int initial_lookback; int cur_lookback; int adjustments_up; int total_steps_up; int adjustments_down; int total_steps_down; int successful_try_ct; int retryable_failure_ct; int highest_step_complete_loop_failure; int null_msg_max_step_for_success; int reset_ct; int latest_avg_tryct_10; Byte edid_checksum_byte; Byte state; // RTABLE_ flags // format 1 // bool found_failure_step; // int lookback; } Results_Table; static Results_Table ** results_tables; /** Output a debugging report for a #Results_Table * * @param rtable pointer to table instance * @param depth logical indentation depth */ static void dbgrpt_results_table(Results_Table * rtable, int depth) { int d1 = depth+1; rpt_structure_loc("Results_Table", rtable, depth); #define ONE_INT_FIELD(_name) rpt_int(#_name, NULL, rtable->_name, d1) ONE_INT_FIELD(busno); ONE_INT_FIELD(cur_step); ONE_INT_FIELD(cur_lookback); ONE_INT_FIELD(remaining_interval); // ONE_INT_FIELD(min_ok_step); // rpt_bool("found_failure_step", NULL, rtable->found_failure_step, d1); ONE_INT_FIELD(cur_retry_loop_step); ONE_INT_FIELD(cur_retry_loop_null_msg_ct); ONE_INT_FIELD(initial_step); // rpt_bool("initial_step_from_cache", NULL, rtable->initial_step_from_cache, d1); ONE_INT_FIELD(adjustments_up); ONE_INT_FIELD(total_steps_up); ONE_INT_FIELD(adjustments_down); ONE_INT_FIELD(total_steps_down); ONE_INT_FIELD(successful_try_ct); ONE_INT_FIELD(retryable_failure_ct); ONE_INT_FIELD(initial_lookback); ONE_INT_FIELD(highest_step_complete_loop_failure); ONE_INT_FIELD(null_msg_max_step_for_success); ONE_INT_FIELD(latest_avg_tryct_10); rpt_vstring(d1, "edid_checksum_byte 0x%02x", rtable->edid_checksum_byte); rpt_vstring(d1, "state %s", VN_INTERPRET_FLAGS_T(rtable->state, rtable_status_flags_table, "|")); #undef ONE_INT_FIELD dbgrpt_circular_invocation_results_buffer(rtable->recent_values, d1); } /** Allocates a new #Results_Table * * @param busno I2C bus number * @return pointer to newly allocated #Results_Table */ static Results_Table * new_results_table(int busno) { Results_Table * rtable = calloc(1, sizeof(Results_Table)); rtable->busno = busno; rtable->initial_step = initial_step; rtable->cur_step = initial_step; rtable->cur_lookback = global_lookback; rtable->recent_values = cirb_new(Max_Recent_Values); rtable->remaining_interval = Default_Interval; // rtable->min_ok_step = 0; // rtable->found_failure_step = false; rtable->state = 0x00; rtable->initial_lookback = rtable->cur_lookback; rtable->highest_step_complete_loop_failure = -1; rtable->null_msg_max_step_for_success = -1; return rtable; } // static Byte get_edid_checkbyte(int busno) { bool debug = false; I2C_Bus_Info * bus_info = i2c_find_bus_info_by_busno(busno); if (!bus_info) SEVEREMSG("i2c_find_bus_info_by_busno(%d) failed!", busno); assert(bus_info); Byte checkbyte = bus_info->edid->bytes[127]; DBGTRC_EXECUTED(debug, TRACE_GROUP, "busno=%d, returning 0x%02x", busno, checkbyte); return checkbyte; } /** Frees a #Results_Table * * @param rtable pointer to table instance to free */ static void free_results_table(Results_Table * rtable) { if (rtable) { if (rtable->recent_values) cirb_free(rtable->recent_values); free(rtable); } } void dsa2_reset_results_table(int busno, DDCA_Sleep_Multiplier sleep_multiplier) { // bool debug = false; Results_Table * rtable = results_tables[busno]; if (rtable) { free_results_table(rtable); } rtable = new_results_table(busno); results_tables[busno] = rtable; int initial_step = (sleep_multiplier >= 0) ? dsa2_multiplier_to_step(sleep_multiplier) : dsa2_multiplier_to_step(1.0f); // DBGTRC_EXECUTED(debug, DDCA_TRC_NONE, "sleep_multiplier=%4.2f, initial_step=%d, step_last=%d"); rtable->initial_step = initial_step; rtable->cur_step = initial_step; rtable->cur_retry_loop_step = initial_step; rtable->state = RTABLE_BUS_DETECTED; rtable->edid_checksum_byte = get_edid_checkbyte(busno); rtable->adjustments_down = 0; rtable->adjustments_up = 0; rtable->total_steps_up = 0; rtable->total_steps_down = 0; rtable->successful_try_ct = 0; rtable->retryable_failure_ct = 0; } /** Returns the #Results_Table for an I2C bus number * * @param bus number * @return pointer to #Results_Table (may be newly created) */ Results_Table * dsa2_get_results_table_by_busno(int busno, bool create_if_not_found) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, create_if_not_found=%s", busno, sbool(create_if_not_found)); assert(busno <= I2C_BUS_MAX); Results_Table * rtable = results_tables[busno]; if (rtable) { rtable->state |= RTABLE_BUS_DETECTED; if ( (rtable->state & RTABLE_FROM_CACHE) && !(rtable->state & RTABLE_EDID_VERIFIED)) { if (get_edid_checkbyte(busno) != rtable->edid_checksum_byte) { LOGABLE_MSG(DDCA_SYSLOG_NOTICE, "Discarding cached sleep adjustment data for bus /dev/i2c-%d. EDID has changed.", busno); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "EDID verification failed. busno=%d", busno); free_results_table(rtable); results_tables[busno] = NULL; rtable = NULL; } else { rtable->state |= RTABLE_EDID_VERIFIED; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "EDID verification succeeded"); } } } if (!rtable && create_if_not_found) { rtable = new_results_table(busno); results_tables[busno] = rtable; rtable->cur_step = initial_step; rtable->cur_retry_loop_step = initial_step; rtable->state = RTABLE_BUS_DETECTED; rtable->edid_checksum_byte = get_edid_checkbyte(busno); } DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "Results_Table", dbgrpt_results_table, rtable); return rtable; } #ifdef UNUSED // static void set_multiplier(Results_Table * rtable, Sleep_Multiplier multiplier) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "multiplier=%7.3f", multiplier); rtable->cur_step = dsa2_multiplier_to_step(multiplier); DBGTRC_DONE(debug, TRACE_GROUP, "Set cur_step=%d", initial_step); } void dsa2_set_multiplier_by_path(DDCA_IO_Path dpath, Sleep_Multiplier multiplier) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dpath=%s, multiplier=%7.3f", dpath_repr_t(&dpath), multiplier); Results_Table * rtable = dsa2_get_results_table_by_busno(dpath_busno(dpath)); rtable->cur_step = dsa2_multiplier_to_step(multiplier); DBGTRC_DONE(debug, TRACE_GROUP, "Set cur_step=%d", initial_step); } #endif /** Given a floating point multiplier value, return the index of the step * with the greatest value less than the value specified. * * @param multiplier floating point multiplier value * @return step index * * @remark * Relies on fact that IEEE floating point variables with whole integer values * convert to correct integer variables. */ int dsa2_multiplier_to_step(DDCA_Sleep_Multiplier multiplier) { bool debug = false; int imult = multiplier * 100; int ndx = dsa2_step_floor; for (; ndx <= step_last ; ndx++) { if ( steps[ndx] >= imult ) break; } int step = (ndx > step_last) ? step_last : ndx; DBGTRC_EXECUTED(debug, TRACE_GROUP, "multiplier = %5.2f, imult = %d, step_last=%d, ndx=%d, step=%d, steps[%d]=%d, returning step=%d", multiplier, imult, step_last, ndx, step, step,steps[step], step); return step; } #ifdef TEST void test_float_to_step_conversion() { for (int ndx = 0; ndx < adjusted_step_ct; ndx++) { DDCA_Sleep_Multiplier f = steps[ndx] / 100.0; int found_ndx = dsa2_multiplier_to_step(f); printf("ndx=%2d, steps[ndx]=%d, f=%2.5f, found_ndx=%d\n", ndx, steps[ndx], f, found_ndx); assert(found_ndx == ndx); } } #endif /** Sets the global initial_step value used for new #Results_Table records * and also resets the cur_step and related values in each existing * #Results_Table. * * @param multiplier sleep multiplier value */ void dsa2_reset_multiplier(DDCA_Sleep_Multiplier multiplier) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "multiplier=%5.2f", multiplier); initial_step = dsa2_multiplier_to_step(multiplier); for (int ndx = 0; ndx < I2C_BUS_MAX; ndx++) { if (results_tables[ndx]) { Results_Table * rtable = results_tables[ndx]; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Processing Results_Table for /dev/i2c-%d", rtable->busno); rtable->cur_step = initial_step; // rtable->found_failure_step = false; // rtable->min_ok_step = 0; rtable->cur_retry_loop_step = initial_step; rtable->adjustments_down = 0; rtable->adjustments_up = 0; rtable->total_steps_up = 0; rtable->total_steps_down = 0; rtable->successful_try_ct = 0; rtable->retryable_failure_ct = 0; } } DBGTRC_DONE(debug, TRACE_GROUP, "Set initial_step=%d", initial_step); } // // The Algorithm // /** Encapsulates the algorithm used by #adjust_for_rcnt_successes() to * determine if recent Successful_Invocation buffer statistics indicate * that the multiplier currently supplied by the dsa2 subsystem should * be increased. * * @param highest_tryct highest try count for any Successful_Invocation record * @param total_tryct total number of tries reported * @param interval number of Successful_Invocation records examined * @return true if cur_step needs to be increased, false if not */ static bool dsa2_too_many_errors(int most_recent_tryct, int highest_tryct, int total_tryct, int interval) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "most_recent_tryct=%d, highest_tryct=%d, total_tryct=%d, interval=%d", most_recent_tryct, highest_tryct, total_tryct, interval); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "target_greatest_tries_upper_bound=%d, target_avg_tries_upper_bound_10=%d, Target_Max_Tries=%d", target_greatest_tries_upper_bound, target_avg_tries_upper_bound_10, Target_Max_Tries); int computed_avg_10 = (total_tryct * 10)/interval; bool result = ( most_recent_tryct > Target_Max_Tries || highest_tryct > target_greatest_tries_upper_bound || computed_avg_10 > target_avg_tries_upper_bound_10); // i.e. total_tryct/interval > 1.4) DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, "computed_avg_10=%d", computed_avg_10); return result; } // #ifdef PERHAPS_FUTURE static bool dsa2_too_few_errors(int highest_tryct, int total_tryct, int interval) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "target_greatest_tries_lower_bound=%d, target_avg_tries_lower_bound_10=%d, highest_tryct=%d, total_tryct=%d, interval=%d", target_greatest_tries_lower_bound, target_avg_tries_lower_bound_10, highest_tryct, total_tryct, interval); int computed_avg_10 = (total_tryct * 10)/interval; bool result = (highest_tryct <= target_greatest_tries_lower_bound && computed_avg_10 <= target_avg_tries_lower_bound_10); DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, "computed_avg_10=%d", computed_avg_10); return result; } // #endif /** Calculates the step to be used on the next try loop iteration after a * retryable loop failure. The step number may be incremented some amount * based on the number of tries remaining. * * If remaining_tries == 0, there's no next_step that's possible. * Return prev_step in this degenerate case. * * @param prev_step number of the step that failed * @param remaining_tries number of tries remaining * @return step number to be used for next try loop iteration */ int dsa2_next_retry_step(int prev_step, int remaining_tries) { bool debug = false; int next_step = prev_step; if (remaining_tries > 0) { // handle maxtries failure int remaining_steps = step_last - prev_step; DDCA_Sleep_Multiplier fadj = (1.0*remaining_steps)/remaining_tries; // don't wait until last try to hit max step if (remaining_tries > 2) fadj = (1.0*remaining_steps) / (remaining_tries-2); if (remaining_tries > 1) fadj = (1.0*remaining_steps) / (remaining_tries-1); DDCA_Sleep_Multiplier fadj2 = fadj; if (fadj > .75 && fadj < 1.0) fadj2 = 1.0; int adjustment = fadj2; next_step = prev_step + adjustment; if (next_step > step_last) next_step = step_last; DBGTRC_EXECUTED(debug, TRACE_GROUP, "Executing prev_step=%d, remaining_tries=%d, remaining_steps=%d, fadj=%2.3f, fadj2=%2.3f, adjustment=%d, returning %d", prev_step, remaining_tries, remaining_steps, fadj, fadj2, adjustment, next_step); } else { DBGTRC_EXECUTED(debug, TRACE_GROUP, "remaining_tries == 0, returning next_step = prev_step = %d", next_step); } return next_step; } #ifdef TESTING void test_dsa2_next_retry_step() { for (int max_tries = 5; max_tries <= 5; max_tries++) { for (int initial_step = 0; initial_step <= step_last; initial_step++) { int cur_step = initial_step; int tryctr = 1; while (tryctr < max_tries) { printf("max_tries=%2d, initial_step=%2d, tryctr=%2d, cur_step=%2d\n", max_tries, initial_step, tryctr, cur_step); cur_step = dsa2_next_retry_step(cur_step, max_tries-tryctr); tryctr++; } printf("\n"); } printf("=============================================\n"); } } #endif /** This function is called periodically to possibly adjust the cur_step value * for a device either up or down based on recent successful execution data * recorded in the circular successful invocation structure. * * @param rtable pointer to #Results_Table to examine * @return updated cur_step */ static int dsa2_adjust_for_rcnt_successes(Results_Table * rtable) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, rtable=%p", rtable->busno, rtable); int next_step = rtable->cur_step; // n. called only if most recent try was a success Successful_Invocation latest_values[Max_Recent_Values]; int actual_lookback = cirb_get_latest( rtable->recent_values, 10, // rtable->lookback, latest_values); assert(actual_lookback > 0); int max_tryct = 0; int min_tryct = 99; int total_tryct = 0; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "actual_lookback=%d", actual_lookback); for (int ndx = 0; ndx < actual_lookback; ndx++) { total_tryct += latest_values[ndx].tryct; if (latest_values[ndx].tryct > max_tryct) max_tryct = latest_values[ndx].tryct; if (latest_values[ndx].tryct < min_tryct) min_tryct = latest_values[ndx].tryct; } int last_value_pos = actual_lookback - 1; int most_recent_step = latest_values[last_value_pos].required_step; int most_recent_tryct = latest_values[last_value_pos].tryct; #ifdef OLD char b[900]; b[0] = '\0'; if ( IS_DBGTRC(debug, DDCA_TRC_NONE) ) { for (int ndx = 0; ndx < actual_lookback; ndx++) { g_snprintf(b + strlen(b), 900-strlen(b), "%s{tryct:%d,reqd step:%d,%ld}", (ndx > 0) ? ", " : "", latest_values[ndx].tryct, latest_values[ndx].required_step, latest_values[ndx].epoch_seconds); } } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, actual_lookback = %d, latest_values:%s", rtable->busno, actual_lookback, b); #endif if ( IS_DBGTRC(debug, DDCA_TRC_NONE) ) { GPtrArray * svals = g_ptr_array_new_with_free_func(g_free); for (int ndx = 0; ndx < actual_lookback; ndx++) { char * s = g_strdup_printf("{tryct:%d,reqd step:%d,%jd}", latest_values[ndx].tryct, latest_values[ndx].required_step, (intmax_t)latest_values[ndx].epoch_seconds); g_ptr_array_add(svals, s); } DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "busno=%d, actual_lookback = %d, latest_values:%s", rtable->busno, actual_lookback, join_string_g_ptr_array_t(svals, ", ") ); g_ptr_array_free(svals, true); } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "max_tryct = %d, min_tryct = %d, total_tryct = %d, most_recent_step=%d", max_tryct, min_tryct, total_tryct, most_recent_step); // show_backtrace(0); if (most_recent_step > step_last) { DBGMSG("most_recent_step=%d, step_last=%d", most_recent_step, step_last); show_backtrace(0); } assert(most_recent_step <= step_last); rtable->latest_avg_tryct_10 = (total_tryct*10)/actual_lookback; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "latest_avg_tryct = %4.1f", rtable->latest_avg_tryct_10/10.0); if (dsa2_too_many_errors(most_recent_tryct, max_tryct, total_tryct, actual_lookback) && rtable->cur_step < most_recent_step // && rtable->cur_step < step_last // redundant ) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "latest_avg_tryct = %4.1f", rtable->latest_avg_tryct_10/10.0); if (next_step < step_last) { next_step = rtable->cur_step++; rtable->total_steps_up++; rtable->adjustments_up++; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, Incremented cur_step. New value: %d", rtable->busno, rtable->cur_step); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Not inccrementing cur_step above step_last=%d", step_last); } } else if (actual_lookback >= Min_Decrement_Lookback && dsa2_too_few_errors(max_tryct, total_tryct, actual_lookback) && rtable->cur_step > 0) { int floor = MIN(rtable->null_msg_max_step_for_success, 3); // is this a good number? if (next_step > floor) { next_step = rtable->cur_step - 1; rtable->total_steps_down++; rtable->adjustments_down++; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, Decremented cur_step. New value: %d", rtable->busno, rtable->cur_step); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Not decrementing cur_step below floor=%d", floor); } rtable->cur_lookback = actual_lookback; } assert(next_step <= step_last); DBGTRC_DONE(debug, TRACE_GROUP, "busno=%d, max_tryct=%d, total_tryct=%d, rtable->cur_step=%d, returning: %d", rtable->busno, max_tryct, total_tryct, rtable->cur_step, next_step); return next_step; } /** Called at the bottom of each try loop that fails in #ddc_read_write_with_retry(). * * Based on the number of tries remaining, may increment the retry_loop_step * for the next step execution in the current loop. * * @param rtable Results_Table for device * @param ddcrc status code * @param remaining_tries number of tries remaining */ void dsa2_note_retryable_failure(Results_Table * rtable, DDCA_Status ddcrc, int remaining_tries) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, rtable=%p, ddcrc=%s, remaining_tries=%d, dsa2_enabled=%s", rtable->busno, rtable, psc_name(ddcrc), remaining_tries, sbool(dsa2_enabled)); assert(rtable); rtable->retryable_failure_ct++; if (ddcrc == DDCRC_NULL_RESPONSE) { rtable->cur_retry_loop_null_msg_ct++; } int prev_step = rtable->cur_retry_loop_step; // has special handling for case of remaining_tries = 0: int next_step = dsa2_next_retry_step(prev_step, remaining_tries); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dsa2_next_retry_step(%d,%d) returned %d", prev_step, remaining_tries, next_step); rtable->cur_retry_loop_step = next_step; DBGTRC_DONE(debug, TRACE_GROUP, "busno=%d, previous step=%d, next step = %d", rtable->busno, prev_step, rtable->cur_retry_loop_step); } /** Called after all (possible) retries in #ddc_write_read_with_retry() * * If ddcrc = 0 (i.e. the operation succeeded, which is the normal case) * a #Successful_Invocation record is added to the Circular Invocation * Response buffer. The results table for the bus is updated. * Depending on how many tries were required, the current step * may be adjusted up or down. The cur_retry_loop_step is reset to the * (possibly updated) cur_loop_step, ready to be used on the next * #ddc_write_read_with_retry() operation. * * If ddcrc != 0 (the operation failed, either because of a fatal error * or retries exhausted) it's not clear what to do. Currently just * cur_retry_loop_step is set to the global initial_step. * * @param rtable #Results_Table for device * @param ddcrc #ddc_write_read_with_retry() return code * @param tries number of tries used, always < max tries for success, * always max tries for retries exhausted, and either * in case of a fatal error of some sort */ void dsa2_record_final( Results_Table * rtable, DDCA_Status ddcrc, int tries, bool cur_loop_null_adjustment_occurred) { bool debug = false; assert(rtable); DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, rtable=%p, ddcrc=%s, tries=%d dsa2_enabled=%s," " cur_loop_null_adjustment_occurred=%s", rtable->busno, rtable, psc_desc(ddcrc), tries, sbool(dsa2_enabled), sbool(cur_loop_null_adjustment_occurred)); if (!dsa2_enabled) { DBGTRC_DONE(debug, TRACE_GROUP, "dsa2 not enabled"); return; } if (cur_loop_null_adjustment_occurred) rtable->null_msg_max_step_for_success = MAX(rtable->null_msg_max_step_for_success, rtable->cur_retry_loop_step); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "cur_step=%d, cur_retry_loop_step=%d, " "cur_retry_loop_null_msg_ct=%d, null_msg_max_step_for_success=%d", rtable->cur_step, rtable->cur_retry_loop_step, rtable->cur_retry_loop_null_msg_ct, rtable->null_msg_max_step_for_success); assert(rtable->cur_retry_loop_step <= step_last); assert(rtable->cur_step <= rtable->cur_retry_loop_step); int next_cur_step = rtable->cur_step; if (ddcrc == 0) { rtable->successful_try_ct++; Successful_Invocation si = {time(NULL), tries, rtable->cur_retry_loop_step}; cirb_add(rtable->recent_values, si); if (rtable->cur_retry_loop_null_msg_ct > 0) { next_cur_step = MIN(rtable->cur_retry_loop_step+1, step_last); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, Incremented cur_step for null_msg_ct=%d. New value: %d", rtable->busno, rtable->cur_retry_loop_null_msg_ct, next_cur_step); } else if (tries > Target_Max_Tries){ // 4 // Too many tries. Unconditionally increase rtable->cur_step next_cur_step = MIN(rtable->cur_retry_loop_step+1, step_last); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, Incremented cur_step for tries > 4. New value: %d", rtable->busno, next_cur_step); } else if (tries > 2) { rtable->remaining_interval -= 1; if (rtable->remaining_interval == 0) { next_cur_step = dsa2_adjust_for_rcnt_successes(rtable); rtable->remaining_interval = adjustment_interval; } } else { next_cur_step = dsa2_adjust_for_rcnt_successes(rtable); rtable->remaining_interval = adjustment_interval; } } else { // ddcrc != 0 if (ddcrc != DDCRC_ALL_RESPONSES_NULL) { // may mean unsupported rtable->highest_step_complete_loop_failure = MAX(rtable->highest_step_complete_loop_failure, rtable->cur_retry_loop_step); next_cur_step = MIN(rtable->cur_retry_loop_step+1, step_last); } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "all tries failed. busno=%d, New cur_step: %d", rtable->busno, next_cur_step); rtable->remaining_interval = adjustment_interval; } if (next_cur_step < dsa2_step_floor) next_cur_step = dsa2_step_floor; else if (next_cur_step > step_last) next_cur_step = step_last; int delta = next_cur_step - rtable->cur_step; if (delta < 0) { rtable->adjustments_down++; rtable->total_steps_down -= delta; } else if (delta > 0) { rtable->adjustments_up++; rtable->total_steps_up = rtable->total_steps_up + delta; } rtable->cur_step = next_cur_step; rtable->cur_retry_loop_step = rtable->cur_step; // for next read_write_with_retry() operation rtable->cur_retry_loop_null_msg_ct = 0; DBGTRC_DONE(debug, TRACE_GROUP, "busno=%d, cur_step=%d, cur_retry_loop_step=%d, remaining_interval=%d", rtable->busno, rtable->cur_step, rtable->cur_retry_loop_step, rtable->remaining_interval); } DDCA_Sleep_Multiplier dsa2_step_to_multiplier(int step) { bool debug = false; DDCA_Sleep_Multiplier result = 1.0f; assert(step >= 0 && step <= step_last); result = steps[step]/100.0; DBGTRC_EXECUTED(debug, TRACE_GROUP, "step=%d, Returning: %.2f", step, result); return result; } DDCA_Sleep_Multiplier dsa2_get_minimum_multiplier() { return dsa2_step_to_multiplier(dsa2_step_floor); } /** Gets the current sleep multiplier value for a device * * Converts the internal step number for the current retry loop * to a floating point value. * * @param rtable #Results_Table for device * @return multiplier value */ DDCA_Sleep_Multiplier dsa2_get_adjusted_sleep_mult(Results_Table * rtable) { bool debug = false; DDCA_Sleep_Multiplier result = 1.0f; assert(rtable); result = steps[rtable->cur_retry_loop_step]/100.0; DBGTRC_EXECUTED(debug, TRACE_GROUP, "busno=%d, rtable=%p, rtable->cur_retry_loop_step=%d, Returning: %.2f", rtable->busno, rtable, rtable->cur_retry_loop_step, result); // show_backtrace(0); return result; } /** Reports internal statistics on the dsa2 algorithm. * * @param rtable pointer to #Results_Table * @param depth logical indentation */ void dsa2_report_internal(Results_Table * rtable, int depth) { int d1 = depth+1; rpt_vstring(depth, "Dynamic sleep algorithm 2 data for /dev/i2c-%d:", rtable->busno); rpt_vstring(d1, "Initial Step: %3d, multiplier = %4.2f", rtable->initial_step, steps[rtable->initial_step]/100.0); // rpt_vstring(d1, "Initial step from cache: %s", sbool(rtable->initial_step_from_cache)); rpt_vstring(d1, "Final Step: %3d, multiplier = %4.2f", rtable->cur_step, steps[rtable->cur_step]/100.0); rpt_vstring(d1, "Initial lookback ct:%3d", rtable->initial_lookback); rpt_vstring(d1, "absolute_step_ct: %3d", absolute_step_ct); rpt_vstring(d1, "dsa2_step_floor %3d", dsa2_step_floor); rpt_vstring(d1, "step_last: %3d", step_last); rpt_vstring(d1, "Final lookback ct: %3d", rtable->cur_lookback); rpt_vstring(d1, "Adjustment interval:%3d", adjustment_interval); rpt_vstring(d1, "Adjustments up: %3d", rtable->adjustments_up); rpt_vstring(d1, "Total steps up: %3d", rtable->total_steps_up); rpt_vstring(d1, "Adjustments down: %3d", rtable->adjustments_down); rpt_vstring(d1, "Total steps down: %3d", rtable->total_steps_down); rpt_vstring(d1, "Successes: %3d", rtable->successful_try_ct); rpt_vstring(d1, "Retryable Failures: %3d", rtable->retryable_failure_ct); rpt_vstring(d1, "Latest avg tryct: %4.1f", rtable->latest_avg_tryct_10/10.0); } #ifdef UNUSED void dsa2_report_internal_all(int depth) { int d1 = depth+1; rpt_label(depth, "Dynamic Sleep Adjustment (algorithm 2)"); for (int busno = 0; busno <= I2C_BUS_MAX; busno++) { Results_Table * rtable = dsa2_get_results_table_by_busno(busno, false); if (rtable) dsa2_report_internal(rtable, d1); } } #endif // // Persistent Statistics // /** Returns the name of the file in directory $HOME/.cache/ddcutil that stores * dynamic sleep stats * * @return fully qualified name of file, NULL if $HOME is not defined * * Caller is responsible for freeing returned value */ char * dsa2_stats_cache_file_name() { return xdg_cache_home_file("ddcutil", DSA_CACHE_FILENAME); } bool dsa2_is_from_cache(Results_Table * rtable) { assert(rtable); // return (rtable && rtable->initial_step_from_cache); return (rtable && (rtable->state & RTABLE_FROM_CACHE)); } /** Saves the current performance statistics in file ddcutil/stats * within the user's XDG cache directory, typically $HOME/.cache. * * @retval 0 success * @return -errno if unable to open the stats file for writing */ Status_Errno dsa2_save_persistent_stats() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); int result = 0; int results_tables_ct = 0; char * stats_fn = dsa2_stats_cache_file_name(); if (!stats_fn) { result = -ENOENT; // SEVEREMSG("Unable to determine dynamic sleep cache file name"); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Unable to determine dynamic sleep cache file name"); goto bye; } FILE * stats_file = NULL; result = fopen_mkdir(stats_fn, "w", ferr(), &stats_file); if (!stats_file) { result = -errno; // SEVEREMSG("Error opening %s: %s", stats_fn, strerror(errno)); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Error opening %s: %s", stats_fn, strerror(errno)); goto bye; } // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Opened %s", stats_fn); for (int ndx = 0; ndx < I2C_BUS_MAX; ndx++) { if (results_tables[ndx] && (results_tables[ndx]->state & RTABLE_BUS_DETECTED)) results_tables_ct++; } DBGTRC(debug, TRACE_GROUP, "results_tables_ct = %d", results_tables_ct); int format_id = 2; fprintf(stats_file, "FORMAT %d\n", format_id); fprintf(stats_file, "* DEV /dev/i2c device\n"); fprintf(stats_file, "* EC EDID check sum byte\n"); fprintf(stats_file, "* C current step\n"); #ifdef OLD if (format_id == 1) { fprintf(stats_file, "* L lookback\n"); fprintf(stats_file, "* I interval remaining\n"); fprintf(stats_file, "* M minimum ok step\n"); fprintf(stats_file, "* F found failure step\n"); fprintf(stats_file, "* Values {epoch_seconds, try_ct, required_step}\n"); fprintf(stats_file, "* DEV EC C L I M F Values\n"); } else { #endif fprintf(stats_file, "* I interval remaining\n"); fprintf(stats_file, "* L current lookback\n"); fprintf(stats_file, "* DEV EC C I L Values\n"); fprintf(stats_file, "* Values {tries required, step, epoch seconds}\n"); #ifdef OLD } #endif for (int ndx = 0; ndx < I2C_BUS_MAX; ndx++) { if (results_tables[ndx]) { Results_Table * rtable = results_tables[ndx]; if (debug) dbgrpt_results_table(rtable, 2); int next_step = -1; #ifdef ALREADY_DONE // in dsa2_record_final if (rtable->highest_step_complete_loop_failure >= 0) { next_step = MIN(rtable->highest_step_complete_loop_failure + 1, step_last); assert(next_step <= step_last); rtable->cur_step = MAX(rtable->cur_step, next_step); } #endif DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, rtable->cur_step=%d, next_step=%d", rtable->busno, rtable->cur_step, next_step); #ifdef FORMAT1 if (format_id == 1) { fprintf(stats_file, "i2c-%d %02x %d %d %d %d %d", rtable->busno, rtable->edid_checksum_byte, rtable->cur_step, rtable->cur_lookback, rtable->remaining_interval, 0, 0); } else { // format_id == 2 #endif fprintf(stats_file, "i2c-%d %02x %d %d %d", rtable->busno, rtable->edid_checksum_byte, rtable->cur_step, rtable->remaining_interval, rtable->cur_lookback); #ifdef FORMAT1 } #endif for (int k = 0; k < rtable->recent_values->ct; k++) { Successful_Invocation si = cirb_get_logical(rtable->recent_values, k); fprintf(stats_file, " {%d,%d,%jd}", si.tryct, si.required_step, (intmax_t)si.epoch_seconds); } #ifdef OUT // wrong - should write it to the circular buffer if (next_step >= 0) { fprintf(stats_file, " {%d,%d,%ld}", 999, rtable->cur_step, cur_realtime_nanosec()/(1000*1000*1000)); } #endif fputc('\n', stats_file); } } fclose(stats_file); bye: free(stats_fn); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, "Wrote %d Results_Table(s)", results_tables_ct); return result; } /** Deletes the stats file. It is not an error if the file does not exist. * * @retval -errno if deletion fails for any reason other than non-existence * @retval 0 success */ Status_Errno dsa2_erase_persistent_stats() { bool debug = false; Status_Errno result = 0; DBGTRC_STARTING(debug, TRACE_GROUP, ""); char * stats_fn = dsa2_stats_cache_file_name(); if (stats_fn) { int rc = remove(stats_fn); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "remove(\"%s\") returned: %d", stats_fn, rc); if (rc < 0 && errno != ENOENT) result = -errno; free(stats_fn); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } static void stats_file_error(GPtrArray* errmsgs, char * format, ...) { va_list(args); va_start(args, format); char buffer[200]; vsnprintf(buffer, sizeof(buffer), format, args); if (errmsgs) g_ptr_array_add(errmsgs, strdup(buffer)); // DBGMSG(buffer); va_end(args); } static bool cirb_parse_and_add(Circular_Invocation_Result_Buffer * cirb, char * segment) { bool debug = false; DBGMSF(debug, "segment |%s|", segment); bool result = false; if ( strlen(segment) >= 7 && segment[0] == '{' && segment[strlen(segment)-1] == '}' ) { char * s = g_strdup(segment); char * comma_pos = strchr(s, ','); char * comma_pos2 = (comma_pos) ? strchr(comma_pos+1, ',') : NULL; char * lastpos = s + strlen(s) - 1; // subtract for final '}' if (comma_pos && comma_pos2) { *comma_pos = '\0'; *comma_pos2 = '\0'; *lastpos = '\0'; if (strlen(s+1) > 0 && strlen(comma_pos+1) > 0 && strlen(comma_pos2 + 1) > 0 ) { Successful_Invocation si; result = str_to_int(s+1, &si.tryct, 10); result &= str_to_int(comma_pos + 1, &si.required_step, 10); long esec; result &= str_to_long(comma_pos2 + 1, &esec, 10); si.epoch_seconds = (time_t) esec; if (result) { cirb_add(cirb, si); } } } g_free(s); } DBGMSF(debug, "Returning %s", sbool(result)); return result; } /** Load execution statistics from a file. * * The file name is determined using XDG rules * * @return struct Error_Info if error, NULL if no error */ Error_Info * dsa2_restore_persistent_stats() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); char * stats_fn = dsa2_stats_cache_file_name(); Error_Info * result = NULL; if (!stats_fn) { result = ERRINFO_NEW(-ENOENT, "Unable to determine dynamic sleep stats file name"); goto bye1; } // DBGMSG("stats_fn=%s", stats_fn); bool all_ok = true; GPtrArray* line_array = g_ptr_array_new_with_free_func(g_free); int linect = file_getlines(stats_fn, line_array, debug); if (linect == -ENOENT) goto bye0; GPtrArray * errmsgs = g_ptr_array_new_with_free_func(g_free); if (linect < 0) { stats_file_error(errmsgs, "Error %s reading stats file %s", psc_desc(linect), stats_fn); all_ok = false; goto bye; } if (linect == 0) { // empty file stats_file_error(errmsgs, "Empty stats file"); goto bye; } char * format_id_line = g_ptr_array_index(line_array, 0); // DBGMSG("format_id_line %p |%s|", format_line, format_line); if (!str_starts_with(format_id_line, "FORMAT ")) { stats_file_error(errmsgs, "Invalid format line: %s", format_id_line); all_ok = false; goto bye; } int format_id; char * sformat = format_id_line + strlen("FORMAT "); // DBGMSG("sformat %d %p |%s|", strlen("FORMAT "), sformat, sformat); bool ok = str_to_int( sformat, &format_id, 10); if (!ok || (format_id != 1 && format_id != 2)) { stats_file_error(errmsgs, "Invalid format: %s", sformat); all_ok = false; goto bye; } for (int linendx = 1; linendx < line_array->len; linendx++) { char * cur_line = g_ptr_array_index(line_array, linendx); // DBGMSG("cur_line = |%s|", cur_line); if (strlen(cur_line) >= 1 && cur_line[0] != '#' && cur_line[0] != '*') { Null_Terminated_String_Array pieces = strsplit(cur_line, " "); int piecect = ntsa_length(pieces); int busno = -1; Results_Table * rtable = NULL; int fieldndx = 0; int min_pieces = 7; // format 1 if (format_id == 2) min_pieces = 5; bool ok = (piecect >= min_pieces); if (ok) { busno = i2c_name_to_busno(pieces[fieldndx++]); // field 0 rtable = new_results_table(busno); // rtable->initial_step_from_cache = true; ok = (busno >= 0); } assert(!ok || rtable); ok = ok && any_one_byte_hex_string_to_byte_in_buf(pieces[fieldndx++], &rtable->edid_checksum_byte); // field 1 ok = ok && str_to_int(pieces[fieldndx++], &rtable->cur_step, 10); // field 2 if (ok) { if (rtable->cur_step > step_last) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, resetting invalid cur_step from %d to %d !!!", busno, rtable->cur_step, step_last); SYSLOG2(DDCA_SYSLOG_ERROR, "(%s) busno=%d, resetting invalid cur_step from %d to %d", __func__, busno, rtable->cur_step, step_last); rtable->cur_step = step_last; } } if (format_id == 1) { int isink; ok = ok && str_to_int(pieces[fieldndx++], &isink, 10); // field 3 } // format 1: field 4, format 2: field 3 ok = ok && str_to_int(pieces[fieldndx++], &rtable->remaining_interval, 10); if (format_id == 1) { int isink; ok = ok && str_to_int(pieces[fieldndx++], &isink, 10); // field 5 ok = ok && str_to_int(pieces[fieldndx++], &isink, 10); // field 6 } // n. Format 2: field 4 (current lookback) ignored if (ok) { // rtable->found_failure_step = (iwork); rtable->cur_retry_loop_step = rtable->cur_step; rtable->initial_step = rtable->cur_step; rtable->initial_lookback = global_lookback; } // field 1: start from field 7, format 2: start from field 5 if (piecect >= min_pieces) { // handle no Successful_Invocation data for (int ndx = min_pieces; ndx < piecect; ndx++) { ok = ok && cirb_parse_and_add(rtable->recent_values, pieces[ndx]); } } if (!ok) { all_ok = false; stats_file_error(errmsgs, "Invalid: %s", cur_line); free_results_table(rtable); } else { rtable->state = RTABLE_FROM_CACHE; results_tables[busno] = rtable; if (debug) dbgrpt_results_table(rtable, 1); } ntsa_free(pieces, true); DBGTRC(debug, TRACE_GROUP, "Restored stats for /dev/i2c-%d", busno); } } if (!all_ok) { for (int ndx = 0; ndx <= I2C_BUS_MAX; ndx++) { if (results_tables[ndx]) { free_results_table(results_tables[ndx]); results_tables[ndx] = NULL; } } } bye: if (!all_ok) { result = ERRINFO_NEW(DDCRC_BAD_DATA, "Error(s) reading cached performance stats file %s", stats_fn); for (int ndx = 0; ndx < errmsgs->len; ndx++) { Error_Info * err = ERRINFO_NEW(DDCRC_BAD_DATA, g_ptr_array_index(errmsgs, ndx)); errinfo_add_cause(result, err); } } g_ptr_array_free(errmsgs, true); bye0: free(stats_fn); g_ptr_array_free(line_array, true); bye1: DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, ""); return result; } #ifdef DIDNT_WORK DDCA_Sleep_Multiplier logistic(double x) { // const double M_E = 2.7182818284590452354; double k = .5; double result = exp(k*x)/(1+exp(k*x)); return result; } void test_one_logistic(int steps) { double domain_min = -8.0f; double domain_max = 8.0f; // dpiuble interval = 1.0f/steps; double interval = (domain_max-domain_min)/steps; for (int i = 0; i <= steps; i++) { double x = i *interval + domain_min; double y = logistic(x); printf("i = %2d x = %2.3f y = %2.3f\n", i, x, y); } } #endif // // Initialization and Termination // /** Initialize this file. */ void init_dsa2() { RTTI_ADD_FUNC(dsa2_adjust_for_rcnt_successes); RTTI_ADD_FUNC(dsa2_erase_persistent_stats); RTTI_ADD_FUNC(dsa2_get_adjusted_sleep_mult); RTTI_ADD_FUNC(dsa2_get_results_table_by_busno); RTTI_ADD_FUNC(dsa2_note_retryable_failure); RTTI_ADD_FUNC(dsa2_record_final); RTTI_ADD_FUNC(dsa2_reset_multiplier); RTTI_ADD_FUNC(dsa2_restore_persistent_stats); RTTI_ADD_FUNC(dsa2_save_persistent_stats); RTTI_ADD_FUNC(dsa2_too_few_errors); RTTI_ADD_FUNC(dsa2_too_many_errors); RTTI_ADD_FUNC(dsa2_next_retry_step); RTTI_ADD_FUNC(dsa2_multiplier_to_step); results_tables = calloc(I2C_BUS_MAX+1, sizeof(Results_Table*)); adjusted_step_ct = absolute_step_ct - dsa2_step_floor; // 11; // initially 11 // test_one_logistic(10); // test_dsa2_next_retry_step(); // test_float_to_step_conversion(); } /** Release all resources */ void terminate_dsa2() { // release all resources if (results_tables) { for (int ndx = 0; ndx < I2C_BUS_MAX+1; ndx++) { if (results_tables[ndx]) free_results_table(results_tables[ndx]); } } free(results_tables); } ddcutil-2.2.0/src/base/dynamic_features.c0000644000175000001440000005401014754153540014017 /** @file dynamic_features.c * * Dynamic Feature Record definition, creation, destruction, and conversion */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include /** \endcond */ #include "ddcutil_status_codes.h" #include "ddcutil_types.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/feature_metadata.h" #include "base/monitor_model_key.h" #include "base/rtti.h" #include "base/vcp_version.h" #include "dynamic_features.h" // // Trace control // static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_UDF; // // Generic functions that probably belong elsewhere // // TODO: Consider moving to string_util typedef struct { char * word; char * rest; } Tokenized; Tokenized first_word(char * s) { // DBGMSG("Starting. s=|%s|", s); Tokenized result = {NULL,NULL}; if (s) { while (isspace(*s)) s++; if (*s) { char * end = s; while (*++end && !isspace(*end)); int wordlen = end-s; result.word = malloc( wordlen+1); memcpy(result.word, s, wordlen); result.word[wordlen] = '\0'; while (isspace(*end)) end++; if (*end == '\0') end = NULL; result.rest = end; } } // DBGMSG("Returning: result.word=|%s|, result.rest=|%s|", result.word, result.rest); return result; } // End of generic functions // Dynamic_Features_Rec /** Create a string representation of the flags set in a #DFR_Flags value. * * @param value to interpret * @return string representation * * The returned value is valid until the next call to this function in * the current thread. Do not free. */ const char * interpret_dfr_flags_symbolic_t(DFR_Flags flags) { bool debug = false; static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buffer = get_thread_fixed_buffer(&buf_key, 100); if (flags == DFR_FLAGS_NONE) strcpy(buffer, "DFR_FLAGS_NONE"); else { g_snprintf(buffer, 100, "%s%s", (flags & DFR_FLAGS_NOT_FOUND) ? "DFR_FLAGS_NOT_FOUND|" : "", (flags & DFR_FLAG_EXCLUDE_FROM_API) ? "DFR_FLAG_EXCLUDE_FROM_API|" : "" ); // remove final comma and blank if (strlen(buffer) > 0) buffer[strlen(buffer)-1] = '\0'; } DBGMSF(debug, "flags=0x%04x, returning %s", flags, buffer); return buffer; } /** Emits a debug report of a #Dynamic_Features_Rec. * * @param dfr value to report * @param depth logical indentation depth */ void dbgrpt_dynamic_features_rec( Dynamic_Features_Rec* dfr, int depth) { assert(dfr && memcmp(dfr->marker, DYNAMIC_FEATURES_REC_MARKER, 4) == 0); int d1 = depth + 1; rpt_structure_loc("Dynamic_Features_Rec", dfr, depth); rpt_vstring(d1, "marker: %4s", dfr->marker); rpt_vstring(d1, "mfg_id: %s", dfr->mfg_id); rpt_vstring(d1, "model_name: %s", dfr->model_name); rpt_vstring(d1, "product_code: %u", dfr->product_code); rpt_vstring(d1, "filename: %s", dfr->filename); rpt_vstring(d1, "MCCS vspec: %d.%d", dfr->vspec.major, dfr->vspec.minor); rpt_vstring(d1, "flags: 0x%02x %s", dfr->flags, interpret_dfr_flags_symbolic_t(dfr->flags)); if (dfr->features) { rpt_vstring(d1, "features count: %d", g_hash_table_size(dfr->features)); for (int ndx = 1; ndx < 256; ndx++) { Dyn_Feature_Metadata * cur_feature = g_hash_table_lookup(dfr->features, GINT_TO_POINTER(ndx)); if (cur_feature) dbgrpt_dyn_feature_metadata(cur_feature, d1); } } } /** Thread safe function that returns a string representation of a #Dynamic_Features_Rec * suitable for diagnostic messages. The returned value is valid until the * next call to this function on the current thread. * * @param dfr pointer to #Dynamic_Features_Rec * @return string representation */ char * dfr_repr_t(Dynamic_Features_Rec * dfr) { static GPrivate dfr_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&dfr_repr_key, 100); if (dfr) g_snprintf(buf, 100, "Dynamic_Features_Rec[%s,%s,%d]", dfr->mfg_id, dfr->model_name, dfr->product_code); else g_snprintf(buf, 100, "NULL"); return buf; } /** Gets a #Dyn_Feature_Metadata record from the features hash table * of a #Dynamic_Features_Rec. * * @param dfr pointer to dynamic feature record * @param feature_code feature code * @return pointer to feature metadata, NULL if not found */ Dyn_Feature_Metadata * dyn_get_dynamic_feature_metadata( Dynamic_Features_Rec * dfr, uint8_t feature_code) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dfr=%s, feature_code=0x%02x", dfr_repr_t(dfr), feature_code); Dyn_Feature_Metadata * result = NULL; if (dfr && dfr->features) result = g_hash_table_lookup(dfr->features, GINT_TO_POINTER(feature_code)); DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", result); return result; } /** Free a #Dyn_Feature_Metadata record. * * @info data pointer to record * * This function can be cast to GDestroyNotify. */ void dyn_free_feature_metadata( Dyn_Feature_Metadata * info) // i.e. Dyn_Feature_Metadata * { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Starting. Dyn_Feature_Metadata * data = %p", info); assert(info && memcmp(info->marker, DDCA_FEATURE_METADATA_MARKER, 4) == 0); // compare vs ddca_free_metadata_contents() if (debug) dbgrpt_dyn_feature_metadata(info, 2); free(info->feature_desc); free(info->feature_name); if (info->sl_values) { DBGMSF(debug, "Freeing sl_values table at %p", info->sl_values); free_sl_value_table(info->sl_values); } // free latest_sl_values ? info->marker[3] = 'x'; free(info); DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Create a #Dynamic_Feature_Rec * * @param mfg_id * @param model_name * @param product_code * @param filename * @return newly allocated #Dynamic_Features_Rec, caller must free */ Dynamic_Features_Rec * dfr_new( const char * mfg_id, const char * model_name, uint16_t product_code, const char * filename) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "mfg_id -> %s, model_name -> %s, product_code=%d, filename -> %s", mfg_id, model_name, product_code, filename); assert(mfg_id); assert(model_name); Dynamic_Features_Rec * frec = calloc(1, sizeof(Dynamic_Features_Rec)); memcpy(frec->marker, DYNAMIC_FEATURES_REC_MARKER, 4); frec->mfg_id = g_strdup(mfg_id); frec->model_name = g_strdup(model_name); frec->product_code = product_code; frec->vspec = DDCA_VSPEC_UNKNOWN; // redundant, since set by calloc(), but be explicit if (filename) frec->filename = g_strdup(filename); DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", frec); return frec; } /** Free a #Dynamic_Features_Rec * * @param frec pointer to record to free, if NULL no operation is performed */ void dfr_free( Dynamic_Features_Rec * frec) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "frec=%p", frec); if (frec) { assert(memcmp(frec->marker, DYNAMIC_FEATURES_REC_MARKER, 4) == 0); if (debug) dbgrpt_dynamic_features_rec(frec, 2); free(frec->mfg_id); free(frec->model_name); free(frec->filename); if (frec->features) { DBGMSF(debug, "Calling g_hash_table_destroy() for %p", frec->features); g_hash_table_destroy(frec->features); // n. destroy function for values set at creation } free(frec); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Functions private to create_monitor_dynamic_features() // /** Creates a #Error_Info using the error location (line number) and * detail, and appends it to array **errors**.. * * @param errors GPtrArray of #Error_Info * @param filename name of file whose lines are being processed * @param linectr line number of error * @param caller function creating the error message * @param fmt message format string * @param .. substitution values * @return newly allocated #Error_Info struct, with status code DDCRC_CONFIG_ERROR */ static void add_error( GPtrArray * errors, // array of Error_Info const char * filename, int linectr, const char * caller, char * fmt, ...) { char detail[200]; char xdetail[300]; char * final_detail; va_list(args); va_start(args, fmt); vsnprintf(detail, 200, fmt, args); if (filename) { if (linectr > 0) { snprintf(xdetail, sizeof(xdetail), "%s at line %d", detail, linectr); // snprintf(xdetail, sizeof(xdetail), "%s at line %d of file %s", detail, linectr, filename); } else snprintf(xdetail, sizeof(xdetail), "%s in file %s", detail, filename); final_detail = xdetail; } else { final_detail = detail; } Error_Info * err = errinfo_new(DDCRC_CONFIG_ERROR, caller, final_detail); g_ptr_array_add(errors, err); va_end(args); } #define ADD_ERROR(_linectr, _fmt, ...) \ add_error(errors, filename, _linectr, __func__, _fmt, ##__VA_ARGS__) static bool attr_keyword( Dyn_Feature_Metadata * cur_feature_metadata, char * keyword) { bool debug = false; DBGMSF(debug, "keyword=|%s|", keyword); bool ok = true; DDCA_Feature_Flags * pflags = &cur_feature_metadata->version_feature_flags; if (streq(keyword, "RW")) *pflags |= DDCA_RW; else if (streq(keyword, "RO")) *pflags |= DDCA_RO; else if (streq(keyword, "WO")) *pflags |= DDCA_WO; else if (streq(keyword, "C")) *pflags |= DDCA_STD_CONT; else if (streq(keyword, "CCONT")) *pflags |= DDCA_COMPLEX_CONT; else if (streq(keyword, "NC")) *pflags |= DDCA_SIMPLE_NC; else if (streq(keyword, "SNC")) *pflags |= DDCA_SIMPLE_NC; else if (streq(keyword, "XNC")) *pflags |= DDCA_EXTENDED_NC; else if (streq(keyword, "T")) *pflags |= DDCA_TABLE; else ok = false; DBGMSF(debug, "Returning %s", SBOOL(ok)); return ok; } static void switch_bits( DDCA_Feature_Flags * pflags, uint16_t old_bit, uint16_t new_bit) { *pflags &= ~old_bit; *pflags |= new_bit; } static void finalize_feature( Dynamic_Features_Rec * frec, Dyn_Feature_Metadata * cur_feature_metadata, GArray * cur_feature_values, const char * filename, GPtrArray * errors) { // DDCA_Feature_Flags * pflags = &cur_feature_metadata->feature_flags; if (cur_feature_values) { // add terminating entry DDCA_Feature_Value_Entry last_entry; last_entry.value_code = 0x00; last_entry.value_name = NULL; g_array_append_val(cur_feature_values, last_entry); cur_feature_metadata->sl_values = (DDCA_Feature_Value_Entry*) cur_feature_values->data; } if ( cur_feature_metadata->version_feature_flags & (DDCA_RW | DDCA_RO | DDCA_WO) ) cur_feature_metadata->version_feature_flags |= DDCA_RW; if (cur_feature_metadata->sl_values) { if (cur_feature_metadata->version_feature_flags & DDCA_COMPLEX_NC) { if ( cur_feature_metadata->version_feature_flags & DDCA_WO) switch_bits(&cur_feature_metadata->version_feature_flags, DDCA_COMPLEX_NC, DDCA_WO_NC); else switch_bits(&cur_feature_metadata->version_feature_flags, DDCA_COMPLEX_NC, DDCA_SIMPLE_NC); } else if ( cur_feature_metadata->version_feature_flags & (DDCA_COMPLEX_CONT | DDCA_STD_CONT | DDCA_TABLE)) ADD_ERROR(-1, "Feature values specified for Continuous or Table feature"); } if (cur_feature_metadata->version_feature_flags & DDCA_NORMAL_TABLE & DDCA_WO) switch_bits(&cur_feature_metadata->version_feature_flags, DDCA_NORMAL_TABLE, DDCA_WO_TABLE); // For now, to revisit // cur_feature_metadata->vspec = frec->vspec; g_hash_table_replace( frec->features, GINT_TO_POINTER(cur_feature_metadata->feature_code), cur_feature_metadata); } /** Parse a set of lines describing a dynamic feature record, returning a * newly created #Dynamic_Feature_Rec if successful. * * @param mfg_id 3 character manufacturer identifier * @param model_name model name * @param product_code product code, as integer * @param lines array of input lines * @param filename source file name, for diagnostic messages, may be NULL * @param dynamic_features_loc where to return pointer to newly allocated #Dynamic_Features_Rec, * NULL if an #Error_Info struct is returned * @return pointer to #Error_Info, NULL if no error * The #Error_Info, and all of its causes, have status code DDCRC_CONFIG_ERROR */ Error_Info * create_dynamic_features_rec( const char * mfg_id, const char * model_name, uint16_t product_code, GPtrArray * lines, const char * filename, // may be NULL Dynamic_Features_Rec ** dynamic_features_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "filename=%s", filename); Error_Info * master_err = NULL; GPtrArray * errors = g_ptr_array_new(); Dynamic_Features_Rec * frec = dfr_new(mfg_id, model_name, product_code, filename); bool mfg_id_seen = false; bool model_name_seen = false; bool product_code_seen = false; frec->features = g_hash_table_new_full( g_direct_hash, g_direct_equal, NULL, // key_destroy_func (GDestroyNotify) dyn_free_feature_metadata); // value_destroy_func Dyn_Feature_Metadata * cur_feature_metadata = NULL; GArray * cur_feature_values = NULL; int linectr = 0; while ( linectr < lines->len ) { char * line = g_ptr_array_index(lines,linectr); // 0 based linectr++; // line numbers in error msgs are 1 based Tokenized t1 = first_word(line); if (t1.word && *t1.word != '*' && *t1.word != '#') { Tokenized t2 = first_word(t1.rest); if (!t2.word) { ADD_ERROR(linectr, "Invalid data \"%s\"", line); } else { if (streq(t1.word, "PRODUCT_CODE")) { product_code_seen = true; int ival; bool ok = str_to_int(t2.word, &ival, 10); if (!ok) { ADD_ERROR(linectr, "Invalid product_code \"%s\"", t2.word); } else if (ival != product_code) { ADD_ERROR(linectr, "Unexpected product_code %d, expected %d", ival, product_code); } } else if (streq(t1.word, "MFG_ID")) { mfg_id_seen = true; if ( !streq(t2.word, mfg_id) ) { ADD_ERROR(linectr, "Unexpected manufacturer id \"%s\", expected \"%s\"", t2.word, mfg_id); } } else if (streq(t1.word, "MODEL")) { model_name_seen = true; char * s = strdup(t1.rest); FIXUP_MODEL_NAME(s); if ( !streq(s, model_name) ) { ADD_ERROR(linectr, "Unexpected model name \"%s\", expected \"%s\"", t1.rest, model_name); } free(s); } else if (streq(t1.word, "MCCS_VERSION") || streq(t1.word, "VCP_VERSION") ) { // mccs_version_seen = true; // not required for now // default as set by calloc() is 0.0, which is DDCA_VSPEC_UNKNOWN // returns DDCA_VSPEC_UKNOWN if invalid DDCA_MCCS_Version_Spec vspec = parse_vspec(t1.rest); if (!vcp_version_is_valid(vspec, /*allow DDCA_VSPEC_UNKNOWN */ false)) ADD_ERROR(linectr, "Invalid MCCS version: \"%s\"", t1.rest); else frec->vspec = vspec; } else if (streq(t1.word, "ATTRS")) { if (!cur_feature_metadata) { ADD_ERROR(linectr, "ATTRS before FEATURE_CODE"); } else { Tokenized t = first_word(t1.rest); while (t.word) { // set values in cur_feature_metadata->feature_flags bool ok = attr_keyword(cur_feature_metadata, t.word); if (!ok) { ADD_ERROR(linectr, "Invalid attribute \"%s\"", t.word); } free(t.word); t = first_word(t.rest); } } } else if (streq(t1.word, "FEATURE_CODE")) { // n. cur_feature_metadata saved in frec if (cur_feature_metadata) { finalize_feature( frec, cur_feature_metadata, cur_feature_values, filename, errors); if (cur_feature_values) { g_array_free(cur_feature_values, false); cur_feature_values = NULL; } } cur_feature_metadata = calloc(1, sizeof(Dyn_Feature_Metadata)); memcpy(cur_feature_metadata->marker, DDCA_FEATURE_METADATA_MARKER, 4); cur_feature_metadata->global_feature_flags = DDCA_USER_DEFINED | DDCA_PERSISTENT_METADATA; char * feature_code = t2.word; char * feature_name = t2.rest; if (!feature_name) { ADD_ERROR(linectr, "Invalid VCP data \"%s\"", line); } else { // found feature id and value // Byte feature_id; int feature_id; // todo: handle xnn as well as nn ? //bool ok = hhs_to_byte_in_buf(feature_code, &feature_id); char * can = canonicalize_possible_hex_value(feature_code); bool ok = str_to_int(can, &feature_id, 16); free(can); if (!ok) { ADD_ERROR(linectr, "Invalid feature code \"%s\"", feature_code); } else { // valid opcode cur_feature_metadata->feature_code = feature_id; cur_feature_metadata->feature_name = g_strdup(feature_name); cur_feature_metadata->feature_desc = NULL; // ignore for now } } } else if (streq(t1.word, "VALUE")) { if (!t2.rest) { ADD_ERROR(linectr, "Missing feature value data \"%s\"", line); } else { // found value code and name int feature_value; // Byte feature_value; char * canonical = canonicalize_possible_hex_value(t2.word); bool ok = str_to_int(canonical, &feature_value, 0); free(canonical); if (!ok || feature_value < 0 || feature_value > 255) { ADD_ERROR(linectr, "Invalid feature value \"%s\"", t2.word); } else { // valid feature value if (!cur_feature_values) cur_feature_values = g_array_new(false, false, sizeof(DDCA_Feature_Value_Entry)); DDCA_Feature_Value_Entry entry; entry.value_code = feature_value; entry.value_name = g_strdup(t2.rest); g_array_append_val(cur_feature_values, entry); } } } else { ADD_ERROR(linectr, "Unexpected field \"%s\"", t1.word); } } // more than 1 field on line if (t2.word) free(t2.word); } // non-comment line if (t1.word) free(t1.word); } // one line of file if (cur_feature_metadata) { finalize_feature( frec, cur_feature_metadata, cur_feature_values, filename, errors); if (cur_feature_values) { g_array_free(cur_feature_values, false); cur_feature_values = NULL; } } if (g_hash_table_size(frec->features) == 0) ADD_ERROR(-1, "No feature codes defined"); if (!mfg_id_seen) ADD_ERROR(-1, "Missing MFG_ID"); if (!model_name_seen) ADD_ERROR(-1, "Missing MODEL_NAME"); if (!product_code_seen) ADD_ERROR(-1, "Missing PRODUCT_CODE"); if (errors->len > 0) { char * detail = g_strdup_printf("Error(s) processing monitor definition file: %s", filename); master_err = errinfo_new_with_causes( DDCRC_CONFIG_ERROR, (Error_Info**) errors->pdata, errors->len, __func__, detail); free(detail); g_ptr_array_free(errors, false); dfr_free(frec); *dynamic_features_loc = NULL; } else { g_ptr_array_free(errors, false); *dynamic_features_loc = frec; } ASSERT_IFF(master_err, !*dynamic_features_loc); DBGTRC_RET_ERRINFO_STRUCT(debug, TRACE_GROUP, master_err, dynamic_features_loc, dbgrpt_dynamic_features_rec); #ifdef OLD DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, master_err, "*dynamic_features_loc=%p", *dynamic_features_loc); if ( (debug || IS_TRACING()) && *dynamic_features_loc ) dbgrpt_dynamic_features_rec(*dynamic_features_loc, 1); #endif return master_err; } void init_base_dynamic_features() { RTTI_ADD_FUNC(dyn_get_dynamic_feature_metadata) RTTI_ADD_FUNC(create_dynamic_features_rec); RTTI_ADD_FUNC(dyn_free_feature_metadata); RTTI_ADD_FUNC(dfr_new); RTTI_ADD_FUNC(dfr_free); } ddcutil-2.2.0/src/base/execution_stats.c0000644000175000001440000005074714727162000013722 /** @file execution_stats.c * * Record execution statistics, mainly the count and elapsed time of system calls. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include /** \endcond */ #include "ddcutil_status_codes.h" #include "util/glib_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/sleep.h" #include "base/parms.h" #include "base/ddc_errno.h" #include "base/linux_errno.h" #include "base/execution_stats.h" // // Typedefs // typedef struct { IO_Event_Type id; const char * name; const char * desc; uint64_t call_nanosec; int call_count; } IO_Event_Type_Stats; // struct that accumulates status code occurrence statistics // The design allows for multiple Status_Code_Counts instances // used for different purposes (e.g. derived status codes), // hence the name field. // But currently there is only 1 instance. #define STATUS_CODE_COUNTS_MARKER "SCCT" typedef struct { char marker[4]; GHashTable * error_counts_hash; // hash table whose key is a status code, and whose // value is the number of occurrences of that status code int total_status_counts; char * name; } Status_Code_Counts; // // Global Variables // static uint64_t program_start_timestamp; static uint64_t resettable_start_timestamp; static Status_Code_Counts * primary_error_code_counts = NULL; static Status_Code_Counts * retryable_error_code_counts = NULL; static GMutex status_code_counts_mutex; static GMutex global_stats_mutex; static bool debug_status_code_counts_mutex = false; static bool debug_global_stats_mutex = false; static bool debug_sleep_stats_mutex = false; // // IO Event Tracking // static IO_Event_Type_Stats io_event_stats[] = { // id name desc nanosec count {IE_FILEIO_WRITE, "IE_FILEIO_WRITE", "i2c writes using write()", 0, 0}, {IE_FILEIO_READ, "IE_FILEIO_READ", "i2c reads using read()", 0, 0}, {IE_IOCTL_WRITE, "I2_IOCTL_WRITE", "i2c writes using ioctl", 0, 0}, {IE_IOCTL_READ, "I2_IOCTL_READ", "i2c reads using ioctl", 0, 0}, {IE_OPEN, "IE_OPEN", "open file calls", 0, 0}, {IE_CLOSE, "IE_CLOSE", "close file calls", 0, 0}, {IE_OTHER, "IE_OTHER", "other I/O calls", 0, 0}, }; #define IO_EVENT_TYPE_CT (sizeof(io_event_stats)/sizeof(IO_Event_Type_Stats)) static GMutex io_event_stats_mutex; static bool debug_io_event_stats_mutex; static void reset_io_event_stats() { bool debug = false || debug_io_event_stats_mutex; DBGMSF(debug, "Starting"); g_mutex_lock(&io_event_stats_mutex); for (int ndx = 0; ndx < IO_EVENT_TYPE_CT; ndx++) { io_event_stats[ndx].call_count = 0; io_event_stats[ndx].call_nanosec = 0; } g_mutex_unlock(&io_event_stats_mutex); DBGMSF(debug, "Done"); } /** Returns symbolic name of an event type. * * @param event_type * @return symbolic name */ const char * io_event_name(IO_Event_Type event_type) { return io_event_stats[event_type].name; } #ifdef UNUSED int max_event_name_length() { int result = 0; int ndx = 0; for (;ndx < IO_EVENT_TYPE_CT; ndx++) { int curval = strlen(io_event_stats[ndx].name); if (curval > result) result = curval; } return result; } #endif static int total_io_event_count() { int total = 0; int ndx = 0; for (;ndx < IO_EVENT_TYPE_CT; ndx++) total += io_event_stats[ndx].call_count; return total; } #ifdef UNUSED uint64_t total_io_event_nanosec() { uint64_t total = 0; int ndx = 0; for (;ndx < IO_EVENT_TYPE_CT; ndx++) total += io_event_stats[ndx].call_nanosec; return total; } #endif // No effect on program logic, but makes debug messages easier to scan uint64_t normalize_timestamp(uint64_t timestamp) { return timestamp - program_start_timestamp; } /** Called immediately after an I2C IO call, this function updates the total * number of calls and elapsed time for categories of calls. * * @param event_type e.g. IE_IOCTL_WRITE * @param location function name * @param start_time_nanos starting time of the event in nanoseconds * @param end_time_nanos ending time of the event in nanoseconds */ void log_io_call( const IO_Event_Type event_type, const char * location, uint64_t start_time_nanos, uint64_t end_time_nanos) { bool debug = false || debug_io_event_stats_mutex; uint64_t elapsed_nanos = (end_time_nanos-start_time_nanos); DBGMSF(debug, "event_type=%d %-10s, elapsed_nanos=%"PRIu64", as millis=%"PRIu64, event_type, io_event_name(event_type), elapsed_nanos, elapsed_nanos/(1000*1000) ); g_mutex_lock(&io_event_stats_mutex); io_event_stats[event_type].call_count++; io_event_stats[event_type].call_nanosec += elapsed_nanos; g_mutex_unlock(&io_event_stats_mutex); DBGMSF(debug, "Updated total nanosec = %"PRIu64", as millis=%"PRIu64, io_event_stats[event_type].call_nanosec, io_event_stats[event_type].call_nanosec /(1000*1000) ); } /** Reports the accumulated execution statistics * * @param depth logical indentation depth */ void report_io_call_stats(int depth) { int d1 = depth+1; rpt_title("Call Stats:", depth); int total_ct = 0; uint64_t total_nanos = 0; int ndx = 0; // int max_name_length = max_event_name_length(); // not working as variable length string specifier // DBGMSG("max_name_length=%d", max_name_length); rpt_vstring(d1, "%-40s Count Millisec ( Nanosec)", "Type"); for (;ndx < IO_EVENT_TYPE_CT; ndx++) { if (io_event_stats[ndx].call_count > 0) { IO_Event_Type_Stats* curstat = &io_event_stats[ndx]; char buf[100]; snprintf(buf, 100, "%-22s (%s)", curstat->desc, curstat->name); rpt_vstring(d1, "%-40s %4d %10" PRIu64 " (%13" PRIu64 ")", buf, curstat->call_count, curstat->call_nanosec / (1000*1000), curstat->call_nanosec ); total_ct += curstat->call_count; total_nanos += curstat->call_nanosec; } } rpt_vstring(d1, "%-40s %4d %10"PRIu64" (%13" PRIu64 ")", "Totals:", total_ct, total_nanos / (1000*1000), total_nanos ); } typedef struct { int count; uint64_t nanos; } Non_Sleep_Call_Totals; Non_Sleep_Call_Totals get_non_sleep_call_totals () { Non_Sleep_Call_Totals totals; totals.count = 0; totals.nanos = 0; for (int ndx = 0; ndx < IO_EVENT_TYPE_CT; ndx++) { if (io_event_stats[ndx].call_count > 0) { IO_Event_Type_Stats* curstat = &io_event_stats[ndx]; totals.count += curstat->call_count; totals.nanos += curstat->call_nanosec; } } return totals; } // // Status Code Occurrence Tracking // // Design: IO errors are noted in the function that sets psc negative, // do not leave it to caller to set. That way do not need to keep track // if a called function has already set. // // BUT: status codes are not noted until they are modulated to Global_Status_Code static Status_Code_Counts * new_status_code_counts(char * name) { bool debug = false || debug_status_code_counts_mutex; DBGMSF(debug, "Starting"); g_mutex_lock(&status_code_counts_mutex); Status_Code_Counts * pcounts = calloc(1,sizeof(Status_Code_Counts)); memcpy(pcounts->marker, STATUS_CODE_COUNTS_MARKER, 4); pcounts->error_counts_hash = g_hash_table_new(NULL,NULL); pcounts->total_status_counts = 0; if (name) pcounts->name = g_strdup(name); g_mutex_unlock(&status_code_counts_mutex); DBGMSF(debug, "Done"); return pcounts; } void free_status_code_counts(Status_Code_Counts * counts) { bool debug = false; DBGMSF(debug, "counts=%p", counts); if (counts) { g_hash_table_destroy(counts->error_counts_hash); g_free(counts->name); free(counts); } DBGMSF(debug, "Done"); } static void reset_status_code_counts_struct(Status_Code_Counts * pcounts) { bool debug = false || debug_status_code_counts_mutex; DBGMSF(debug, "Starting"); assert(pcounts); g_mutex_lock(&status_code_counts_mutex); if (pcounts->error_counts_hash) g_hash_table_remove_all(pcounts->error_counts_hash); pcounts->total_status_counts = 0; g_mutex_unlock(&status_code_counts_mutex); DBGMSF(debug, "Done"); } static void reset_status_code_counts() { reset_status_code_counts_struct(primary_error_code_counts); reset_status_code_counts_struct(retryable_error_code_counts); } static int log_any_status_code(Status_Code_Counts * pcounts, int rc, const char * caller_name) { bool debug = false || debug_status_code_counts_mutex; DBGMSF(debug, "caller=%s, rc=%d", caller_name, rc); assert(pcounts->error_counts_hash); if (rc == 0) { DBGMSG("Called with rc = 0, from function %s", caller_name); } g_mutex_lock(&status_code_counts_mutex); pcounts->total_status_counts++; // n. if key rc not found, returns NULL, which is 0 int ct = GPOINTER_TO_INT(g_hash_table_lookup(pcounts->error_counts_hash, GINT_TO_POINTER(rc)) ); g_hash_table_insert(pcounts->error_counts_hash, GINT_TO_POINTER(rc), GINT_TO_POINTER(ct+1)); // DBGMSG("Old count=%d", ct); // check the new value #ifndef NDEBUG int newct = #endif GPOINTER_TO_INT(g_hash_table_lookup(pcounts->error_counts_hash, GINT_TO_POINTER(rc)) ); g_mutex_unlock(&status_code_counts_mutex); // DBGMSG("new count for key %d = %d", rc, newct); assert(newct == ct+1); DBGMSF(debug, "Done"); return ct+1; } /** Log a status code occurrence * * @param rc status code * @param caller_name function logging the event * * @return status code (unchanged) * * @remark returning the status code allows for assigning a status code and * logging it to be done in one statement */ Public_Status_Code log_status_code(Public_Status_Code rc, const char * caller_name) { // DBGMSG("rc=%d, caller_name=%s", rc, caller_name); Status_Code_Counts * pcounts = primary_error_code_counts; // if ( ddcrc_is_derived_status_code(rc) ) // pcounts = secondary_status_code_counts; log_any_status_code(pcounts, rc, caller_name); return rc; } /** Log a status code that occurs in a retry loop * * @param rc status code * @param caller_name function logging the event * * @return status code (unchanged) * * @remark returning the status code allows for assigning a status code and * logging it to be done in one statement */ Public_Status_Code log_retryable_status_code(Public_Status_Code rc, const char * caller_name) { // DBGMSG("rc=%d, caller_name=%s", rc, caller_name); Status_Code_Counts * pcounts = retryable_error_code_counts; log_any_status_code(pcounts, rc, caller_name); return rc; } // Used by qsort in show_specific_status_counts() static int compare( const void* a, const void* b) { int int_a = * ( (int*) (a) ); int int_b = * ( (int*) (b) ); if ( int_a == int_b ) return 0; else if ( int_a < int_b ) return 1; else return -1; } static void report_specific_status_counts(Status_Code_Counts * pcounts, int depth) { bool debug = false; DBGMSF(debug, "Starting"); char * title = (pcounts->name) ? pcounts->name : "Errors"; assert(pcounts->error_counts_hash); unsigned int keyct; // g_hash_table_get_keys_as_array() new in v 2.40, which is not later than the version // in all but the most recent distros, .e.g SUSE 13.2 is v 2.18 // gpointer * keysp = g_hash_table_get_keys_as_array(pcounts->error_counts_hash, &keyct); GList * glist = g_hash_table_get_keys(pcounts->error_counts_hash); // copies the pointers in the linked list to the array, does not duplicate gpointer * keysp = g_list_to_g_array(glist, &keyct); g_list_free(glist); if (debug) { DBGMSG("Keys. keyct=%d", keyct); for (int ndx = 0; ndx < keyct; ndx++) { DBGMSG( "keysp[%d]: %p %d", ndx, keysp[ndx], GPOINTER_TO_INT(keysp[ndx]) ); } } int summed_ct = 0; rpt_vstring(depth, "%s: %s\n", title, (keyct == 0) ? "None" : ""); if (keyct > 0) { qsort(keysp, keyct, sizeof(gpointer), compare); // sort keys rpt_vstring(depth, "Count Status Code Description"); int ndx; for (ndx=0; ndxerror_counts_hash,keyp)); summed_ct += ct; Status_Code_Info * desc = find_status_code_info(key); // or consider flags in Status_Code_Info with this information char * aux_msg = ""; if (ddcrc_is_derived_status_code(key)) aux_msg = " (derived)"; else if (ddcrc_is_not_error(key)) aux_msg = " (not an error)"; rpt_vstring(depth, "%5d %-28s (%5ld) %s %s", ct, (desc) ? desc->name : "", key, (desc) ? desc->description : "", aux_msg ); } } rpt_vstring(depth, "Total errors: %d", pcounts->total_status_counts); assert(summed_ct == pcounts->total_status_counts); g_free(keysp); DBGMSF(debug, "Done"); } /** Master function to display status counts * * @param depth logical_indentation_depth */ void report_all_status_counts(int depth) { report_specific_status_counts(primary_error_code_counts, 0); // show_specific_status_counts(secondary_status_code_counts); // not used rpt_nl(); report_specific_status_counts(retryable_error_code_counts, 0); rpt_nl(); } static int get_true_io_error_count(Status_Code_Counts * pcounts) { assert(pcounts->error_counts_hash); unsigned int keyct; // g_hash_table_get_keys_as_array() new in v 2.40, which is not later than the version // in all but the most recent distros, .e.g SUSE 13.2 is v 2.18 // gpointer * keysp = g_hash_table_get_keys_as_array(pcounts->error_counts_hash, &keyct); GList * glist = g_hash_table_get_keys(pcounts->error_counts_hash); gpointer * keysp = g_list_to_g_array(glist, &keyct); g_list_free(glist); int summed_ct = 0; int ndx; for (ndx=0; ndxerror_counts_hash,GINT_TO_POINTER(key))); summed_ct += ct; } // DBGMSG("Total errors: %d", total_counts); assert(summed_ct == pcounts->total_status_counts); g_free(keysp); return summed_ct; } // // Sleep Strategy // // Names for Sleep_Event enum values static const char * sleep_event_names[] = { "SE_WRITE_TO_READ", "SE_POST_WRITE", "SE_POST_READ", "SE_POST_SAVE_SETTINGS", "SE_PRE_MULTI_PART_READ", "SE_POST_CAP_TABLE_SEGMENT", "SE_SPECIAL", }; #define SLEEP_EVENT_ID_CT (sizeof(sleep_event_names)/sizeof(char *)) static int max_sleep_event_name_size() { int result = 0; for (int ndx = 0; ndx < SLEEP_EVENT_ID_CT; ndx++) { if (strlen(sleep_event_names[ndx]) > result) result = strlen(sleep_event_names[ndx]); } return result; } /** Returns the name of a sleep event type * * @param event_type sleep event type, e.g. SE_WRITE_TO_READ * @result * */ const char * sleep_event_name(Sleep_Event_Type event_type) { // ensure sleep_event_names stays in sync with Sync_Event_Type #ifndef NDEBUG const int sleep_event_type_count = SE_SPECIAL+1; // relies on values in enum assigned from 0 assert( SLEEP_EVENT_ID_CT == sleep_event_type_count); #endif return sleep_event_names[event_type]; } static int sleep_event_cts_by_id[SLEEP_EVENT_ID_CT]; static int total_sleep_event_ct = 0; static GMutex sleep_stats_mutex; void reset_sleep_event_counts() { bool debug = false || debug_sleep_stats_mutex; DBGMSF(debug, "Starting"); g_mutex_lock(&sleep_stats_mutex); for (int ndx = 0; ndx < SLEEP_EVENT_ID_CT; ndx++) { sleep_event_cts_by_id[ndx] = 0; } g_mutex_unlock(&sleep_stats_mutex); DBGMSF(debug, "Done"); } void record_sleep_event(Sleep_Event_Type event_type) { // For better performance, separate mutex for each index in array g_mutex_lock(&sleep_stats_mutex); sleep_event_cts_by_id[event_type]++; total_sleep_event_ct++; g_mutex_unlock(&sleep_stats_mutex); } /** Reports execution statistics. * * @param depth logical indentation depth */ void report_execution_stats(int depth) { int sleep_name_field_size = max_sleep_event_name_size(); int d1 = depth+1; rpt_title("IO and Sleep Events:", depth); rpt_vstring(d1, "Total IO events: %5d", total_io_event_count()); rpt_vstring(d1, "IO error count: %5d", get_true_io_error_count(primary_error_code_counts)); rpt_vstring(d1, "Total sleep events: %5d", total_sleep_event_ct); rpt_nl(); rpt_title("Sleep Event type Count", d1); for (int id=0; id < SLEEP_EVENT_ID_CT; id++) { rpt_vstring(d1, "%-*s %4d", sleep_name_field_size, sleep_event_names[id], sleep_event_cts_by_id[id]); } } // // Module initialization // /** Initializes execution stats module. * * Must be called once at program startup. */ void init_execution_stats() { primary_error_code_counts = new_status_code_counts("DDC Related Errors"); retryable_error_code_counts = new_status_code_counts("Errors Wrapped in Retry"); // secondary_status_code_counts = new_status_code_counts("Derived and Other Errors"); program_start_timestamp = cur_realtime_nanosec(); resettable_start_timestamp = program_start_timestamp; elapsed_time_nanosec(); // first call initializes, used for dbgtrc } /** Resets collected execution statistics */ void reset_execution_stats() { bool debug = false || debug_global_stats_mutex; DBGMSF(debug, "Starting"); reset_sleep_event_counts(); reset_status_code_counts(); reset_io_event_stats(); g_mutex_lock(&global_stats_mutex); resettable_start_timestamp = cur_realtime_nanosec(); g_mutex_unlock(&global_stats_mutex); DBGMSF(debug, "Done"); } /** Reports elapsed time statistics. * * @param depth logical indentation depth * * If a statistics reset has occurred, reports both the time * since reset and total elapsed time. */ void report_elapsed_stats(int depth) { uint64_t end_nanos = cur_realtime_nanosec(); if (program_start_timestamp != resettable_start_timestamp) { g_mutex_lock(&global_stats_mutex); // not really needed, make coverity happy uint64_t cur_elapsed_nanos = end_nanos - resettable_start_timestamp; g_mutex_unlock(&global_stats_mutex); rpt_vstring(depth, "Elapsed milliseconds since last reset (nanosec):%10"PRIu64" (%13"PRIu64")", cur_elapsed_nanos / (1000*1000), cur_elapsed_nanos); } uint64_t elapsed_nanos = end_nanos - program_start_timestamp; rpt_vstring(depth, "Total elapsed milliseconds (nanoseconds): %10"PRIu64" (%13"PRIu64")", elapsed_nanos / (1000*1000), elapsed_nanos); } void report_elapsed_summary(int depth) { uint64_t end_nanos = cur_realtime_nanosec(); uint64_t elapsed_nanos = end_nanos - program_start_timestamp; Non_Sleep_Call_Totals non_sleep_totals = get_non_sleep_call_totals (); Sleep_Stats sleep_totals = get_sleep_stats();; rpt_vstring(depth, "Total non sleep system call time: %10"PRIu64" milliseconds", non_sleep_totals.nanos / (1000*1000) ); rpt_vstring(depth, "Total sleep call time: %10"PRIu64" milliseconds", sleep_totals.actual_sleep_nanos / (1000*1000) ); rpt_vstring(depth, "Elapsed time: %10"PRIu64" milliseconds", elapsed_nanos / (1000*1000)); rpt_nl(); } /** Cleanup at program termination */ void terminate_execution_stats() { bool debug = false; DBGMSF(debug, "Starting"); free_status_code_counts(primary_error_code_counts); free_status_code_counts(retryable_error_code_counts); DBGMSF(debug, "Done"); } ddcutil-2.2.0/src/base/feature_lists.c0000644000175000001440000001423514441414365013351 /** @file feature_lists.c */ // Copyright (C) 2018=2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "feature_lists.h" #include #include #include #include #include #include "util/data_structures.h" #include "util/coredefs.h" #include "base/core.h" /* This file could be reimplemented using Bit_Set_256 which is an identical data structure. However, the reimplementable functions are largely trivial. Consider eliminating completely, calling Bit_Set_256 functions directly from api_metadata.c. */ typedef struct { char * feature_list_string_buf; int feature_list_buf_size; } Thread_Feature_Lists_Data; static Thread_Feature_Lists_Data * get_thread_data() { static GPrivate per_thread_data_key = G_PRIVATE_INIT(g_free); Thread_Feature_Lists_Data *thread_data = g_private_get(&per_thread_data_key); // GThread * this_thread = g_thread_self(); // printf("(%s) this_thread=%p, settings=%p\n", __func__, this_thread, settings); if (!thread_data) { thread_data = g_new0(Thread_Feature_Lists_Data, 1); g_private_set(&per_thread_data_key, thread_data); } // printf("(%s) Returning: %p\n", __func__, thread_data); return thread_data; } #ifdef FUTURE inline Bit_Set_256 flist_to_bs256(DDCA_Feature_List vcplist) { Bit_Set_256 result; memcpy(result.bytes,vcplist.bytes,32); return result; } #endif void feature_list_clear(DDCA_Feature_List* vcplist) { memset(vcplist->bytes, 0, 32); } void feature_list_add(DDCA_Feature_List * vcplist, uint8_t vcp_code) { int flagndx = vcp_code >> 3; int shiftct = vcp_code & 0x07; Byte flagbit = 0x01 << shiftct; // printf("(%s) val=0x%02x, flagndx=%d, shiftct=%d, flagbit=0x%02x\n", // __func__, val, flagndx, shiftct, flagbit); vcplist->bytes[flagndx] |= flagbit; } bool feature_list_contains(DDCA_Feature_List * vcplist, uint8_t vcp_code) { int flagndx = vcp_code >> 3; int shiftct = vcp_code & 0x07; Byte flagbit = 0x01 << shiftct; // printf("(%s) val=0x%02x, flagndx=%d, shiftct=%d, flagbit=0x%02x\n", // __func__, val, flagndx, shiftct, flagbit); bool result = vcplist->bytes[flagndx] & flagbit; #ifdef FUTURE bool result2 = bs256_contains( flist_to_bs256(*vcplist), vcp_code); assert(result == result2); #endif return result; } DDCA_Feature_List feature_list_or( DDCA_Feature_List* vcplist1, DDCA_Feature_List* vcplist2) { DDCA_Feature_List result; for (int ndx = 0; ndx < 32; ndx++) { result.bytes[ndx] = vcplist1->bytes[ndx] | vcplist2->bytes[ndx]; } return result; } DDCA_Feature_List feature_list_and( DDCA_Feature_List* vcplist1, DDCA_Feature_List* vcplist2) { DDCA_Feature_List result; for (int ndx = 0; ndx < 32; ndx++) { result.bytes[ndx] = vcplist1->bytes[ndx] & vcplist2->bytes[ndx]; } return result; } DDCA_Feature_List feature_list_and_not( DDCA_Feature_List* vcplist1, DDCA_Feature_List * vcplist2) { // DBGMSG("Starting. vcplist1=%p, vcplist2=%p", vcplist1, vcplist2); DDCA_Feature_List result; for (int ndx = 0; ndx < 32; ndx++) { result.bytes[ndx] = vcplist1->bytes[ndx] & ~vcplist2->bytes[ndx]; } // char * s = ddca_feature_list_string(&result, "0x",", "); // DBGMSG("Returning: %s", s); // free(s); return result; } int feature_list_count_old( DDCA_Feature_List * feature_list) { int result = 0; if (feature_list) { for (int ndx = 0; ndx < 256; ndx++) { if (feature_list_contains(feature_list, ndx)) result++; } } return result; } int feature_list_count( DDCA_Feature_List * feature_list) { // regard the array of 32 bytes as an array of 8 4-byte unsigned integers uint64_t * list2 = (uint64_t *) feature_list; unsigned int ct = 0; for (int ndx = 0; ndx < 4; ndx++) { // clever algorithm for counting number of bits per Brian Kernihgan uint64_t v = list2[ndx]; for (; v; ct++) { v &= v - 1; // clear the least significant bit set } // DBGMSG("feature_list_count() returning: %d", ct); } assert(ct == feature_list_count_old(feature_list)); return ct; } /** Returns a string representation of a #DDCA_Feature_List * * \param feature_list #DDCA_Feature_List value * \param value_prefix string to start each value e.g. "0x", "h", if NULL then "" * \param sepstr separator string between values, if NULL then "" * \return string representation * * \remark * The returned string is valid until the next call to this function in the * current thread. */ const char * feature_list_string( DDCA_Feature_List * feature_list, const char * value_prefix, const char * sepstr) { // DBGMSG("Starting. feature_list=%p, value_prefix=|%s|, sepstr=|%s|", // feature_list, value_prefix, sepstr); // rpt_hex_dump((Byte*)feature_list, 32, 2); Thread_Feature_Lists_Data * thread_data = get_thread_data(); char * buf = NULL; if (feature_list) { if (!value_prefix) value_prefix = ""; if (!sepstr) sepstr = ""; int vsize = strlen(value_prefix) + 2 + strlen(sepstr); int feature_ct = feature_list_count_old(feature_list); int reqd_size = (feature_ct*vsize)+1; // +1 for trailing null if (reqd_size > thread_data->feature_list_buf_size) { if (thread_data->feature_list_string_buf) free(thread_data->feature_list_string_buf); thread_data->feature_list_string_buf = malloc(reqd_size); thread_data->feature_list_buf_size = reqd_size; } buf = thread_data->feature_list_string_buf; buf[0] = '\0'; // DBGMSG("feature_ct=%d, vsize=%d, buf size = %d", feature_ct, vsize, vsize*feature_ct); for (int ndx = 0; ndx < 256; ndx++) { if (feature_list_contains(feature_list, ndx)) sprintf(buf + strlen(buf), "%s%02x%s", value_prefix, ndx, sepstr); } if (feature_ct > 0) buf[strlen(buf)-strlen(sepstr)] = '\0'; } // DBGMSG("Returned string length: %d", strlen(buf)); // DBGMSG("Returning %p - %s", buf, buf); return buf; } ddcutil-2.2.0/src/base/feature_metadata.c0000644000175000001440000005567514754153540014012 /* @file feature_metadata.c * * Functions for external and internal representation of * display-specific feature metadata. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include "util/debug_util.h" #include "util/glib_util.h" #include "util/report_util.h" /** \endcond */ #include "base/displays.h" #include "base/rtti.h" #include "base/vcp_version.h" #include "base/feature_metadata.h" #include "base/dynamic_features.h" // oops for dbgreport_feature_metadata() /** Thread safe function that returns a string representation of a #Nontable_Vcp_Value * suitable for diagnostic messages. The returned value is valid until the * next call to this function on the current thread. * * \param vcp_value pointer to #Nontable_Vcp_Value * \return string representation of value */ char * nontable_vcp_value_repr_t(Nontable_Vcp_Value * vcp_value) { static GPrivate nontable_value_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&nontable_value_repr_key, 100); if (vcp_value) g_snprintf(buf, 100, "Nontable_Vcp_Value[vcp_code: 0x%02x, max=%d, cur=%d, mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x]", vcp_value->vcp_code, vcp_value->max_value, vcp_value->cur_value, vcp_value->mh, vcp_value->ml, vcp_value->sh, vcp_value->sl); else strcpy(buf, "Nontable_Vcp_Value[NULL]"); return buf; } // Feature flags #ifdef UNUSED /** Creates a string representation of DDCA_Feature_Flags bitfield. * * @param flags feature characteristics * @return string representation, valid until the next call * of this function in the current thread, do not free * * @remark * Currently used only in debug code. (11/2018) */ char * interpret_feature_flags_t(DDCA_Version_Feature_Flags flags) { static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buffer = get_thread_fixed_buffer(&buf_key, 100); g_snprintf(buffer, 100, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", flags & DDCA_RO ? "Read-Only, " : "", flags & DDCA_WO ? "Write-Only, " : "", flags & DDCA_RW ? "Read-Write, " : "", flags & DDCA_STD_CONT ? "Continuous (standard), " : "", flags & DDCA_COMPLEX_CONT ? "Continuous (complex), " : "", flags & DDCA_SIMPLE_NC ? "Non-Continuous (simple), " : "", flags & DDCA_EXTENDED_NC ? "Non-Continuous (extended), " : "", flags & DDCA_COMPLEX_NC ? "Non-Continuous (complex), " : "", flags & DDCA_NC_CONT ? "Non-Continuous with continuous subrange, " :"", flags & DDCA_WO_NC ? "Non-Continuous (write-only), " : "", flags & DDCA_NORMAL_TABLE ? "Table (readable), " : "", flags & DDCA_WO_TABLE ? "Table (write-only), " : "", flags & DDCA_DEPRECATED ? "Deprecated, " : "", flags & DDCA_USER_DEFINED ? "User-defined, " : "", flags & DDCA_SYNTHETIC ? "Synthesized metadata, " : "", // Should never occur in DDCA_Version_Feature_Flags: flags & DDCA_PERSISTENT_METADATA ? "Persistent metadata, " : "", flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY ? "Synthesized VFTE, " : "" ); // remove final comma and blank if (strlen(buffer) > 0) buffer[strlen(buffer)-2] = '\0'; return buffer; } #endif /** Creates a string representation of DDCA_Feature_Flags bitfield. * * @param flags feature characteristics * @return string representation, valid until the next call * of this function in the current thread, do not free * * @remark * DDCA_Feature_Flags is a union (DDCA_Version_Feature_Flags,DDCA_Global_Feature_Flags) * All are defined as uint16_t, so this function can be used to interpret * DDCA_Version_Feature_Flags and DDCA_Global_Feature_Flags as well as * DDCA_Feature_Flags. */ const char * interpret_ddca_feature_flags_symbolic_t(DDCA_Feature_Flags flags) { bool debug = false; static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buffer = get_thread_fixed_buffer(&buf_key, 100); g_snprintf(buffer, 100, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", // Exactly 1 of the following should be set in DDCA_Version_Feature_Flags: flags & DDCA_RO ? "DDCA_RO|" : "", flags & DDCA_WO ? "DDCA_WO|" : "", flags & DDCA_RW ? "DDCA_RW|" : "", // Exactly 1 of the following should be set in DDCA_Version_Feature_Flags: flags & DDCA_STD_CONT ? "DDCA_STD_CONT|" : "", flags & DDCA_COMPLEX_CONT ? "DDCA_COMPLEX_CONT|" : "", flags & DDCA_SIMPLE_NC ? "DDCA_SIMPLE_NC|" : "", flags & DDCA_EXTENDED_NC ? "DDCA_EXTENDED_NC|" : "", flags & DDCA_COMPLEX_NC ? "DDCA_COMPLEX_NC|" : "", flags & DDCA_NC_CONT ? "DDCA_NC_CONT|" : "", flags & DDCA_WO_NC ? "DDCA_WO_CONT|" : "", flags & DDCA_NORMAL_TABLE ? "DDCA_NORMAL_TABLE|" : "", flags & DDCA_WO_TABLE ? "DDCA_WO_TABLE|" : "", flags & DDCA_DEPRECATED ? "DDCA_DEPRECATED|" : "", // Lifecycle in DDCA_Global_Feature_Flags: flags & DDCA_PERSISTENT_METADATA ? "DDCA_PERSISTENT_METADATA|" : "", flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY ? "DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY|" : "", // Provenance in DDCA_Global_Feature_Flags: flags & DDCA_USER_DEFINED ? "DDCA_USER_DEFINED|" : "", flags & DDCA_SYNTHETIC ? "DDCA_SYNTHESIZED|" : "" ); // remove final comma and blank if (strlen(buffer) > 0) buffer[strlen(buffer)-1] = '\0'; DBGF(debug, "flags=0x%04x, returning %s", flags, buffer); return buffer; } const char * interpret_ddca_global_feature_flags_symbolic_t(DDCA_Feature_Flags flags) { bool debug = false; static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buffer = get_thread_fixed_buffer(&buf_key, 100); g_snprintf(buffer, 100, "%s%s%s%s", // Lifecycle in DDCA_Global_Feature_Flags: flags & DDCA_PERSISTENT_METADATA ? "DDCA_PERSISTENT_METADATA|" : "", flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY ? "DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY|" : "", // Provenance in DDCA_Global_Feature_Flags: flags & DDCA_USER_DEFINED ? "DDCA_USER_DEFINED|" : "", flags & DDCA_SYNTHETIC ? "DDCA_SYNTHESIZED|" : "" ); // remove final comma and blank if (strlen(buffer) > 0) buffer[strlen(buffer)-1] = '\0'; DBGF(debug, "flags=0x%04x, returning %s", flags, buffer); return buffer; } const char * interpret_ddca_version_feature_flags_symbolic_t(DDCA_Feature_Flags flags) { bool debug = false; static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * buffer = get_thread_fixed_buffer(&buf_key, 100); g_snprintf(buffer, 100, "%s%s%s%s%s%s%s%s%s%s%s%s%s", // Exactly 1 of the following should be set in DDCA_Version_Feature_Flags: flags & DDCA_RO ? "DDCA_RO|" : "", flags & DDCA_WO ? "DDCA_WO|" : "", flags & DDCA_RW ? "DDCA_RW|" : "", // Exactly 1 of the following should be set in DDCA_Version_Feature_Flags: flags & DDCA_STD_CONT ? "DDCA_STD_CONT|" : "", flags & DDCA_COMPLEX_CONT ? "DDCA_COMPLEX_CONT|" : "", flags & DDCA_SIMPLE_NC ? "DDCA_SIMPLE_NC|" : "", flags & DDCA_EXTENDED_NC ? "DDCA_EXTENDED_NC|" : "", flags & DDCA_COMPLEX_NC ? "DDCA_COMPLEX_NC|" : "", flags & DDCA_NC_CONT ? "DDCA_NC_CONT|" : "", flags & DDCA_WO_NC ? "DDCA_WO_CONT|" : "", flags & DDCA_NORMAL_TABLE ? "DDCA_NORMAL_TABLE|" : "", flags & DDCA_WO_TABLE ? "DDCA_WO_TABLE|" : "", flags & DDCA_DEPRECATED ? "DDCA_DEPRECATED|" : "" ); // remove final comma and blank if (strlen(buffer) > 0) buffer[strlen(buffer)-1] = '\0'; DBGF(debug, "flags=0x%04x, returning %s", flags, buffer); return buffer; } // SL value tables /** Returns the number of entries in a feature value table, including the * final terminating entry. * * @param table feature value table * @return number of entries */ static int sl_value_table_size(DDCA_Feature_Value_Entry * table) { int ct = 0; if (table) { DDCA_Feature_Value_Entry * cur = table; while (true) { ct++; if (!cur->value_name) break; cur++; } } return ct; } /** Emit a debugging report of a feature value table. * * @param table pointer to first #DDCA_Feature_Value_Entry in table * @param title name of table * @param depth logical indentation depth */ void dbgrpt_sl_value_table(DDCA_Feature_Value_Entry * table, char * title, int depth) { int d1 = depth+1; if (table) { rpt_vstring(depth, "%s table at %p", title, table); if (table) { rpt_vstring(depth, "Members: "); DDCA_Feature_Value_Entry * cur = table; while (cur->value_name) { rpt_vstring(d1, "0x%02x -> %s", cur->value_code, cur->value_name); cur++; } } } else { rpt_vstring(depth, "%s table: NULL", title); } } #ifdef UNUSED_VARIANT void dbgrpt_sl_value_table_dup(DDCA_Feature_Value_Entry * table, int depth) { rpt_vstring(depth, "DDCA_Feature_Value_Table at %p", table); if (table) { DDCA_Feature_Value_Entry * cur = table; while (cur->value_code != 0x00 || cur->value_name) { rpt_vstring(depth+1, "0x%02x - %s", cur->value_code, cur->value_name); cur++; } } } #endif /** Make a deep copy of a feature value table * * @param oldtable pointer to first #DDCA_Feature_Value_Entry in table to copy * @return copied table. */ DDCA_Feature_Value_Entry * copy_sl_value_table(DDCA_Feature_Value_Entry * oldtable) { bool debug = false; DBGMSF(debug, "Starting. oldtable=%p, size=%d", oldtable, sl_value_table_size(oldtable)); DDCA_Feature_Value_Entry * newtable = NULL; if (oldtable) { int oldsize = sl_value_table_size(oldtable); newtable = calloc(oldsize, sizeof(DDCA_Feature_Value_Entry)); DDCA_Feature_Value_Entry * oldentry = oldtable; DDCA_Feature_Value_Entry * newentry = newtable; int ct = 0; while(true) { ct++; newentry->value_code = oldentry->value_code; if (oldentry->value_name) newentry->value_name = g_strdup(oldentry->value_name); else break; oldentry++; newentry++; }; DBGMSF(debug, "Copied %d entries, including terminating entry", ct); } DBGMSF(debug, "Done. Returning: %p", newtable); return newtable; } /** Free a feature value table. * * @param table pointer to first entry in table */ void free_sl_value_table(DDCA_Feature_Value_Entry * table) { bool debug = false; DBGMSF(debug, "Starting. table=%p", table); DBGMSF(debug, "table size = %d", sl_value_table_size(table)); if (table) { DDCA_Feature_Value_Entry * cur = table; while(true) { if (cur->value_name) { DBGMSF(debug, "Freeing: %p", cur->value_name); free(cur->value_name); } else break; cur++; } free(table); } DBGMSF(debug, "Done"); } /* Given a hex value to be interpreted and an array of value table entries, * return the explanation string for value. * * Arguments: * value_entries array of Feature_Value_Entry * value_id value to look up * * Returns: * explanation string from the Feature_Value_Entry found (do not free) * NULL if not found */ char * sl_value_table_lookup( DDCA_Feature_Value_Entry * value_entries, Byte value_id) { // DBGMSG("Starting. pvalues_for_feature=%p, value_id=0x%02x", pvalues_for_feature, value_id); char * result = NULL; DDCA_Feature_Value_Entry * cur_value = value_entries; while (cur_value->value_name != NULL) { // DBGMSG("value_code=0x%02x, value_name = %s", cur_value->value_code, cur_value->value_name); if (cur_value->value_code == value_id) { result = cur_value->value_name; // DBGMSG("Found"); break; } cur_value++; } return result; } /** Output a debug report of a #Dyn_Feature_Metadata instance * * @param md instance to report * @param depth logical indentation depth */ void dbgrpt_dyn_feature_metadata( Dyn_Feature_Metadata * md, int depth) { int d0 = depth; int d1 = depth+1; rpt_structure_loc("Dyn_Feature_Metadata", md, depth); rpt_vstring(d0, "Feature code: 0x%02x", md->feature_code); rpt_vstring(d1, "MCCS version: %d.%d", md->vcp_version.major, md->vcp_version.minor); rpt_vstring(d1, "Feature name: %s", md->feature_name); rpt_vstring(d1, "Description: %s", md->feature_desc); rpt_vstring(d1, "Global feature flags: 0x%04x", md->global_feature_flags); rpt_vstring(d1, "Interpreted global feature flags: %s", interpret_ddca_global_feature_flags_symbolic_t(md->global_feature_flags)); rpt_vstring(d1, "Version feature flags: 0x%04x", md->version_feature_flags); rpt_vstring(d1, "Interpreted version feature flags: %s", interpret_ddca_version_feature_flags_symbolic_t(md->version_feature_flags)); dbgrpt_sl_value_table(md->sl_values, "Feature values", d1); } // // Display_Feature_Metadata (used internally) // /** Emits a debug report on a #Display_Feature_Metadata instance. * The report is written to the current report destination. * * @param meta pointer to instance * @param depth logical indentation depth */ void dbgrpt_display_feature_metadata( Display_Feature_Metadata * meta, int depth) { rpt_vstring(depth, "Display_Feature_Metadata at %p", meta); if (meta) { assert(memcmp(meta->marker, DISPLAY_FEATURE_METADATA_MARKER, 4) == 0); int d1 = depth+1; rpt_vstring(d1, "display_ref: %s", dref_repr_t(meta->display_ref)); rpt_vstring(d1, "feature_code: 0x%02x", meta->feature_code); rpt_vstring(d1, "vcp_version: %d.%d = %s", meta->vcp_version.major, meta->vcp_version.minor, format_vspec(meta->vcp_version)); rpt_vstring(d1, "feature_name: %s", meta->feature_name); rpt_vstring(d1, "feature_desc: %s", meta->feature_desc); const char * s = interpret_ddca_global_feature_flags_symbolic_t(meta->global_feature_flags); rpt_vstring(d1, "global flags: 0x%04x = %s", meta->global_feature_flags, s); const char * t = interpret_ddca_version_feature_flags_symbolic_t(meta->version_feature_flags); rpt_vstring(d1, "version flags: 0x%04x = %s", meta->version_feature_flags, t); dbgrpt_sl_value_table(meta->sl_values, "Feature values", d1); rpt_vstring(d1, "nontable_formatter: %p - %s", meta->nontable_formatter, rtti_get_func_name_by_addr(meta->nontable_formatter)) ; rpt_vstring(d1, "nontable_formatter_sl: %p - %s", meta->nontable_formatter_sl, rtti_get_func_name_by_addr(meta->nontable_formatter_sl)); rpt_vstring(d1, "nontable_formatter_universal: %p - %s", meta->nontable_formatter_universal, rtti_get_func_name_by_addr(meta->nontable_formatter_universal)) ; // the future rpt_vstring(d1, "table_formatter: %p - %s", meta->table_formatter, rtti_get_func_name_by_addr(meta->table_formatter)); } } /** Frees a #Display_Feature_Metadata instance. * * @param meta pointer to instance */ void dfm_free( Display_Feature_Metadata * meta) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_VCP, "meta=%p", meta); // if (debug) // dbgrpt_display_feature_metadata(meta, 2); if (meta) { DBGTRC_NOPREFIX(debug, DDCA_TRC_VCP, "feature_code = 0x%02x", meta->feature_code); assert(memcmp(meta->marker, DISPLAY_FEATURE_METADATA_MARKER, 4) == 0); meta->marker[3] = 'x'; free(meta->feature_name); free(meta->feature_desc); free_sl_value_table(meta->sl_values); free(meta); } DBGTRC_DONE(debug, DDCA_TRC_VCP, ""); } /** Common allocation and basic initialization for #Display_Feature_Metadata. * * @param feature_code * @return newly allocated #Display_Feature_Metadata * * @remark sets marker and feature_code fields, all other fields to 0 */ Display_Feature_Metadata * dfm_new( DDCA_Vcp_Feature_Code feature_code) { Display_Feature_Metadata * result = calloc(1, sizeof(Display_Feature_Metadata)); memcpy(result->marker, DISPLAY_FEATURE_METADATA_MARKER, 4); result->feature_code = feature_code; return result; } #ifdef UNUSED void dfm_set_feature_name(Display_Feature_Metadata * meta, const char * feature_name) { assert(meta); if (meta->feature_name) free(meta->feature_name); meta->feature_name = g_strdup(feature_name); } void dfm_set_feature_desc(Display_Feature_Metadata * meta, const char * feature_desc) { assert(meta); if (meta->feature_desc) free(meta->feature_desc); meta->feature_desc = g_strdup(feature_desc); } #endif /** Converts a #Dyn_Feature_Metadata record, representing user supplied * metadata, to a #Display_Feature_Metadata. * * @param dyn_meta instance to convert * @result newly created #Display_Feature_Metadata * * @remark * It is the responsibility of the caller to free the returned instance */ Display_Feature_Metadata * dfm_from_dyn_feature_metadata( Dyn_Feature_Metadata * dyn_meta) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "ddc_meta=%p", dyn_meta); assert(dyn_meta); assert(memcmp(dyn_meta->marker, DDCA_FEATURE_METADATA_MARKER, 4) == 0); if (debug) dbgrpt_dyn_feature_metadata(dyn_meta, 2); Display_Feature_Metadata * dfm = dfm_new(dyn_meta->feature_code); dfm->display_ref = NULL; dfm->feature_desc = (dyn_meta->feature_desc) ? g_strdup(dyn_meta->feature_desc) : NULL; dfm->feature_name = (dyn_meta->feature_name) ? g_strdup(dyn_meta->feature_name) : NULL; // ensure global flag values also defined as version flag values are not used: assert(!(dyn_meta->global_feature_flags & DDCA_SYNTHETIC)); assert(!(dyn_meta->global_feature_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY)); assert(dyn_meta->global_feature_flags & DDCA_USER_DEFINED); assert(dyn_meta->global_feature_flags & DDCA_PERSISTENT_METADATA); dfm->global_feature_flags = dyn_meta->global_feature_flags; dfm->version_feature_flags = dyn_meta->version_feature_flags; dfm->nontable_formatter = NULL; dfm->nontable_formatter_sl = NULL; dfm->table_formatter = NULL; dfm->vcp_version = DDCA_VSPEC_UNQUERIED; dfm->sl_values = copy_sl_value_table(dyn_meta->sl_values); // dfm->latest_sl_values = copy_sl_value_table(ddca_meta->latest_sl_values); if (debug) dbgrpt_display_feature_metadata(dfm, 2); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning dfm=%p", dfm); return dfm; } // // External DDCA_Feature_Metadata // /** Output a debug report of a #DDCA_Feature_Metadata instance * * @param md instance to report * @param depth logical indentation depth */ void dbgrpt_ddca_feature_metadata( DDCA_Feature_Metadata * md, int depth) { int d0 = depth; int d1 = depth+1; rpt_structure_loc("DDCA_Feature_Metadata", md, depth); rpt_vstring(d0, "Feature code: 0x%02x", md->feature_code); rpt_vstring(d1, "MCCS version: %d.%d", md->vcp_version.major, md->vcp_version.minor); rpt_vstring(d1, "Feature name: %s", md->feature_name); rpt_vstring(d1, "Description: %s", md->feature_desc); rpt_vstring(d1, "Feature flags: 0x%04x", md->feature_flags); rpt_vstring(d1, "Interpreted flags: %s", interpret_ddca_feature_flags_symbolic_t(md->feature_flags)); dbgrpt_sl_value_table(md->sl_values, "Feature values", d1); } /** Converts a #Display_Feature_Metadata to a DDCA_Feature_Metadata * * @param ddca_meta instance to convert * @result newly created #DDCA_Feature_Metadata * * @remark * It is the responsibility of the caller to free the returned instance */ DDCA_Feature_Metadata * dfm_to_ddca_feature_metadata( Display_Feature_Metadata * dfm) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dfm=%p", dfm); if (debug) dbgrpt_display_feature_metadata(dfm, 2); DDCA_Feature_Metadata * ddca_meta = calloc(1, sizeof(DDCA_Feature_Metadata)); memcpy(ddca_meta->marker, DDCA_FEATURE_METADATA_MARKER, 4); ddca_meta->feature_code = dfm->feature_code; ddca_meta->vcp_version = dfm->vcp_version; ddca_meta->feature_flags = dfm->version_feature_flags; if (dfm->global_feature_flags & DDCA_PERSISTENT_METADATA) ddca_meta->feature_flags |= DDCA_PERSISTENT_METADATA; // ddca_meta->feature_flags &= ~DDCA_PERSISTENT_METADATA; // ddca_meta->feature_flags &= ~DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY; ddca_meta->feature_name = (dfm->feature_name) ? g_strdup(dfm->feature_name) : NULL; ddca_meta->feature_desc = (dfm->feature_desc) ? g_strdup(dfm->feature_desc) : NULL; DBGMSF(debug, "** dfm->sl_values = %p", dfm->sl_values); ddca_meta->sl_values = copy_sl_value_table(dfm->sl_values); DBGTRC_RET_STRUCT(debug, DDCA_TRC_NONE, DDCA_Feature_Metadata, dbgrpt_ddca_feature_metadata, ddca_meta); return ddca_meta; } /** Frees a #DDCA_Feature_Metadata instance. * * @param metadata pointer to instance */ void free_ddca_feature_metadata(DDCA_Feature_Metadata * metadata) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_VCP, "metadata = %p", metadata); if ( metadata && memcmp(metadata->marker, DDCA_FEATURE_METADATA_MARKER, 4) == 0) { if (debug) dbgrpt_ddca_feature_metadata(metadata, 2); DBGTRC_NOPREFIX(debug, DDCA_TRC_VCP, "feature_code=0x%02x, DDCA_PERSISTENT_METADATA set: %s", metadata->feature_code, sbool(metadata->feature_flags & DDCA_PERSISTENT_METADATA)); assert(!(metadata->feature_flags & DDCA_PERSISTENT_METADATA)); free(metadata->feature_name); free(metadata->feature_desc); free_sl_value_table(metadata->sl_values); metadata->marker[3] = 'x'; } DBGTRC_DONE(debug, DDCA_TRC_VCP, ""); } void init_feature_metadata() { RTTI_ADD_FUNC(dfm_free); RTTI_ADD_FUNC(dfm_from_dyn_feature_metadata); RTTI_ADD_FUNC(dfm_to_ddca_feature_metadata); } ddcutil-2.2.0/src/base/feature_set_ref.c0000644000175000001440000001324214754153540013641 /* \file feature_sets.c * * Feature set identifiers */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include "util/data_structures.h" #include "util/report_util.h" #include "util/string_util.h" /** \endcond */ #include "base/core.h" #include "feature_set_ref.h" // // VCP_Feature_Subset utilities // Value_Name_Table vcp_subset_table = { // ddcutil defined groups VNT(VCP_SUBSET_PROFILE, "PROFILE"), VNT(VCP_SUBSET_COLOR, "COLOR"), VNT(VCP_SUBSET_LUT, "LUT"), // MCCS defined groups VNT(VCP_SUBSET_CRT, "CRT"), VNT(VCP_SUBSET_TV, "TV"), VNT(VCP_SUBSET_AUDIO, "AUDIO"), VNT(VCP_SUBSET_WINDOW, "WINDOW"), VNT(VCP_SUBSET_DPVL, "DPVL"), VNT(VCP_SUBSET_PRESET, "PRESET"), // by feature type VNT(VCP_SUBSET_TABLE, "TABLE"), VNT(VCP_SUBSET_SCONT, "SCONT"), VNT(VCP_SUBSET_CCONT, "CCONT"), VNT(VCP_SUBSET_CONT, "CONT"), VNT(VCP_SUBSET_SNC, "SNC"), VNT(VCP_SUBSET_XNC, "XNC"), VNT(VCP_SUBSET_CNC, "CNC"), VNT(VCP_SUBSET_NC, "NC"), VNT(VCP_SUBSET_NC_WO, "NC_WO"), VNT(VCP_SUBSET_NC_CONT, "NC_CONT"), // special handling VNT(VCP_SUBSET_SCAN, "SCAN"), // VNT(VCP_SUBSET_ALL, NULL), // VNT(VCP_SUBSET_SUPPORTED, "SUPPORTED"), VNT(VCP_SUBSET_KNOWN, "KNOWN"), VNT(VCP_SUBSET_MFG, "MFG"), VNT(VCP_SUBSET_UDF, "UDF"), VNT(VCP_SUBSET_SINGLE_FEATURE, NULL), VNT(VCP_SUBSET_MULTI_FEATURES, NULL), VNT(VCP_SUBSET_NONE, NULL), VNT_END }; const int vcp_subset_count = ARRAY_SIZE(vcp_subset_table) - 1; /** Given a #VCP_Feature_Subset id, return its symbolic name. * * @param subset_id * @param subset symbolic name, do not free */ char * feature_subset_name(VCP_Feature_Subset subset_id) { return vnt_name(vcp_subset_table, subset_id); } /** Returns a comma separated list of external subset names for a set of subset ids. * The returned value is valid until the next call to this * function in the current thread. * * @param subset_ids * @return comma delimited list, do not free */ char * feature_subset_names(VCP_Feature_Subset subset_ids) { GString * buf = g_string_sized_new(100); bool first = true; for(int kk=0; kk < vcp_subset_count; kk++) { Value_Name_Title cur_desc = vcp_subset_table[kk]; if (subset_ids & cur_desc.value) { if (first) first = false; else g_string_append(buf, ", "); g_string_append(buf, (cur_desc.title) ? cur_desc.title : cur_desc.name); } } char * result = buf->str; g_string_free(buf, false); return result; } /** Outputs a debug report of #Feature_Set_Ref instance * * @param fsref feature set reference * @param depth logical indentation depth */ void dbgrpt_feature_set_ref(Feature_Set_Ref * fsref, int depth) { rpt_vstring(depth, "subset: %s (%d)", feature_subset_name(fsref->subset), fsref->subset); // rpt_vstring(depth, "specific_feature: 0x%02x", fsref->specific_feature); rpt_vstring(depth, "multi features: %s", bs256_to_string_t(fsref->features, "x", " ")); } /** Returns a representation of #Feature_Set_Ref. * The returned value is valid until the next call to this function in the current thread. * * @param fsref feature set reference * @return string description, do not free */ char * fsref_repr_t(Feature_Set_Ref * fsref) { static GPrivate fsref_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&fsref_repr_key, 200); if (fsref->subset == VCP_SUBSET_SINGLE_FEATURE) snprintf(buf, 200, "[VCP_SUBSET_SINGLE_FEATURE, 0x%02x]", // fsref->specific_feature); bs256_first_bit_set(fsref->features)); else if (fsref->subset == VCP_SUBSET_MULTI_FEATURES) snprintf(buf, 200, "[VCP_SUBSET_MULTI_FEATURES, %s]", bs256_to_string_t(fsref->features, "x", " ")); else snprintf(buf, 200, "[%s]", feature_subset_name(fsref->subset)); return buf; } static Value_Name_Title_Table feature_set_flag_table = { #ifdef UNUSED VNT(FSF_FORCE, "force"), #endif VNT(FSF_SHOW_UNSUPPORTED, "report unsupported features"), VNT(FSF_NOTABLE, "do not report table features"), VNT(FSF_RW_ONLY, "include only RW features"), VNT(FSF_RO_ONLY, "include only RO features"), VNT(FSF_WO_ONLY, "include only WO features"), VNT(FSF_CHECK_UDF, "use user-defined feature definitions"), VNT_END }; const int feature_set_flag_ct = ARRAY_SIZE(feature_set_flag_table)-1; /* Returns a string representation containing the symbolic names of the * flags in a #Feature_Set_Flags instance. * The returned value is valid until the next call to this function in the current thread. * * @param flags feature set flags * @return string description, do not free */ char * feature_set_flag_names_t(Feature_Set_Flags flags) { static GPrivate feature_set_flag_names_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&feature_set_flag_names_key, 100); char * s = vnt_interpret_flags( flags, feature_set_flag_table, false, // use value name, not description "|"); // sepstr STRLCPY(buf, s, 100); free(s); return buf; } ddcutil-2.2.0/src/base/flock.c0000644000175000001440000002670414754153540011604 /** @file flock.c */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "public/ddcutil_types.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/edid.h" #include "util/file_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/timestamp.h" #include "util/traced_function_stack.h" #include "base/core.h" #include "base/parms.h" #include "base/rtti.h" #include "base/status_code_mgt.h" #ifdef EXPERIMENTAL_FLOCK_RECOVERY #include "i2c/i2c_edid.h" // violates layering #include "i2c/i2c_execute.h" #endif #include "base/flock.h" static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_BASE; bool cross_instance_locks_enabled = DEFAULT_ENABLE_FLOCK; int flock_poll_millisec = DEFAULT_FLOCK_POLL_MILLISEC; int flock_max_wait_millisec = DEFAULT_FLOCK_MAX_WAIT_MILLISEC; bool debug_flock = false; void i2c_enable_cross_instance_locks(bool yesno) { bool debug = false; cross_instance_locks_enabled = yesno; DBGTRC_EXECUTED(debug, TRACE_GROUP, "yesno = %s", SBOOL(yesno)); } // // Debugging Functions // void show_flock(const char * filename, bool dest_syslog) { if (dest_syslog) start_capture(DDCA_CAPTURE_NOOPTS); int inode = get_inode_by_fn(filename); rpt_vstring(1, "Processes locking %s (inode %d): ", filename, inode); char cmd[80]; g_snprintf(cmd, 80, "cat /proc/locks | cut -d' ' -f'7 8' | grep 00:05:%d | cut -d' ' -f'1'", inode); execute_shell_cmd_rpt(cmd, 1); // *** TEMP *** GPtrArray * pids = execute_shell_cmd_collect(cmd); for (int ndx = 0; ndx < pids->len; ndx++) { char * spid = g_ptr_array_index(pids, ndx); rpt_vstring(2, "%s", spid); g_snprintf(cmd, 80, "cat /proc/%s/status | grep -E -e Name -e State -e '^Pid:'", spid); execute_shell_cmd_rpt(cmd, 1); // *** TEMP *** GPtrArray * status_lines = execute_shell_cmd_collect(cmd); for (int k = 0; k < status_lines->len; k ++) { rpt_vstring(2, "%s", (char*) g_ptr_array_index(status_lines, k)); } rpt_nl(); g_ptr_array_free(status_lines, true); } g_ptr_array_free(pids,true); if (dest_syslog) { Null_Terminated_String_Array ntsa = end_capture_as_ntsa(); for (int ndx = 0; ntsa[ndx]; ndx++) { char * s = ntsa[ndx]; SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", s); s++; } ntsa_free(ntsa, true); } } void show_lsof(const char * filename) { MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "Programs holding %s open:", filename); rpt_lsof(filename, 1); char cmd[80]; g_snprintf(cmd, 80, "lsof %s", filename); GPtrArray* lsof_lines = execute_shell_cmd_collect(cmd); for (int ndx = 0; ndx < lsof_lines->len; ndx++) { MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, " %s", (char*) g_ptr_array_index(lsof_lines, ndx)); } g_ptr_array_free(lsof_lines, true); } void explore_flock(int fd, const char * filename) { int inode = get_inode_by_fd(fd); intmax_t pid = get_process_id(); DBGMSG("pid=%jd filename = %s, inode=%d", pid, filename, inode); execute_shell_cmd_rpt("lslocks|grep /dev/i2c", 1); char cmd[80]; // g_snprintf(cmd, 80, "cat /proc/locks | cut -d' ' -f'7 8' | grep 00:05:%d", inode); // execute_shell_cmd_rpt(cmd, 1); g_snprintf(cmd, 80, "cat /proc/locks | cut -d' ' -f'7 8' | grep 00:05:%d | cut -d' ' -f'1'", inode); execute_shell_cmd_rpt(cmd, 1); GPtrArray * pids_locking_inode = execute_shell_cmd_collect(cmd); rpt_vstring(1, "Processing locking inode %jd:", inode); for (int ndx = 0; ndx < pids_locking_inode->len; ndx++) { // cast to avoid coverity warning: rpt_vstring(2, "%s", (char*) g_ptr_array_index(pids_locking_inode, ndx)); } // g_snprintf(cmd, 80, "ls /proc/%jd", pid); // execute_shell_cmd_rpt(cmd, 1); // g_snprintf(cmd, 80, "cat /proc/%jd/cmdline", pid); // execute_shell_cmd_rpt(cmd, 1); g_snprintf(cmd, 80, "cat /proc/%jd/status | grep -E -e Name -e State -e '^Pid:'", pid); execute_shell_cmd_rpt(cmd, 1); GPtrArray * pids = execute_shell_cmd_collect(cmd); for (int ndx = 0; ndx < pids->len; ndx++) { //* case avoids coverity warning rpt_vstring(3, "%s", (char *) g_ptr_array_index(pids, ndx)); } } #ifdef EXPERIMENTAL_FLOCK_RECOVERY static bool simple_ioctl_read_edid_by_fd( int fd, int read_size, bool write_before_read, int depth) { bool debug = true; DBGMSF(debug, "Starting. fd=%d, filename=%s, read_size=%d, write_before_read=%s", fd, filename_for_fd_t(fd), read_size, sbool(write_before_read)); assert(read_size == 128 || read_size == 256); rpt_nl(); rpt_vstring(depth, "Attempting simple %d byte EDID read, fd=%d, %s initial write", read_size, fd, (write_before_read) ? "WITH" : "WITHOUT" ); Byte * edid_buf = calloc(1, 256); int rc = 0; bool ok = false; if (write_before_read) { edid_buf[0] = 0x00; rc = i2c_ioctl_writer(fd, 0x50, 1, edid_buf); if (rc < 0) { rpt_vstring(depth, "write of 1 byte failed, errno = %s", linux_errno_desc(errno)); rpt_label(depth, "Continuing"); } } DBGMSF(debug, "Calling i2c_ioctl_reader(), read_bytewise=false, read_size=%d, edid_buf=%p", read_size, edid_buf); rc = i2c_ioctl_reader(fd, 0x50, false, read_size, edid_buf); if (rc < 0) { rpt_vstring(depth,"read failed. errno = %s", linux_errno_desc(errno)); } else { rpt_hex_dump(edid_buf, read_size, depth+1); ok = true; } free(edid_buf); DBGMSF(debug, "Returning: %s", sbool(ok)); return ok; } #endif Status_Errno flock_lock_by_fd(int fd, const char * filename, bool wait) { assert(filename); bool debug = false; debug = debug || debug_flock; #ifdef EXPERIMENTAL_FLOCK_RECOVERY debug = debug || streq(filename,"/devi2c-25"); #endif DBGTRC_STARTING(debug, DDCA_TRC_BASE, "fd=%d, filename=%s, wait=%s", fd, filename, SBOOL(wait)); // int inode = get_inode_by_fn(filename); // int inode2 = get_inode_by_fd(fd); // assert(inode == inode2); int operation = LOCK_EX|LOCK_NB; int total_wait_millisec = 0; uint64_t max_wait_millisec = (wait) ? flock_max_wait_millisec : 0; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "flock_poll_millisec=%jd, flock_max_wait_millisec=%jd ", flock_poll_millisec, flock_max_wait_millisec); Status_Errno flockrc = 0; int flock_call_ctr = 0; while(true) { DBGTRC_NOPREFIX(debug||debug_flock, DDCA_TRC_NONE, "Calling flock(%d,0x%04x), filename=%s flock_call_ctr=%d, total_wait_millisec %d...", fd, operation, filename, flock_call_ctr, total_wait_millisec); flock_call_ctr++; flockrc = flock(fd, operation); if (flockrc == 0) { DBGTRC_NOPREFIX(debug || debug_flock /* || (flock_call_ctr > 1 && debug_flock) */, DDCA_TRC_NONE, "flock succeeded, filename=%s, flock_call_ctr=%d", filename, flock_call_ctr); #ifdef EXPLORING explore_flock(fd, filename); #endif break; } // flockrc == 0 // handle failure // n.b. lock will fail w EAGAIN if at least NEC display turned off assert(flockrc == -1); int errsv = errno; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "filename=%s, flock_call_ctr=%d, flock() returned: %s", filename, flock_call_ctr, psc_desc(-errsv)); if (total_wait_millisec > max_wait_millisec) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Max wait time %"PRIu64" milliseconds exceeded after %d flock() calls", max_wait_millisec, flock_call_ctr); SYSLOG2(DDCA_SYSLOG_ERROR, "Max wait time %"PRIu64" milliseconds exceeded after %d flock() calls", max_wait_millisec, flock_call_ctr); flockrc = DDCRC_FLOCKED; break; } if (errsv != EWOULDBLOCK ) { // n. EWOULDBLOCK == EAGAIN DBGTRC_NOPREFIX(true, TRACE_GROUP, "Unexpected error from flock() for %s: %s", filename, psc_desc(-errsv)); flockrc = -errsv; break; } #ifdef EXPERIMENTAL_FLOCK_RECOVERY if (errsv == EWOULDBLOCK) { Buffer * edidbuf = buffer_new(256, ""); Status_Errno_DDC rc = i2c_get_raw_edid_by_fd(fd, edidbuf); bool found_edid = (rc == 0); buffer_free(edidbuf, ""); DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "able to read edid directly: %s", sbool(found_edid)); // TODO: read attributes // RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", dh->dref-> simple_ioctl_read_edid_by_fd(fd, 256, // read size true, //write before read 2); // depth } #endif DBGTRC_NOPREFIX(debug || debug_flock, DDCA_TRC_NONE, "Resource locked. filename=%s, flock_call_ctr=%d, Sleeping", filename, flock_call_ctr); // if (flock_call_ctr == 1) // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "%s locked. Retrying...", filename); usleep(flock_poll_millisec*1000); total_wait_millisec += flock_poll_millisec; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "end of polling loop. flockrc = %d", flockrc); // DBGMSG("Testing Flock diagnostics:"); // show_flock(filename, true); if (flockrc == 0) { if (flock_call_ctr == 1) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "flock() for %s succeeded after %d calls", filename, flock_call_ctr); // floods syslog: // SYSLOG2(DDCA_SYSLOG_DEBUG, "flock() for %s succeeded after %d calls", filename, flock_call_ctr); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "flock() for %s succeeded after %d calls", filename, flock_call_ctr); SYSLOG2(DDCA_SYSLOG_NOTICE, "flock() for %s succeeded after %d calls", filename, flock_call_ctr); } } else { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "flock() for %s failed on %d calls", filename, flock_call_ctr); if (IS_DBGTRC(true, DDCA_TRC_NONE)) { DBGMSG("Flock diagnostics:"); show_flock(filename, false); show_backtrace(0); debug_current_traced_function_stack(/*reverse*/ false); current_traced_function_stack_to_syslog(DDCA_SYSLOG_ERROR, /*reverse=*/ false); } SYSLOG2(DDCA_SYSLOG_ERROR, "flock() for %s failed on %d calls", filename, flock_call_ctr); SYSLOG2(DDCA_SYSLOG_NOTICE, "Flock diagnostics:"); show_flock(filename, true); backtrace_to_syslog(LOG_ERR, 0); } DBGTRC_RET_DDCRC(debug, DDCA_TRC_BASE,flockrc, "filename=%s", filename); return flockrc; } Status_Errno flock_unlock_by_fd(int fd) { bool debug = false; debug = debug || debug_flock; DBGTRC_STARTING(debug, DDCA_TRC_BASE, "fd=%d, filename=%s", fd, filename_for_fd_t(fd)); int result = 0; assert(cross_instance_locks_enabled); DBGTRC_NOPREFIX(debug || debug_flock, TRACE_GROUP, "Calling flock(%d,LOCK_UN) filename=%s...", fd, filename_for_fd_t(fd)); int rc = flock(fd, LOCK_UN); if (rc < 0) { result = errno; DBGTRC_NOPREFIX(true, TRACE_GROUP, "Unexpected error from flock(..,LOCK_UN): %s", psc_desc(-result)); } DBGTRC_RET_DDCRC(debug, DDCA_TRC_BASE, result, "filename=%s", filename_for_fd_t(fd)); return result; } void init_flock() { RTTI_ADD_FUNC(flock_lock_by_fd); RTTI_ADD_FUNC(flock_unlock_by_fd); } ddcutil-2.2.0/src/base/i2c_bus_base.c0000644000175000001440000006443614754153540013032 /** @file i2c_bus_base.c */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "config.h" #include "util/coredefs.h" #include "util/debug_util.h" #include "util/edid.h" #include "public/ddcutil_types.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #include "util/timestamp.h" #include "util/traced_function_stack.h" #include "core.h" #include "rtti.h" #include "i2c_bus_base.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_I2C; GPtrArray * all_i2c_buses = NULL; /// array of #I2C_Bus_Info bool use_x37_detection_table = false; static GMutex all_i2c_buses_mutex; bool primitive_sysfs = false; // // Local utility functions // // Keep in sync with definitions in i2c_bus_base.h Value_Name_Table i2c_bus_flags_table = { VN(I2C_BUS_EXISTS), VN(I2C_BUS_ACCESSIBLE), // VN(I2C_BUS_ADDR_0X50), VN(I2C_BUS_ADDR_X37), VN(I2C_BUS_ADDR_X30), // VN(I2C_BUS_EDP), // VN(I2C_BUS_LVDS), VN(I2C_BUS_PROBED), // VN(I2C_BUS_VALID_NAME_CHECKED), // VN(I2C_BUS_HAS_VALID_NAME), VN(I2C_BUS_SYSFS_EDID), VN(I2C_BUS_X50_EDID), // VN(I2C_BUS_DRM_CONNECTOR_CHECKED), VN(I2C_BUS_LVDS_OR_EDP), VN(I2C_BUS_APPARENT_LAPTOP), VN(I2C_BUS_DISPLAYLINK), #ifdef OLD VN(I2C_BUS_SYSFS_UNRELIABLE), #endif VN(I2C_BUS_INITIAL_CHECK_DONE), VN(I2C_BUS_DDC_DISABLED), VN(I2C_BUS_DDC_CHECKS_IGNORABLE), VN(I2C_BUS_SYSFS_KNOWN_RELIABLE), VN_END }; /** Creates a string interpretation of I2C_Bus_Info.flags. * * @param flags flags value * @return string interpretation, caller must free */ char * i2c_interpret_bus_flags(uint16_t flags) { return VN_INTERPRET_FLAGS(flags, i2c_bus_flags_table, " | "); } /** Creates a string interpretation of I2C_Bus_Info.flags. * * @param flags flags value * @return string interpretation * * The string returned is valid until the next call to this function in * the current thread. It must not be free'd by the caller. */ char * i2c_interpret_bus_flags_t(uint16_t flags) { return VN_INTERPRET_FLAGS_T(flags, i2c_bus_flags_table, " | "); } const char * drm_connector_found_by_name(Drm_Connector_Found_By found_by) { char * result = NULL; switch(found_by) { case DRM_CONNECTOR_NOT_CHECKED: result = "DRM_CONNECTOR_NOT_CHECKED"; break; case DRM_CONNECTOR_NOT_FOUND: result = "DRM_CONNECTOR_NOT_FOUND"; break; case DRM_CONNECTOR_FOUND_BY_BUSNO: result = "DRM_CONNECTOR_FOUND_BY_BUSNO"; break; case DRM_CONNECTOR_FOUND_BY_EDID: result = "DRM_CONNECTOR_FOUND_BY_EDID"; break; } return result; } /** Retrieves the value of a text attribute (e.g. enabled) in the SYSFS * DRM connector directory for an I2C bus. * * @param businfo * @param attribute attribute name * @return attribute value, or NULL if not a DRM display * * Caller is responsible for freeing the returned value */ char * i2c_get_drm_connector_attribute(const I2C_Bus_Info * businfo, const char * attribute) { assert(businfo); // assert(businfo->flags & I2C_BUS_DRM_CONNECTOR_CHECKED); assert(businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_CHECKED); char * result = NULL; if (businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_FOUND) { assert(businfo->drm_connector_name); RPT_ATTR_TEXT(-1, &result, "/sys/class/drm", businfo->drm_connector_name, attribute); } return result; } void i2c_remove_bus_by_busno(int busno) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d", busno); assert(busno); g_mutex_lock(&all_i2c_buses_mutex); int busNdx = i2c_find_bus_info_index_in_gptrarray_by_busno(all_i2c_buses, busno); if (busNdx < 0) { MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "Record for busno %d not found in all_i2c_buses array", busno); } else { I2C_Bus_Info * businfo = g_ptr_array_remove_index(all_i2c_buses, busNdx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "businfo=%p", businfo); // not needed, i2c_free_bus_info() is free func for all_i2c_buses // i2c_free_bus_info(businfo); } g_mutex_unlock(&all_i2c_buses_mutex); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // called if display removed, bus may or may not still exist void i2c_reset_bus_info(I2C_Bus_Info * businfo) { bool debug = false; assert(businfo); DBGTRC_STARTING(debug, TRACE_GROUP, "businfo=%p, busno = %d, flags=%s", businfo, businfo->busno, i2c_interpret_bus_flags_t(businfo->flags)); if (debug) { show_backtrace(1); } if (i2c_device_exists(businfo->busno)) { //businfo->flags &= ~(I2C_BUS_ACCESSIBLE | I2C_BUS_ADDR_X30 | I2C_BUS_ADDR_X37 | // I2C_BUS_SYSFS_EDID | I2C_BUS_X50_EDID ); businfo->flags = 0; } if (businfo->edid) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Calling free_parsed_edid for %p, marker=%s", businfo->edid, hexstring_t((Byte*) businfo->marker, 4)); SYSLOG2(DDCA_SYSLOG_DEBUG, "Calling free_parsed_edid for %p, marker=%s", businfo->edid, hexstring_t((Byte*) businfo->marker,4)); free_parsed_edid(businfo->edid); businfo->edid = NULL; } // free(businfo->drm_connector_name); // double free if ( IS_DBGTRC(debug, TRACE_GROUP) ) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Final businfo:"); i2c_dbgrpt_bus_info(businfo, true, 2); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } char * i2c_get_drm_connector_name(I2C_Bus_Info * businfo) { bool debug = false; char * result = NULL; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, drm_connector_found_by=%s drm_connector_name=|%s|", businfo->busno, drm_connector_found_by_name(businfo->drm_connector_found_by), businfo->drm_connector_name); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "flags: %s", i2c_interpret_bus_flags_t(businfo->flags) ); // if (!(businfo->flags & I2C_BUS_DRM_CONNECTOR_CHECKED) ) { // ??? when can this be false? ??? result = businfo->drm_connector_name; // } DBGTRC_RET_STRING(debug, TRACE_GROUP, result, ""); return result; } /** Reports on a single I2C bus. * * \param businfo pointer to Bus_Info structure describing bus * \param include_sysinfo report I2C_Sys_Info for bus * \param depth logical indentation depth * * \remark * Although this is a debug type report, it is called (indirectly) by the * ENVIRONMENT command. */ void i2c_dbgrpt_bus_info(I2C_Bus_Info * businfo, bool include_sysinfo, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "businfo=%p, include_sysinfo=%s", businfo, SBOOL(include_sysinfo)); assert(businfo); rpt_structure_loc("I2C_Bus_Info", businfo, depth); rpt_vstring(depth, "Flags: %s", i2c_interpret_bus_flags_t(businfo->flags)); rpt_vstring(depth, "Bus /dev/i2c-%d found: %s", businfo->busno, sbool(businfo->flags&I2C_BUS_EXISTS)); rpt_vstring(depth, "Bus /dev/i2c-%d probed: %s", businfo->busno, sbool(businfo->flags&I2C_BUS_PROBED )); if ( businfo->flags & I2C_BUS_PROBED ) { #ifdef OUT rpt_vstring(depth, "Driver: %s", businfo->driver); rpt_vstring(depth, "Bus accessible: %s", sbool(businfo->flags&I2C_BUS_ACCESSIBLE )); rpt_vstring(depth, "Bus is eDP: %s", sbool(businfo->flags&I2C_BUS_EDP )); rpt_vstring(depth, "Bus is LVDS: %s", sbool(businfo->flags&I2C_BUS_LVDS)); rpt_vstring(depth, "Valid bus name checked: %s", sbool(businfo->flags & I2C_BUS_VALID_NAME_CHECKED)); rpt_vstring(depth, "I2C bus has valid name: %s", sbool(businfo->flags & I2C_BUS_HAS_VALID_NAME)); #ifdef DETECT_SLAVE_ADDRS rpt_vstring(depth, "Address 0x30 present: %s", sbool(businfo->flags & I2C_BUS_ADDR_X30)); #endif rpt_vstring(depth, "Address 0x37 present: %s", sbool(businfo->flags & I2C_BUS_ADDR_X37)); rpt_vstring(depth, "Address 0x50 present: %s", sbool(businfo->flags & I2C_BUS_ADDR_0X50)); rpt_vstring(depth, "Device busy: %s", sbool(businfo->flags & I2C_BUS_BUSY)); #endif rpt_vstring(depth, "errno for open: %s", psc_desc(businfo->open_errno)); // rpt_vstring(depth, "Connector name checked: %s", sbool(businfo->flags & I2C_BUS_DRM_CONNECTOR_CHECKED)); rpt_vstring(depth, "drm_connector_found_by: %s (%d)", drm_connector_found_by_name(businfo->drm_connector_found_by), businfo->drm_connector_found_by); if (businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_CHECKED) { rpt_vstring(depth, "drm_connector_name: %s", businfo->drm_connector_name); rpt_vstring(depth, "drm_connector_id: %d", businfo->drm_connector_id); if (businfo->drm_connector_name) { // possibly_write_detect_to_status_by_businfo(businfo); // in i2c/i2c_sysfs_base.h rpt_label(depth, "Current /sys attributes:"); RPT_ATTR_TEXT(depth+1, NULL, "/sys/class/drm", businfo->drm_connector_name, "enabled"); RPT_ATTR_TEXT(depth+1, NULL, "/sys/class/drm", businfo->drm_connector_name, "status"); RPT_ATTR_TEXT(depth+1, NULL, "/sys/class/drm", businfo->drm_connector_name, "dpms"); // RPT_ATTR_EDID(depth+1, NULL, "/sys/class/drm", businfo->drm_connector_name, "edid"); bool edid_found = GET_ATTR_EDID(NULL, "/sys/class/drm",businfo->drm_connector_name, "edid"); rpt_vstring(depth, "/sys/class/drm/%s/edid: %s", businfo->drm_connector_name, (edid_found) ? "Found" : "Not found"); } } // not useful and clutters the output // i2c_report_functionality_flags(businfo->functionality, /* maxline */ 90, depth); // if (businfo->edid) { // report_parsed_edid(businfo->edid, true /* verbose */, depth); // } rpt_vstring(depth, "last_checked_asleep: %s", sbool(businfo->last_checked_dpms_asleep)); } #ifdef OUT // sole non-sysfs use of i2c_sysfs_i2c_sys_info.c: #ifndef TARGET_BSD if (include_sysinfo) { I2C_Sys_Info * info = get_i2c_sys_info(businfo->busno, -1); dbgrpt_i2c_sys_info(info, depth); free_i2c_sys_info(info); } #endif #endif DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } // // Lifecycle // /** Allocates and initializes a new #I2C_Bus_Info struct * * @param busno I2C bus number * @return newly allocated #I2C_Bus_Info */ I2C_Bus_Info * i2c_new_bus_info(int busno) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d", busno); assert(busno != 255 && busno != -1); I2C_Bus_Info * businfo = calloc(1, sizeof(I2C_Bus_Info)); memcpy(businfo->marker, I2C_BUS_INFO_MARKER, 4); businfo->busno = busno; businfo->drm_connector_found_by = DRM_CONNECTOR_NOT_CHECKED; #ifdef ALT_LOCK_REC businfo->lock_record = create_display_lock_record(i2c_io_path(busno)); #endif DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", businfo); return businfo; } #ifdef UNUSED void i2c_add_bus_info(I2C_Bus_Info * businfo) { assert(businfo); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Adding businfo record for bus %d to all_i2c_buses", businfo->busno); assert(businfo->busno != 255 && businfo->busno != -1); g_mutex_lock(&all_i2c_buses_mutex); g_ptr_array_add(all_i2c_buses, businfo); g_mutex_unlock(&all_i2c_buses_mutex); DBGTRC_DONE(debug, TRACE_GROUP, ""); } I2C_Bus_Info * i2c_add_bus(int busno) { I2C_Bus_Info * businfo = i2c_new_bus_info(busno); businfo->flags = I2C_BUS_EXISTS; i2c_add_bus_info(businfo); return businfo; } #endif /** Gets the I2C_Bus_Info struct for the specified bus. * If the struct does not already exist, and the bus exists, * a new struct is allocated. * * @param busno I2C bus number * @param new_info location at which to return a flag * indicating whether the struct returned * is to a newly allocated instance * @return pointer to struct for the spscified bus * NULL if no existing struct found and the * bus does not exist */ I2C_Bus_Info * i2c_get_bus_info(int busno, bool* new_info) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "busno=%d", busno); *new_info = false; g_mutex_lock(&all_i2c_buses_mutex); I2C_Bus_Info * businfo = i2c_find_bus_info_in_gptrarray_by_busno(all_i2c_buses, busno); if (!businfo) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding /dev/"I2C"-%d to set of buses", busno); businfo = i2c_new_bus_info(busno); businfo->flags = I2C_BUS_EXISTS; g_ptr_array_add(all_i2c_buses, businfo); *new_info = true; } g_mutex_unlock(&all_i2c_buses_mutex); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning businfo=%p for busno%d, *new_info=%s", businfo, busno, SBOOL(*new_info)); return businfo; } void i2c_remove_bus_by_businfo(I2C_Bus_Info * businfo) { assert(businfo); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Removing businfo record for bus %d from all_i2c_buses", businfo->busno); assert(businfo->busno != 255 && businfo->busno != -1); g_mutex_lock(&all_i2c_buses_mutex); g_ptr_array_remove(all_i2c_buses, businfo); g_mutex_unlock(&all_i2c_buses_mutex); DBGTRC_DONE(debug, TRACE_GROUP, ""); } void i2c_discard_buses0(GPtrArray* buses) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "buses=%p", buses); if (buses) { g_ptr_array_free(buses, true); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Discard all known buses */ void i2c_discard_buses() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); g_mutex_lock(&all_i2c_buses_mutex); if (all_i2c_buses) { i2c_discard_buses0(all_i2c_buses); all_i2c_buses= NULL; } g_mutex_unlock(&all_i2c_buses_mutex); DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Frees a #I2C_Bus_Info struct * * @param businfo pointer to struct */ void i2c_free_bus_info(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "businfo = %p", businfo); // if (IS_DBGTRC(debug, TRACE_GROUP)) // show_backtrace(1); if (businfo) DBGTRC(debug, TRACE_GROUP, "marker = |%.4s|, busno = %d", businfo->marker, businfo->busno); if (businfo && memcmp(businfo->marker, I2C_BUS_INFO_MARKER, 4) == 0) { // just ignore if already freed if (businfo->edid) { char msg[100]; g_snprintf(msg, 100, "Calling free_parsed_edid busno=%d, edid=%p, marker=%s", businfo->busno, businfo->edid, hexstring_t((Byte*) businfo->marker,4)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s", msg); if (IS_DBGTRC(debug, TRACE_GROUP)) SYSLOG2(DDCA_SYSLOG_DEBUG, "%s", msg); free_parsed_edid(businfo->edid); businfo->edid = NULL; } FREE(businfo->driver); FREE(businfo->drm_connector_name); businfo->marker[3] = 'x'; free(businfo); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } #ifdef UNUSED // For g_ptr_array_set_free_func() void i2c_gdestroy_bus_info(void * data) { i2c_free_bus_info(data); } #endif #ifdef UNUSED /** Updates an existing #I2C_Bus_Info struct with recent * data from a source sruct. Modifies those fields which * can change. * * @param old * @param new */ void i2c_update_bus_info(I2C_Bus_Info * existing, I2C_Bus_Info* new) { bool debug = false; assert(existing); assert(new); DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, existing=%p, new=%p", existing->busno, existing, new); if ( IS_DBGTRC(debug, DDCA_TRC_NONE)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Initial bus info:"); i2c_dbgrpt_bus_info(existing, true, 4); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "new bus info:"); i2c_dbgrpt_bus_info(new, true, 4); } if (existing->edid) { free_parsed_edid(existing->edid); } if (new->edid) existing->edid = copy_parsed_edid(new->edid); else existing->edid = NULL; #define COPY_BIT(_old, _new, _bit) \ if (_new->flags & _bit) \ _old->flags |= _bit; \ else \ _old->flags &= ~_bit; COPY_BIT(existing, new, I2C_BUS_ADDR_X37); COPY_BIT(existing, new, I2C_BUS_ADDR_X30); COPY_BIT(existing, new, I2C_BUS_PROBED); COPY_BIT(existing, new, I2C_BUS_SYSFS_EDID); COPY_BIT(existing, new, I2C_BUS_X50_EDID); // COPY_BIT(existing, new, I2C_BUS_DRM_CONNECTOR_CHECKED); #undef COPY_BIT if (existing->drm_connector_name) { free(existing->drm_connector_name); existing->drm_connector_name = NULL; existing->drm_connector_id = -1; } existing->drm_connector_found_by = new->drm_connector_found_by; if (new->drm_connector_name) existing->drm_connector_name = g_strdup_printf("%s", new->drm_connector_name); existing->drm_connector_id = new->drm_connector_id; existing->last_checked_dpms_asleep = new->last_checked_dpms_asleep; if ( IS_DBGTRC(debug, DDCA_TRC_NONE)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Updated bus info:"); i2c_dbgrpt_bus_info(existing, true, 4); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } #endif // // Generic Bus_Info retrieval // I2C_Bus_Info * i2c_find_bus_info_in_gptrarray_by_busno(GPtrArray * buses, int busno) { bool debug = false; DBGMSF(debug, "Starting. buses=%p, busno=%d", buses, busno); I2C_Bus_Info * result = NULL; for (int ndx = 0; ndx < buses->len; ndx++) { I2C_Bus_Info * cur_info = g_ptr_array_index(all_i2c_buses, ndx); if (cur_info->busno == busno) { result = cur_info; break; } } DBGMSF(debug, "Done. Returning: %p", result); return result; } int i2c_find_bus_info_index_in_gptrarray_by_busno(GPtrArray * buses, int busno) { bool debug = false; DBGMSF(debug, "Starting. busno=%d", busno); int result = -1; for (int ndx = 0; ndx < buses->len; ndx++) { I2C_Bus_Info * cur_info = g_ptr_array_index(all_i2c_buses, ndx); if (cur_info->busno == busno) { result = ndx; break; } } DBGMSF(debug, "Done. Returning: %d", result); return result; } // // Operations on the set of all buses // /** Retrieves bus information by I2C bus number. * * @param busno bus number * * @return pointer to Bus_Info struct for the bus,\n * NULL if invalid bus number */ I2C_Bus_Info * i2c_find_bus_info_by_busno(int busno) { bool debug = false; DBGMSF(debug, "Starting. busno=%d", busno); I2C_Bus_Info * result = i2c_find_bus_info_in_gptrarray_by_busno(all_i2c_buses, busno); DBGMSF(debug, "Done. Returning: %p", result); return result; } /** Retrieves bus information by its index in the i2c_buses array * * @param busndx * * @return pointer to Bus_Info struct for the bus,\n * NULL if invalid index */ I2C_Bus_Info * i2c_get_bus_info_by_index(guint busndx) { bool debug = false; DBGMSF(debug, "busndx=%d", busndx); assert(all_i2c_buses); I2C_Bus_Info * businfo = NULL; if (busndx < all_i2c_buses->len) { businfo = g_ptr_array_index(all_i2c_buses, busndx); DBGMSF(debug, "busno=%d, flags = 0x%04x = %s", businfo->busno, businfo->flags, i2c_interpret_bus_flags_t(businfo->flags) ); } DBGMSF(debug, "Done. Returning businfo-%p. busndx=%d, busno=%d", businfo, busndx, (businfo) ? businfo->busno : -1 ); return businfo; } /** Reports I2C buses. * * @param report_all if false, only reports buses with monitors,\n * if true, reports all detected buses * @param include_sysfs_info include sysfs information in report * @param depth logical indentation depth * * @return count of reported buses * * @remark * Used by query-sysenv.c, always OL_VERBOSE */ int i2c_dbgrpt_buses(bool report_all, bool include_sysfs_info, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "report_all=%s", sbool(report_all)); assert(all_i2c_buses); int busct = all_i2c_buses->len; int reported_ct = 0; puts(""); if (report_all) rpt_vstring(depth,"Detected %d non-ignorable I2C buses:", busct); else rpt_vstring(depth, "I2C buses with monitors detected:"); for (int ndx = 0; ndx < busct; ndx++) { I2C_Bus_Info * busInfo = g_ptr_array_index(all_i2c_buses, ndx); if ( (busInfo->edid) || report_all) { rpt_nl(); i2c_dbgrpt_bus_info(busInfo, include_sysfs_info, depth); reported_ct++; } } if (reported_ct == 0) rpt_vstring(depth, " No buses\n"); DBGTRC_DONE(debug, TRACE_GROUP, "Returning %d", reported_ct); return reported_ct; } void i2c_dbgrpt_buses_summary(int depth) { Bit_Set_256 buses_all = EMPTY_BIT_SET_256; Bit_Set_256 buses_w_edid = EMPTY_BIT_SET_256; Bit_Set_256 buses_x37 = EMPTY_BIT_SET_256; assert(all_i2c_buses); int busct = all_i2c_buses->len; for (int ndx = 0; ndx < busct; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(all_i2c_buses, ndx); int busno = businfo->busno; buses_all = bs256_insert(buses_all, busno); if ( (businfo->edid) ) { buses_w_edid = bs256_insert(buses_w_edid, busno); if ( (businfo->flags & I2C_BUS_ADDR_X37) ) { buses_x37 = bs256_insert(buses_x37, busno); } } } rpt_vstring(depth, "Number of buses: %d", bs256_count(buses_all)); rpt_vstring(depth, "All I2C buses: %s", bs256_to_string_decimal_t(buses_all, "", " ")); rpt_vstring(depth, "Buses with edid: %s", bs256_to_string_decimal_t(buses_w_edid, "", " ")); rpt_vstring(depth, "Buses with x37 active: %s", bs256_to_string_decimal_t(buses_x37, "", " ")); } // // Simple /dev/i2c inquiry // /** Checks if an I2C bus with a given number exists. * * @param busno bus number * * @return true/false */ bool i2c_device_exists(int busno) { bool debug = false; bool result = false; char namebuf[20]; struct stat statbuf; sprintf(namebuf, "/dev/"I2C"-%d", busno); int rc = stat(namebuf, &statbuf); if (rc == 0) { result = true; } else { DBGMSF(debug, "stat(%s) returned %d, errno=%s", namebuf, rc, linux_errno_desc(errno) ); } DBGMSF(debug, "busno=%d, returning %s", busno, sbool(result) ); return result; } /** Returns the number of I2C buses on the system, by looking for * devices named /dev/i2c-n. * * Note that no attempt is made to open the devices. */ int i2c_device_count() { bool debug = false; int busct = 0; for (int busno=0; busno < I2C_BUS_MAX; busno++) { if (i2c_device_exists(busno)) busct++; } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Returning %d", busct ); return busct; } Error_Info * i2c_check_device_access(char * dev_name) { Error_Info * err = NULL; if ( access(dev_name, R_OK|W_OK) < 0 ) { int errsv = errno; // EACCESS if lack permissions, ENOENT if file doesn't exist char * s = NULL; if (errsv == ENOENT) { // should never occur because of prior i2c_device_exists() check s = g_strdup_printf("access(%s) returned ENOENT", dev_name); DBGMSG("%s", s); err = ERRINFO_NEW(-ENOENT, "%s", s); SYSLOG2(DDCA_SYSLOG_WARNING, "%s", s); } else if (errsv == EACCES) { s = g_strdup_printf("Device %s lacks R/W permissions", dev_name); // DBGMSG("%s", s); err = ERRINFO_NEW(-EACCES, "%s", s); SYSLOG2(DDCA_SYSLOG_WARNING, "%s", s); } else { s = g_strdup_printf( "access() returned errno = %s", psc_desc(errsv)); SYSLOG2(DDCA_SYSLOG_ERROR, "%s", s); err = ERRINFO_NEW(-ENOENT, "%s", s); } free(s); } return err; } // // x37 detection table - Records x37 responsiveness to avoid recheck // const char * x37_detection_state_name(X37_Detection_State state) { char * s = NULL; switch(state) { case X37_Not_Recorded: s = "X37_Not_Recorded"; break; case X37_Not_Detected: s = "X37_Not_Detected"; break; case X37_Detected: s = "X37_Detected"; break; } return s; } static GHashTable * x37_detection_table = NULL; char * x37_detection_table_key(int busno, Byte* edidbytes) { char * buf = g_strdup_printf("%s%d", hexstring_t(edidbytes,128), busno); //guint key = g_str_hash(buf); // free(buf); return buf; } void i2c_record_x37_detected(int busno, Byte * edidbytes, X37_Detection_State detected) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "detected = %s, busno=%d, edidbytes = %s", x37_detection_state_name(detected), busno, hexstring_t(edidbytes+120, 8)); if (!x37_detection_table) x37_detection_table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL); assert(detected != X37_Not_Recorded); char * key = x37_detection_table_key(busno, edidbytes); g_hash_table_replace(x37_detection_table, key, GINT_TO_POINTER(detected)); // free(key); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } X37_Detection_State i2c_query_x37_detected(int busno, Byte * edidbytes) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "busno=%d, edidbytes = ...%s", busno, hexstring_t(edidbytes+120, 8)); X37_Detection_State result = X37_Not_Recorded; if (x37_detection_table) { char * key = x37_detection_table_key(busno, edidbytes); gpointer pval = g_hash_table_lookup(x37_detection_table, key); result = GPOINTER_TO_INT(pval); free(key); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: %s", x37_detection_state_name(result)); return result; } /** Module initialization. */ void init_i2c_bus_base() { RTTI_ADD_FUNC(i2c_get_bus_info); RTTI_ADD_FUNC(i2c_discard_buses0); RTTI_ADD_FUNC(i2c_discard_buses); RTTI_ADD_FUNC(i2c_dbgrpt_buses); RTTI_ADD_FUNC(i2c_free_bus_info); RTTI_ADD_FUNC(i2c_new_bus_info); RTTI_ADD_FUNC(i2c_reset_bus_info); RTTI_ADD_FUNC(i2c_remove_bus_by_busno); RTTI_ADD_FUNC(i2c_dbgrpt_bus_info); RTTI_ADD_FUNC(i2c_query_x37_detected); RTTI_ADD_FUNC(i2c_record_x37_detected); // connected_buses = EMPTY_BIT_SET_256; } void terminate_i2c_bus_base() { // DBGMSG("Executing. x37_detection_table = %p", x37_detection_table); if (x37_detection_table) { g_hash_table_destroy(x37_detection_table); } if (all_i2c_buses) { // i2c_free_bus_info() already set as free function g_ptr_array_free(all_i2c_buses, true); free (all_i2c_buses); } } ddcutil-2.2.0/src/base/linux_errno.c0000644000175000001440000005424414572333721013051 /** @file linux_errno.c * * Linux errno descriptions */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include /** \endcond */ #include "util/debug_util.h" #include "util/string_util.h" #include "base/linux_errno.h" // To consider: use libexplain. // Forward declarations // static Status_Code_Info * get_negative_errno_info(int errnum); Status_Code_Info * find_errno_description(int errnum); void show_errno_desc_table(); /** Initialize linux_errno.c */ // n. called from main before command line parsed, trace control not yet established void init_linux_errno() { #ifdef OLD register_retcode_desc_finder( RR_ERRNO, get_negative_errno_info, false); // finder_arg_is_modulated #endif // show_errno_desc_table(); } // // Error handling // // // Known system error numbers // // Because macro EDENTRY ignores the description value supplied and sets // the description field to NULL, find_errno_description(), called by // linux_errno_desc(), will lookup the description using strerror(). #define EDENTRY(id,desc) {id, #id, NULL} // Errors 1-34 defined in static Status_Code_Info errno_desc[] = { EDENTRY(0, "success"), // 0 EDENTRY(EPERM, "Operation not permitted"), // 1 EDENTRY(ENOENT, "No such file or directory"), // 2 EDENTRY(ESRCH, "No such process"), // 3 EDENTRY(EINTR, "Interrupted system call"), // 4 EDENTRY(EIO, "I/O error"), // 5 EDENTRY(ENXIO, "No such device or address"), // 6 EDENTRY(E2BIG, "Argument list too long"), // 7 EDENTRY(ENOEXEC, "Exec format error"), // 8 EDENTRY(EBADF, "Bad file number"), // 9 EDENTRY(ECHILD, "No child processes"), // 10 #ifdef TARGET_BSD EDENTRY(EDEADLK, "Deadlock"), // was EAGAIN // 11 #else EDENTRY(EAGAIN, "Try again"), // 11 #endif EDENTRY(ENOMEM, "Out of memory"), // 12 EDENTRY(EACCES, "Permission denied"), // 13 EDENTRY(EFAULT, "Bad address"), // 14 EDENTRY(ENOTBLK, "Block device required"), // 15 EDENTRY(EBUSY, "Device or resource busy"), // 16 EDENTRY(EEXIST, "File exists"), // 17 EDENTRY(EXDEV, "Cross-device link"), // 18 EDENTRY(ENODEV, "No such device"), // 19 EDENTRY(ENOTDIR, "Not a directory"), // 21 EDENTRY(EISDIR, "Is a directory"), // 22 EDENTRY(EINVAL, "Invalid argument"), // 22 EDENTRY(ENFILE, "File table overflow"), // 23 EDENTRY(EMFILE, "Too many open files"), // 24 EDENTRY(ENOTTY, "Not a typewriter"), // 25 EDENTRY(ETXTBSY, "Text file busy"), // 26 EDENTRY(EFBIG, "File too large"), // 27 EDENTRY(ENOSPC, "No space left on device"), // 28 EDENTRY(ESPIPE, "Illegal seek"), // 29 EDENTRY(EROFS, "Read-only file system"), // 30 EDENTRY(EMLINK, "Too many links"), // 31 EDENTRY(EPIPE, "Broken pipe"), // 32 // math software: EDENTRY(EDOM, "Math argument out of domain of func"), // 33 EDENTRY(ERANGE, "Math result not representable"), // 34 #ifdef TARGET_LINUX EDENTRY(EDEADLK, "Resource deadlock would occur"), // 35 == EDEADLOCK EDENTRY(ENAMETOOLONG, "File name too long"), // 36 EDENTRY(ENOLCK, "No record locks available"), // 37 EDENTRY(ENOSYS, "Invalid system call number"), // 38 EDENTRY(ENOTEMPTY, "Directory not empty"), // 39 EDENTRY(ELOOP, "Too many symbolic links encountered"), // 40 EDENTRY(EAGAIN, "Operation would block"), // 41 == EWOULDBLOCK EDENTRY(ENOMSG, "No message of desired type"), // 42 EDENTRY(EIDRM, "Identifier removed"), // 43 EDENTRY(ECHRNG, "Channel number out of range"), // 44 EDENTRY(EL2NSYNC, "Level 2 not synchronized"), // 45 EDENTRY(EL3HLT, "Level 3 halted"), // 46 EDENTRY(EL3RST, "Level 3 reset"), // 47 EDENTRY(ELNRNG, "Link number out of range"), // 48 EDENTRY(EUNATCH, "Protocol driver not attached"), // 49 EDENTRY(ENOCSI, "No CSI structure available"), // 50 EDENTRY(EL2HLT, "Level 2 halted"), // 51 EDENTRY(EBADE, "Invalid exchange"), // 52 EDENTRY(EBADR, "Invalid request descriptor"), // 53 EDENTRY(EXFULL, "Exchange full"), // 54 EDENTRY(ENOANO, "No anode"), // 55 EDENTRY(EBADRQC, "Invalid request code"), // 56 EDENTRY(EBADSLT, "Invalid slot"), // 57 EDENTRY(EBFONT, "Bad font file format"), // 59 EDENTRY(ENOSTR, "Device not a stream"), // 60 EDENTRY(ENODATA, "No data available"), // 61 EDENTRY(ETIME, "Timer expired"), // 62 EDENTRY(ENOSR, "Out of streams resources"), // 63 EDENTRY(ENONET, "Machine is not on the network"), // 64 EDENTRY(ENOPKG, "Package not installed"), // 65 EDENTRY(EREMOTE, "Object is remote"), // 66 EDENTRY(ENOLINK, "Link has been severed"), // 67 EDENTRY(EADV, "Advertise error"), // 68 EDENTRY(ESRMNT, "Srmount error"), // 69 EDENTRY(ECOMM, "Communication error on send"), // 70 #endif #ifdef TARGET_BSD // non-blocking and interrupt i/o EDENTRY(EAGAIN, "Resource temporarily unavailable"), // 35 #ifndef _POSIX_SOURCE EDENTRY(EWOULDBLOCK, "Operation would block"), // 35 defined as EAGAIN EDENTRY(EINPROGRESS, "Operation now in progress"), // 36 EDENTRY(EALREADY, "Operation already in progress"), // 37 // ipc/network software -- argument errors EDENTRY(ENOTSOCK, "Socket operation on non-socket"), // 38 EDENTRY(EDESTADDRREQ, "Destination address required"), // 39 EDENTRY(EMSGSIZE, "Message too long"), // 40 EDENTRY(EPROTOTYPE, "Protocol wrong type for socket"), // 41 EDENTRY(ENOPROTOOPT, "Protocol not available"), // 42 EDENTRY(EPROTONOSUPPORT,"Protocol not supported"), // 43 EDENTRY(ESOCKTNOSUPPORT,"Socket type not supported"), // 44 EDENTRY(EOPNOTSUPP, "Operation not supported"), // 45 also ENOTSUP EDENTRY(EPFNOSUPPORT, "Protocol family not supported"), // 46 EDENTRY(EAFNOSUPPORT, "Address family not supported by protocol family"), // 47 EDENTRY(EADDRINUSE, "Address already in use"), // 48 EDENTRY(EADDRNOTAVAIL, "Can't assign requested address"), // 49 // ipc/network software -- operational errors EDENTRY(ENETDOWN, "Network is down"), // 50 EDENTRY(ENETUNREACH, "Network is unreachable"), // 51 EDENTRY(ENETRESET , "Network dropped connection on reset"), //52 EDENTRY(ECONNABORTED, "Software caused connection abort"), //53 EDENTRY(ECONNRESET, "Connection reset by peer"), // 54 EDENTRY(ENOBUFS, "No buffer space available"), // 55 EDENTRY(EISCONN, "Socket is already connected"), // 56 EDENTRY(ENOTCONN, "Socket is not connected"), // 57 EDENTRY(ESHUTDOWN , "Can't send after socket shutdown"), //58 EDENTRY(ETOOMANYREFS, "Too many references: can't splice"), //59 EDENTRY(ETIMEDOUT , "Operation timed out"), // 60 EDENTRY(ECONNREFUSED, "Connection refused"), //61 EDENTRY(ELOOP, "Too many levels of symbolic links"), //62 #endif /* _POSIX_SOURCE */ EDENTRY(ENAMETOOLONG , "File name too long"), // 63 #ifndef _POSIX_SOURCE EDENTRY(EHOSTDOWN, "Host is down"), //64 EDENTRY(EHOSTUNREACH, "No route to host"), // 65 #endif /* _POSIX_SOURCE */ EDENTRY(ENOTEMPTY, "Directory not empty"), // 66 /* quotas & mush */ #ifndef _POSIX_SOURCE EDENTRY(EPROCLIM, "Too many processes"), // 67 EDENTRY(EUSERS, "Too many users"), // 68 EDENTRY(EDQUOT, "Disc quota exceeded"), // 69 /* Network File System */ EDENTRY(ESTALE, "Stale NFS file handle"), // 70 EDENTRY(EREMOTE, "Too many levels of remote in path"), // 71 EDENTRY(EBADRPC, "RPC struct is bad"), //72 EDENTRY(ERPCMISMATCH, "RPC version wrong"), // 73 EDENTRY(EPROGUNAVAIL, "RPC prog. not avail"), // 74 EDENTRY(EPROGMISMATCH, "Program version wrong"), // 75 EDENTRY(EPROCUNAVAIL , "Bad procedure for program"), //76 #endif /* _POSIX_SOURCE */ EDENTRY(ENOLCK, "No locks available"), // 77 EDENTRY(ENOSYS, "Function not implemented"), // 78 #ifndef _POSIX_SOURCE EDENTRY(EFTYPE, "Inappropriate file type or format"), // 79 EDENTRY(EAUTH, "Authentication error"), // 80 EDENTRY(ENEEDAUTH, "Need authenticator"), // 81 EDENTRY(EIDRM , "Identifier removed"), // 82 EDENTRY(ENOMSG, "No message of desired type"), // 83 EDENTRY(EOVERFLOW, "Value too large to be stored in data type"), // 84 EDENTRY(ECANCELED, "Operation canceled"), // 85 EDENTRY(EILSEQ , "Illegal byte sequence"), // 86 EDENTRY(ENOATTR, "Attribute not found"), // 87 EDENTRY(EDOOFUS , "Programming error"), // 88 #endif /* _POSIX_SOURCE */ EDENTRY(EBADMSG , "Bad message"), // 89 EDENTRY(EMULTIHOP, "Multihop attempted"), // 90 EDENTRY(ENOLINK , "Link has been severed"), // 91 EDENTRY(EPROTO, "Protocol error"), // 92 #ifndef _POSIX_SOURCE EDENTRY(ENOTCAPABLE, "Capabilities insufficient"), // 93 EDENTRY(ECAPMODE, "Not permitted in capability mode"), // 94 EDENTRY(ENOTRECOVERABLE ,"State not recoverable"), // 95 EDENTRY(EOWNERDEAD , "Previous owner died"), // 96 EDENTRY(EINTEGRITY, "Integrity check failed"), // 97 #endif /* _POSIX_SOURCE */ #else EDENTRY(EPROTO, "Protocol error"), // 71 EDENTRY(EMULTIHOP, "Multihop attempted"), // 72 EDENTRY(EDOTDOT, "RFS specific error"), // 73 EDENTRY(EBADMSG, "Not a data message"), // 74 EDENTRY(EOVERFLOW, "Value too large for defined data type"), // 75 EDENTRY(ENOTUNIQ, "Name not unique on network"), // 76 EDENTRY(EBADFD, "File descriptor in bad state"), // 77 EDENTRY(EREMCHG, "Remote address changed"), // 78 EDENTRY(ELIBACC, "Can not access a needed shared library"), // 79 EDENTRY(ELIBBAD, "Accessing a corrupted shared library"), // 80 EDENTRY(ELIBSCN, ".lib section in a.out corrupted"), // 81 EDENTRY(ELIBMAX, "Attempting to link in too many shared libraries"), // 82 EDENTRY(ELIBEXEC, "Cannot exec a shared library directly"), // 83 EDENTRY(EILSEQ, "Illegal byte sequence"), // 84 EDENTRY(ERESTART, "Interrupted system call should be restarted"), // 85 EDENTRY(ESTRPIPE, "Streams pipe error"), // 86 EDENTRY(EUSERS, "Too many users"), // 87 EDENTRY(ENOTSOCK, "Socket operation on non-socket"), // 88 EDENTRY(EDESTADDRREQ, "Destination address required"), // 89 EDENTRY(EMSGSIZE, "Message too long"), // 90 EDENTRY(EPROTOTYPE, "Protocol wrong type for socket"), // 91 EDENTRY(ENOPROTOOPT, "Protocol not available"), // 92 EDENTRY(EPROTONOSUPPORT, "Protocol not supported"), // 93 EDENTRY(ESOCKTNOSUPPORT, "Socket type not supported"), // 94 EDENTRY(EOPNOTSUPP, "Operation not supported on transport endpoint"),// 95 EDENTRY(EPFNOSUPPORT, "Protocol family not supported"), // 96 EDENTRY(EAFNOSUPPORT, "Address family not supported by protocol"), // 97 EDENTRY(EADDRINUSE, "Address already in use"), // 98 EDENTRY(EADDRNOTAVAIL, "Cannot assign requested address"), // 99 EDENTRY(ENETDOWN, "Network is down"), // 100 EDENTRY(ENETUNREACH, "Network is unreachable"), // 101 EDENTRY(ENETRESET, "Network dropped connection because of reset"), // 102 EDENTRY(ECONNABORTED, "Software caused connection abort"), // 103 EDENTRY(ECONNRESET, "Connection reset by peer"), // 104 EDENTRY(ENOBUFS, "No buffer space available"), // 105 EDENTRY(EISCONN, "Transport endpoint is already connected"), // 106 EDENTRY(ENOTCONN, "Transport endpoint is not connected"), // 107 EDENTRY(ESHUTDOWN, "Cannot send after transport endpoint shutdown"),// 108 EDENTRY(ETOOMANYREFS, "Too many references: cannot splice"), // 109 EDENTRY(ETIMEDOUT, "Connection timed out"), // 110 EDENTRY(ECONNREFUSED, "Connection refused"), // 111 EDENTRY(EHOSTDOWN, "Host is down"), // 112 EDENTRY(EHOSTUNREACH, "No route to host"), // 113 EDENTRY(EALREADY, "Operation already in progress"), // 114 EDENTRY(EINPROGRESS, "Operation now in progress"), // 115 EDENTRY(ESTALE, "Stale file handle"), // 116 EDENTRY(EUCLEAN, "Structure needs cleaning"), // 117 EDENTRY(ENOTNAM , "Not a XENIX named type file"), // 118 EDENTRY(ENAVAIL , "No XENIX semaphores available"), // 119 EDENTRY(EISNAM , "Is a named type file"), // 120 EDENTRY(EREMOTEIO , "Remote I/O error"), // 121 EDENTRY(EDQUOT , "Quota exceeded"), // 122 EDENTRY(ENOMEDIUM , "No medium found"), // 123 EDENTRY(EMEDIUMTYPE , "Wrong medium type"), // 124 EDENTRY(ECANCELED , "Operation canceled"), // 125 EDENTRY(ENOKEY , "Required key not available"), // 126 EDENTRY(EKEYEXPIRED , "Key has expired"), // 127 EDENTRY(EKEYREVOKED , "Key has been revoked"), // 128 EDENTRY(EKEYREJECTED , "Key was rejected by service"), // 129 EDENTRY(EOWNERDEAD , "Owner died"), // 130 /* for robust mutexes */ EDENTRY(ENOTRECOVERABLE , "State not recoverable"), // 131 EDENTRY(ERFKILL , "Operation not possible due to RF-kill"), // 132 EDENTRY(EHWPOISON , "Memory page has hardware error"), // 133 #endif }; #undef EDENTRY static const int errno_desc_ct = sizeof(errno_desc)/sizeof(Status_Code_Info); #define WORKBUF_SIZE 300 static char workbuf[WORKBUF_SIZE]; static char dummy_errno_description[WORKBUF_SIZE]; static Status_Code_Info dummy_errno_desc; /** Debugging function that displays the errno description table. */ void show_errno_desc_table() { printf("(%s) errno_desc table:\n", __func__); for (int ndx=0; ndx < errno_desc_ct; ndx++) { Status_Code_Info cur = errno_desc[ndx]; printf("(%3d, %-20s, %s\n", cur.code, cur.name, cur.description); } } /** Simple call to get a description string for a Linux errno value. * * For use in specifically reporting an unmodulated Linux error number. * * \param error_number system errno value (positive) * \return string describing the error. * * The string returned is valid until the next call to this function. * * The errno value must be passed as a positive number. */ char * linux_errno_desc(int error_number) { bool debug = false; if (debug) printf("(%s) error_number = %d\n", __func__, error_number); assert(error_number >= 0); Status_Code_Info * pdesc = find_errno_description(error_number); if (pdesc) { snprintf(workbuf, WORKBUF_SIZE, "%s(%d): %s", pdesc->name, error_number, pdesc->description); } else { snprintf(workbuf, WORKBUF_SIZE, "%d: %s", error_number, strerror(error_number)); } if (debug) printf("(%s) error_number=%d, returning: |%s|\n", __func__, error_number, workbuf); return workbuf; } char * linux_errno_name(int error_number) { Status_Code_Info * pdesc = find_errno_description(error_number); return pdesc->name; } /* Returns the Status_Code_Info record for the specified error number * * @param errnum linux error number, in positive, unmodulated form * * @return Status_Code_Description record, NULL if not found * * @remark * If the description field of the found Status_Code_Info struct is NULL, it is set * by calling strerror() */ Status_Code_Info * find_errno_description(int errnum) { bool debug = false; if (debug) printf("(%s) errnum=%d\n", __func__, errnum); Status_Code_Info * result = NULL; int ndx; for (ndx=0; ndx < errno_desc_ct; ndx++) { if (errnum == errno_desc[ndx].code) { result = &errno_desc[ndx]; break; } } if (result && !result->description) { // char * desc = strerror(errnum); // result->description = malloc(strlen(desc)+1); // strcpy(result->description, desc); result->description = g_strdup(strerror(errnum)); } if (debug) printf("(%s) Returning %p\n", __func__, (void*)result); return result; } // n. returned value is valid only until next call Status_Code_Info * create_dynamic_errno_info(int errnum) { Status_Code_Info * result = &dummy_errno_desc; result->code = errnum; result->name = NULL; // would be simpler to use strerror_r(), but the return value of // that function depends on compiler switches. char * s = strerror(errnum); // generates an unknown code message for unrecognized errnum int sz = sizeof(dummy_errno_description); strncpy(dummy_errno_description, s, sz); dummy_errno_description[sz-1] = '\0'; // ensure trailing null in case strncpy truncated result->description = dummy_errno_description; return result; } Status_Code_Info * get_errno_info(int errnum) { Status_Code_Info * result = find_errno_description(errnum); return result; } // returns NULL if not found Status_Code_Info * get_negative_errno_info(int errnum) { bool debug = false; if (debug) printf("(%s) errnum=%d\n", __func__, errnum); return get_errno_info(-errnum); } /** Gets the Linux error number for a symbolic name. * The value is returned as a negative number. * * @param errno_name symbolic name, e.g. EBUSY * @param perrno where to return error number * * @return true if found, false if not */ bool errno_name_to_number(const char * errno_name, int * perrno) { bool debug = false; DBGF(debug, "Starting. errno_name=%s", errno_name); int found = false; *perrno = 0; for (int ndx = 0; ndx < errno_desc_ct; ndx++) { DBGF(debug, "Comparing: errno_desc[ndx] = %s", errno_desc[ndx].name); if ( streq(errno_desc[ndx].name, errno_name) ) { *perrno = -errno_desc[ndx].code; found = true; break; } } DBGF(debug, "Done. Returning: %s. *perrno = %d", sbool(found), *perrno); return found; } /** Gets the Linux error number for a symbolic name. * The value is returned as a negative, modulated number. * * @param errno_name symbolic name, e.g. EBUSY * @param p_error_number where to return error number * * @return true if found, false if not */ #ifdef OLD bool errno_name_to_modulated_number( const char * errno_name, Global_Status_Code * p_error_number) { int result = 0; bool found = errno_name_to_number(errno_name, &result); assert(result >= 0); if (result != 0) { result = modulate_rc(result, RR_ERRNO); assert(result <= 0); } *p_error_number = result; return found; } #endif #ifdef OLD bool errno_name_to_modulated_number( const char * errno_name, Public_Status_Code * p_error_number) { return errno_name_to_number(errno_name, p_error_number); } #endif ddcutil-2.2.0/src/base/monitor_model_key.c0000644000175000001440000002466314754153540014227 /** @file monitor_model_key.c * * Uniquely identifies a monitor model using its manufacturer id, * model name, and product code, as listed in the EDID. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "util/debug_util.h" #include "util/edid.h" #include "util/glib_util.h" #include "util/regex_util.h" #include "core.h" #include "rtti.h" #include "monitor_model_key.h" /** Returns a Monitor_Model_Key on the stack. */ Monitor_Model_Key mmk_value( const char * mfg_id, const char * model_name, uint16_t product_code) { // verify that constants used in public ddcutil_c_types.h match those in util/edid.h // assert(DDCA_EDID_MFG_ID_FIELD_SIZE == EDID_MFG_ID_FIELD_SIZE); // assert(DDCA_EDID_MODEL_NAME_FIELD_SIZE == EDID_MODEL_NAME_FIELD_SIZE); assert(mfg_id && strlen(mfg_id) < EDID_MFG_ID_FIELD_SIZE); assert(model_name && strlen(model_name) < EDID_MODEL_NAME_FIELD_SIZE); Monitor_Model_Key result; // memcpy(result.marker, MONITOR_MODEL_KEY_MARKER, 4); (void) g_strlcpy(result.mfg_id, mfg_id, EDID_MFG_ID_FIELD_SIZE); STRLCPY(result.model_name, model_name, EDID_MODEL_NAME_FIELD_SIZE); FIXUP_MODEL_NAME(result.model_name); result.product_code = product_code; result.defined = true; return result; } /** Returns an "undefined" Monitor_Model_Key on the stack. */ Monitor_Model_Key mmk_undefined_value() { Monitor_Model_Key result; memset(&result, 0, sizeof(result)); // memcpy(result.marker, MONITOR_MODEL_KEY_MARKER, 4); return result; } /** Returns a Monitor Model Key on the stack with values obtained * from an EDID */ Monitor_Model_Key mmk_value_from_edid(Parsed_Edid * edid) { Monitor_Model_Key result; // memcpy(result.marker, MONITOR_MODEL_KEY_MARKER, 4); /* coverity[OVERRUN] */ (void) g_strlcpy(result.mfg_id, edid->mfg_id, EDID_MFG_ID_FIELD_SIZE); /* coverity[overrun-buffer-val] */ (void) g_strlcpy(result.mfg_id, edid->mfg_id, EDID_MFG_ID_FIELD_SIZE); /* coverity[access_debuf_const] */ (void) g_strlcpy(result.mfg_id, edid->mfg_id, EDID_MFG_ID_FIELD_SIZE); // STRLCPY(result.mfg_id, edid->mfg_id, EDID_MFG_ID_FIELD_SIZE); memcpy(result.mfg_id, edid->mfg_id, EDID_MFG_ID_FIELD_SIZE); /* coverity[OVERRUN] */ (void) g_strlcpy(result.model_name, edid->model_name, EDID_MODEL_NAME_FIELD_SIZE); FIXUP_MODEL_NAME(result.model_name); result.product_code = edid->product_code; result.defined = true; return result; } /** Allocates and initializes a new Monitor_Model_Key on the heap. */ Monitor_Model_Key * mmk_new( const char * mfg_id, const char * model_name, uint16_t product_code) { assert(mfg_id && strlen(mfg_id) < EDID_MFG_ID_FIELD_SIZE); assert(model_name && strlen(model_name) < EDID_MODEL_NAME_FIELD_SIZE); Monitor_Model_Key * result = calloc(1, sizeof(Monitor_Model_Key)); // memcpy(result->marker, MONITOR_MODEL_KEY_MARKER, 4); STRLCPY(result->mfg_id, mfg_id, EDID_MFG_ID_FIELD_SIZE); STRLCPY(result->model_name, model_name, EDID_MODEL_NAME_FIELD_SIZE); FIXUP_MODEL_NAME(result->model_name); result->product_code = product_code; result->defined = true; return result; } Monitor_Model_Key mmk_value_from_string(const char * sval) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "sval = |%s|", sval); static const char * mmk_pattern = "^([A-Z]{3})-(.{0,13})-([0-9]*)$"; regmatch_t matches[4]; bool ok = compile_and_eval_regex_with_matches( mmk_pattern, sval, 4, // max_matches, matches); Monitor_Model_Key result = mmk_undefined_value(); if (ok) { // for (int kk = 0; kk < 4; kk++) { // rpt_vstring(1, "match %d, substring start=%d, end=%d", kk, matches[kk].rm_so, matches[kk].rm_eo); // } char * mfg_id = substr(sval, matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so); char * model_name = substr(sval, matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so); char * product_code_s = substr(sval, matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so); FIXUP_MODEL_NAME(model_name); // DBGF(debug, "mfg_id=|%s|", mfg_id); // DBGF(debug, "model_name=|%s|", model_name); // DBGF(debug, "product_code_s=|%s|", product_code_s); uint16_t product_code; int ival; ok = str_to_int(product_code_s, &ival, 10); product_code = (uint16_t) ival; assert(ok); // DBGF(debug, "product_code: %d", product_code); result = mmk_value(mfg_id, model_name, product_code); free(mfg_id); free(model_name); free(product_code_s); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: %s", mmk_repr(result)); return result; } Monitor_Model_Key * mmk_new_from_value(Monitor_Model_Key mmk) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "mmk=%s", mmk_repr(mmk)); Monitor_Model_Key * result = NULL; if (mmk.defined) { result = calloc(1, sizeof(Monitor_Model_Key)); memcpy(result, &mmk, sizeof(Monitor_Model_Key)); #ifdef ALTERNATIVE Monitor_Model_Key * result2 = mmk_new( mmk.mfg_id, mmk.model_name, mmk.product_code); assert(monitor_model_key_eq(*result, *result2)); mmk_free(result2); #endif assert(monitor_model_key_eq(mmk, *result)); } if (result) DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: %p -> %s", result, mmk_repr(*result)); else DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: NULL"); return result; } Monitor_Model_Key * mmk_new_from_string(const char * s) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "s=|s|", s); Monitor_Model_Key * result = NULL; Monitor_Model_Key mmk = mmk_value_from_string(s); if (mmk.defined) { result = mmk_new_from_value(mmk); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: %p", result); return result; } bool is_valid_mmk(const char * sval) { Monitor_Model_Key mmk = mmk_value_from_string(sval); return mmk.defined; } Monitor_Model_Key * mmk_new_from_edid( Parsed_Edid * edid) { Monitor_Model_Key * result = NULL; if (edid) { result = calloc(1, sizeof(Monitor_Model_Key)); memcpy(result->mfg_id, edid->mfg_id, EDID_MFG_ID_FIELD_SIZE); memcpy(result->model_name, edid->model_name, EDID_MODEL_NAME_FIELD_SIZE); FIXUP_MODEL_NAME(result->model_name); result->product_code = edid->product_code; result->defined = true; } return result; } /** Frees a Monitor_Model_Key */ void mmk_free( Monitor_Model_Key * mmk) { free(mmk); } /** Compares 2 Monitor_Model_Key values for equality * * \param mmk1 * \param mmk2 * \return true/false */ bool monitor_model_key_eq( Monitor_Model_Key mmk1, Monitor_Model_Key mmk2) { bool result = false; if (!mmk1.defined && !mmk2.defined) { result = true; } else if (mmk1.defined && mmk2.defined) { result = (mmk1.product_code == mmk2.product_code && strcmp(mmk1.mfg_id, mmk2.mfg_id) == 0 && strcmp(mmk1.model_name, mmk2.model_name) == 0 ); } return result; } #ifdef UNUSED Monitor_Model_Key * monitor_model_key_undefined_new() { Monitor_Model_Key * result = calloc(1, sizeof(Monitor_Model_Key)); // memcpy(result->marker, MONITOR_MODEL_KEY_MARKER, 4); return result; } // needed at API level? Monitor_Model_Key monitor_model_key_assign(Monitor_Model_Key old) { return old; } bool monitor_model_key_is_defined(Monitor_Model_Key mmk) { // DDCA_Monitor_Model_Key undefined = monitor_model_key_undefined_value(); // bool result = monitor_model_key_eq(mmk, undefined); return mmk.defined; } #endif /** Returns a string form of a Monitor_Model_Key, suitable for use as an * identifier in file names, hash keys, etc. * * The returned value has the form MFG-MODEL-PRODUCT_CODE. * * Non-alphanumeric characters (commonly " ") in the model name are replaced by "_". * * \param mfg * \param model_name * \param product_code * \return key string (caller must free or save in persistent data structure) */ char * mmk_model_id_string( const char * mfg, const char * model_name, uint16_t product_code) { bool debug = false; DBGMSF(debug, "Starting. mfg=|%s|, model_name=|%s| product_code=%u", mfg, model_name, product_code); assert(mfg); assert(model_name); char * model_name2 = g_strdup(model_name); FIXUP_MODEL_NAME(model_name2); char * result = g_strdup_printf("%s-%s-%u", mfg, model_name2, product_code); free(model_name2); DBGMSF(debug, "Returning: |%s|", result); return result; } /** Returns a string representation of a Monitor_Model_Key in a form * suitable for file names, hash keys, etc. * * The value returned has the same form as returned by #model_id_string. * * \param model_id * \return string representation * * The value returned will be valid until the next call to this function in * the current thread. Caller should not free. */ char * mmk_string(Monitor_Model_Key * model_id) { static GPrivate dh_buf_key = G_PRIVATE_INIT(g_free); const int bufsz = 100; char * buf = get_thread_fixed_buffer(&dh_buf_key, bufsz); char * result = NULL; // perhaps use thread safe buffer so caller doesn't have to free if (model_id) { char * s = mmk_model_id_string( model_id->mfg_id, model_id->model_name, model_id->product_code); strcpy(buf, s); free(s); result = buf; } return result; } /** Returns a string representation of a Monitor_Model_Key in a format * suitable for debug messages. * * \param mmk Monitor_Model_Key value * \return string representation * * The value returned will be valid until the next call to this function in * the current thread. Caller should not free. */ char * mmk_repr(Monitor_Model_Key mmk) { static GPrivate dh_buf_key = G_PRIVATE_INIT(g_free); const int bufsz = 100; char * buf = get_thread_fixed_buffer(&dh_buf_key, bufsz); if (!mmk.defined) strcpy(buf, "[Undefined]"); else snprintf(buf, 100, "[%s,%s,%d]", mmk.mfg_id, mmk.model_name, mmk.product_code); return buf; } void init_monitor_model_key() { RTTI_ADD_FUNC(mmk_value_from_string); RTTI_ADD_FUNC(mmk_new_from_value); } #undef FIXUP_MODEL_NAME ddcutil-2.2.0/src/base/monitor_quirks.c0000644000175000001440000000230514572333721013561 /** @file monitor_quirks.c */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "util/coredefs_base.h" #include "base/core.h" #include "base/monitor_model_key.h" #include "base/monitor_quirks.h" typedef struct { Monitor_Model_Key mmk; Monitor_Quirk_Data data; } Monitor_Quirk_Table_Entry; static Monitor_Quirk_Table_Entry quirk_table[] = { {{ "XMI", "Mi Monitor", 13380, true}, { MQ_NO_SETTING, NULL}}, // {{ "DEL", "DELL U3011", 16485, true}, { MQ_NO_MFG_RANGE, "msg 1"}}, // for testing // {{ "NEC", "P241W", 26715, true}, { MQ_NO_SETTING, "msg 2"}}, // for testing }; int quirk_table_size = ARRAY_SIZE(quirk_table); Monitor_Quirk_Data * get_monitor_quirks(Monitor_Model_Key * mmk) { bool debug = false; DBGMSF(debug, "quirk_table_size=%d, mmk=%s", quirk_table_size, mmk_repr(*mmk)); Monitor_Quirk_Data * result = NULL; for (int ndx = 0; ndx < quirk_table_size; ndx++) { DBGMSF(debug, "ndx=%d, mmk=%s", ndx, mmk_repr(quirk_table[ndx].mmk)); if (monitor_model_key_eq(*mmk, quirk_table[ndx].mmk)) { result = &quirk_table[ndx].data; break; } } return result; } ddcutil-2.2.0/src/base/per_thread_data.c0000644000175000001440000006316514754576332013626 /** @file per_thread_data.c */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include #include #include #include "util/debug_util.h" #include "util/glib_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/timestamp.h" #include "base/core.h" #include "base/core_per_thread_settings.h" #include "base/displays.h" #include "base/parms.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/per_thread_data.h" void ptd_profile_function_report(Per_Thread_Data * ptd, gpointer depth); // Master table of sleep data for all threads GHashTable * per_thread_data_hash = NULL; // key is thread id static GPrivate this_thread_has_lock; static GPrivate lock_depth; // GINT_TO_POINTER(0); static bool debug_mutex = false; int ptd_lock_count = 0; int ptd_unlock_count = 0; int cross_thread_operation_blocked_count = 0; void dbgrpt_per_thread_data_locks(int depth) { rpt_vstring(depth, "ptd_lock_count: %-4d", ptd_lock_count); rpt_vstring(depth, "ptd_unlock_count: %-4d", ptd_unlock_count); rpt_vstring(depth, "cross_thread_operation_blocked_count: %-4d", cross_thread_operation_blocked_count); } static bool cross_thread_operation_active = false; static GMutex cross_thread_operation_mutex; static pid_t cross_thread_operation_owner; // The locking strategy relies on the fact that in practice conflicts // will be rare, and critical sections short. // Operations that occur on the // are blocked only using a spin-lock. // The groups of operations: // - Operations that operate on the single Per_Thread_Data instance // associated with the currently executing thread. // - Operations that operate on a single Per_Thread_Data instance, // but possibly not from the thread associated with the Per_Thread_Data instance. // - Operations that operate on multiple Per_Thread_Data instances. // These are referred to as cross thread operations. // Alt, perhaps clearer, refer to them as multi-thread data instances. /** */ bool ptd_cross_thread_operation_start() { // Only 1 cross thread action can be active at one time. // All per_thread actions must wait bool debug = false; debug = debug || debug_mutex; bool lock_performed = false; // which way is better? bool thread_has_lock = GPOINTER_TO_INT(g_private_get(&this_thread_has_lock)); int thread_lock_depth = GPOINTER_TO_INT(g_private_get(&lock_depth)); assert ( ( thread_has_lock && thread_lock_depth > 0) || (!thread_has_lock && thread_lock_depth == 0) ); DBGMSF(debug, "Already locked: %s", sbool(thread_has_lock)); if (thread_lock_depth == 0) { // (A) // if (!thread_has_lock) { // thread_lock_depth is per-thread, so must be unchanged from (A) g_mutex_lock(&cross_thread_operation_mutex); lock_performed = true; cross_thread_operation_active = true; ptd_lock_count++; // should this be a depth counter rather than a boolean? g_private_set(&this_thread_has_lock, GINT_TO_POINTER(true)); Thread_Output_Settings * thread_settings = get_thread_settings(); // intmax_t cur_thread_id = get_thread_id(); intmax_t cur_thread_id = thread_settings->tid; cross_thread_operation_owner = cur_thread_id; DBGMSF(debug, "Locked by thread %d", cur_thread_id); sleep_millis(10); // give all per-thread functions time to finish } g_private_set(&lock_depth, GINT_TO_POINTER(thread_lock_depth+1)); DBGMSF(debug, "Returning: %s", sbool(lock_performed) ); return lock_performed; } void ptd_cross_thread_operation_end() { int thread_lock_depth = GPOINTER_TO_INT(g_private_get(&lock_depth)); g_private_set(&lock_depth, GINT_TO_POINTER(thread_lock_depth-1)); assert(thread_lock_depth >= 1); if (thread_lock_depth == 1) { // if (unlock_requested) { cross_thread_operation_active = false; cross_thread_operation_owner = 0; g_private_set(&this_thread_has_lock, false); ptd_unlock_count++; assert(ptd_lock_count == ptd_unlock_count); g_mutex_unlock(&cross_thread_operation_mutex); } else { assert( ptd_lock_count > ptd_unlock_count ); } } /** Block execution of single Per_Thread_Data operations when an operation * involving multiple Per_Thead_Data instances is active. */ void ptd_cross_thread_operation_block() { // intmax_t cur_threadid = get_thread_id(); Thread_Output_Settings * thread_settings = get_thread_settings(); intmax_t cur_threadid = thread_settings->tid; if (cross_thread_operation_active && cur_threadid != cross_thread_operation_owner) { __sync_fetch_and_add(&cross_thread_operation_blocked_count, 1); do { sleep_millis(10); } while (cross_thread_operation_active); } } // satisfies type GDestroyNotify: void (*GDestroyNotify) (gpointer data); void per_thread_data_destroy(void * data) { if (data) { Per_Thread_Data * ptd = data; #ifdef REMOVED_20 free(ptd->description); #endif free(ptd->cur_func); if (ptd->function_stats) g_hash_table_destroy(ptd->function_stats); free(ptd); } } void terminate_per_thread_data() { if (per_thread_data_hash) { g_hash_table_destroy(per_thread_data_hash); } } // // Locking // #ifdef PTD static void ptd_init(Per_Thread_Data * ptd) { } #endif /** Gets the #Per_Thread_Data struct for the current thread, using the * current thread's id number. If the struct does not already exist, it * is allocated and initialized. * * @return pointer to #Per_Thread_Data struct * * @remark * The structs are maintained centrally rather than using a thread-local pointer * to a block on the heap because the of a problem when the thread is closed. * Valgrind complains of access errors for closed threads, even though the * struct is on the heap and still readable. */ Per_Thread_Data * ptd_get_per_thread_data() { bool debug = false; // intmax_t cur_thread_id = get_thread_id(); Thread_Output_Settings * thread_settings = get_thread_settings(); intmax_t cur_thread_id = thread_settings->tid; // DBGMSF(debug, "Getting thread sleep data for thread %d", cur_thread_id); // bool this_function_owns_lock = ptd_lock_if_unlocked(); assert(per_thread_data_hash); // allocated by init_thread_data_module() // DBGMSG("per_thread_data_hash = %p", per_thread_data_hash); // n. data hash for current thread can only be looked up from current thread, // so there's nothing can happen to per_thread_data_hash before g_hash_table_insert() Per_Thread_Data * data = g_hash_table_lookup(per_thread_data_hash, GINT_TO_POINTER(cur_thread_id)); if (!data) { DBGMSF(debug, "==> Per_Thread_Data not found for thread %d", cur_thread_id); data = g_new0(Per_Thread_Data, 1); data->thread_id = cur_thread_id; // data->sleep_multiplier = -1.0f; g_private_set(&lock_depth, GINT_TO_POINTER(0)); #ifdef PTD ptd_init(data); DBGMSF(debug, "Initialized: %s. thread_sleep_data_defined: %s. thread_retry_data_defined; %s", sbool(data->initialized), sbool( data->thread_sleep_data_defined), sbool( data->thread_retry_data_defined)); #endif g_hash_table_insert(per_thread_data_hash, GINT_TO_POINTER(cur_thread_id), data); DBGMSF(debug, "Created Per_Thread_Data struct for thread id = %d", data->thread_id); DBGMSF(debug, "per_thread_data_hash size=%d", g_hash_table_size(per_thread_data_hash)); if (debug) dbgrpt_per_thread_data(data, 1); } // ptd_unlock_if_needed(this_function_owns_lock); return data; } #ifdef REMOVED_20 // Thread description operations always operate on the Per_Thread_Data // instance for the currently executing thread. void ptd_set_thread_description(const char * description) { ptd_cross_thread_operation_block(); Per_Thread_Data * ptd = ptd_get_per_thread_data(); // DBGMSG("thread: %d, description: %s", ptd->thread_id, description); if (ptd->description) free(ptd->description); ptd->description = g_strdup(description); } void ptd_append_thread_description(const char * addl_description) { ptd_cross_thread_operation_block(); Per_Thread_Data * ptd = ptd_get_per_thread_data(); // DBGMSG("ptd->description = %s, addl_descripton = %s", ptd->description, addl_description); if (!ptd->description) ptd->description = g_strdup(addl_description); else if (str_contains(ptd->description, addl_description) < 0) { char * s = ptd->description; ptd->description = g_strdup_printf("%s; %s", ptd->description, addl_description); free(s); } } const char * ptd_get_thread_description_t() { static GPrivate x_key = G_PRIVATE_INIT(g_free); static GPrivate x_len_key = G_PRIVATE_INIT(g_free); ptd_cross_thread_operation_block(); Per_Thread_Data * ptd = ptd_get_per_thread_data(); char * buf = NULL; if (ptd->description) { char * buf = get_thread_dynamic_buffer(&x_key, &x_len_key, strlen(ptd->description)+1); strcpy(buf,ptd->description); } return buf; } #endif /** Output a debug report of a #Per_Thread_Data struct. * * @param data pointer to #Per_Thread_Data struct * @param depth logical indentation level * * // relies on caller for possible blocking */ void dbgrpt_per_thread_data(Per_Thread_Data * data, int depth) { int d1 = depth+1; rpt_structure_loc("Per_Thread_Data", data, depth); rpt_vstring(d1,"initialized %s", sbool(data->initialized)); rpt_vstring(d1,"thread_id %d", data->thread_id); #ifdef REMOVED_20 rpt_vstring(d1,"description %s", data->description); #endif rpt_vstring(d1,"cur_dh: %s", dh_repr(data->cur_dh) ); rpt_vstring(d1,"cur_func %s", data->cur_func); rpt_vstring(d1,"cur_start %"PRIu64, data->cur_start); rpt_vstring(d1,"function profile stats: "); ptd_profile_function_report(data, GINT_TO_POINTER(depth+1)); } /** Applies a specified function with signature GFunc to all * #Per_Thread_Data instances. * * @param func function to apply * \parm arg an arbitrary argument passed as a pointer * * This is a multi-instance operation. */ void ptd_apply_all(Ptd_Func func, void * arg) { ptd_cross_thread_operation_start(); bool debug = false; assert(per_thread_data_hash); // allocated by init_thread_data_module() GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter,per_thread_data_hash); while (g_hash_table_iter_next (&iter, &key, &value)) { Per_Thread_Data * data = value; DBGMSF(debug, "Thread id: %d", data->thread_id); func(data, arg); } ptd_cross_thread_operation_end(); } /** Apply a given function to all #Per_Thread_Data structs, ordered by thread id. * Note that this report includes structs for threads that have been closed. * * @param func function to apply * @param arg pointer or integer value * * This is a multi-instance operation. */ void ptd_apply_all_sorted(Ptd_Func func, void * arg) { bool debug = false; DBGMSF(debug, "Starting"); ptd_cross_thread_operation_start(); assert(per_thread_data_hash); DBGMSF(debug, "hash table size = %d", g_hash_table_size(per_thread_data_hash)); GList * keys = g_hash_table_get_keys (per_thread_data_hash); GList * new_head = g_list_sort(keys, gaux_ptr_intcomp); GList * l; for (l = new_head; l != NULL; l = l->next) { int key = GPOINTER_TO_INT(l->data); DBGMSF(debug, "Key: %d", key); Per_Thread_Data * data = g_hash_table_lookup(per_thread_data_hash, l->data); assert(data); func(data, arg); } g_list_free(new_head); // would keys also work? ptd_cross_thread_operation_end(); DBGMSF(debug, "Done"); } /** Emits a brief summary of a #Per_Thread_Data instance, * showing the thread id number and description. * * ptd pointer to #Per_Thread_Data instance * arg logical indentation * * @note * This function has a GFunc signature * @note * Called only by multi-thread-data functions that hold lock */ void ptd_thread_summary(Per_Thread_Data * ptd, void * arg) { int depth = GPOINTER_TO_INT(arg); int d1 = depth+1; ptd_cross_thread_operation_block(); // simple but ugly // rpt_vstring(depth, "Thread: %d. Description:%s", // ptd->thread_id, ptd->description); // rpt_vstring(depth, "Thread: %d", ptd->thread_id); // char * header = "Description: "; char header[100]; g_snprintf(header, 100, "Thread %d: ", ptd->thread_id); rpt_vstring(d1, "%s", header); #ifdef REMOVED_20 int hdrlen = strlen(header); if (!ptd->description) rpt_vstring(d1, "%s", header); else { Null_Terminated_String_Array pieces = strsplit_maxlength(ptd->description, 60, " "); int ntsa_ndx = 0; while (true) { char * s = pieces[ntsa_ndx++]; if (!s) break; rpt_vstring(d1, "%-*s%s", hdrlen, header, s); if (strlen(header) > 0) { // *header = '\0'; // better, test it next time working with this function strcpy(header, ""); // header = ""; } } ntsa_free(pieces, true); } #endif } /** Emits a brief summary (thread id and description) for each * #Per_Thread_Data instance. * * @param depth logical indentation depth */ void ptd_list_threads(int depth) { // bool this_function_owns_lock = ptd_lock_if_unlocked(); int d1 = depth +1; // rpt_label(depth, "Have data for threads:"); rpt_label(depth, "Report has per-thread data for threads:"); ptd_apply_all_sorted(ptd_thread_summary, GINT_TO_POINTER(d1)); rpt_nl(); } #ifdef PTD void report_all_thread_status_counts(int depth) { bool debug = false; DBGMSF(debug, "Starting"); rpt_label(depth, "No per-thread status code statistics are collected"); rpt_nl(); DBGMSF(debug, "Done"); } #endif #ifdef TIMING_TEST // test timing for getting thread id // conclusion: // at 10 calls using cached value is 2 times as fast // at 100 calls using cached value is 11 times as fast // at 1000 calls using cached value is 24 times as fast void test_get_thread_id() { // int loopct = 10 * 1000 * 1000; // 10 million int loopct = 1000; intmax_t threadid; intmax_t start = cur_realtime_nanosec(); for (int ndx = 0; ndx < loopct; ndx++) { threadid = get_thread_id(); } intmax_t end = cur_realtime_nanosec(); intmax_t elapsed = (end-start)/1000; printf("threadid = %ld, direct: %10"PRIu64"\n", threadid, elapsed); start = cur_realtime_nanosec(); Thread_Output_Settings* ts = get_thread_settings(); ts->tid = get_thread_id(); for (int ndx = 0; ndx < loopct; ndx++) { Thread_Output_Settings* ts = get_thread_settings(); threadid = ts->tid; } end = cur_realtime_nanosec(); intmax_t elapsed2 = (end-start)/1000; printf("threadid = %ld, thread_setings: %10"PRIu64"\n", threadid, elapsed2); int ratio = elapsed/elapsed2; printf("ratio: %d\n", ratio); } #endif // // Collect Performance Stats // bool ptd_api_profiling_enabled = false; void ptd_profile_function_stats_key_destroy(void * data) { // GDestroyNotify // key is function name, type char* g_free(data); } void free_per_thread_function_stats(Per_Thread_Function_Stats * stats) { free(stats->function); free(stats); } void ptd_profile_function_stats_value_destroy(void * data) { // GDestroyNofify // value is Per_Thread_Function_Stats* Per_Thread_Function_Stats * stats = (Per_Thread_Function_Stats *) data; free(stats->function); free(stats); } void ptd_profile_reset_thread_stats(Per_Thread_Data * ptd, void * data) { bool debug = false; DBGMSF(debug, "Starting. ptd=%p, data=%p", ptd, data); ptd_cross_thread_operation_block(); // wait for any cross-thread operation to complete if (ptd->function_stats) g_hash_table_remove_all(ptd->function_stats); DBGMSF(debug, "Done"); } void ptd_profile_reset_all_stats() { ptd_cross_thread_operation_start(); ptd_apply_all(ptd_profile_reset_thread_stats, NULL); ptd_cross_thread_operation_end(); } // gets the Function_Stats_Hash table for the current thread static inline Function_Stats_Hash * ptd_profile_get_stats() { // does this function need to block? Per_Thread_Data * ptd = ptd_get_per_thread_data(); if (!ptd->function_stats) { ptd->function_stats = g_hash_table_new_full(g_str_hash, g_str_equal, ptd_profile_function_stats_key_destroy, ptd_profile_function_stats_value_destroy); } return ptd->function_stats; } void ptd_profile_function_start(const char * func) { bool debug = false; DBGMSF(debug, "Executing. func=%s", func); Per_Thread_Data * ptd = ptd_get_per_thread_data(); // If profiling currently active, do not profile called functions if (!ptd->cur_func) { ptd->cur_func = strdup(func); ptd->cur_start = cur_realtime_nanosec(); } else { DBGMSF(debug, "Currently profiling %s, Ignoring called function %s", ptd->cur_func, func); } } void ptd_profile_function_end(const char * func) { bool debug = false; Per_Thread_Data * ptd = ptd_get_per_thread_data(); DBGMSF(debug, "Starting. func=%s, cur_func=%s", func, ptd->cur_func); // Ignore called functions if (streq(ptd->cur_func, func)) { Function_Stats_Hash * stats_table = ptd_profile_get_stats(); Per_Thread_Function_Stats * function_stats = g_hash_table_lookup(stats_table, func); // DBGMSF(debug, " stats_table=%p, function_stats=%p", stats_table, function_stats); if (!function_stats) { function_stats = calloc(1, sizeof(Per_Thread_Function_Stats)); function_stats->function = strdup(func); g_hash_table_insert(stats_table, strdup(func), function_stats); } uint64_t elapsed_nanosec = cur_realtime_nanosec() - ptd->cur_start; function_stats->total_calls++; function_stats->total_nanosec += elapsed_nanosec; DBGMSF(debug, "Done. func=%s, elapsed_nanosec=%jd, total_nanosec=%jd", func, elapsed_nanosec, function_stats->total_nanosec); free(ptd->cur_func); ptd->cur_func = NULL; } else { DBGMSF(debug, "Currently profiling %s, ignoring end of %s", ptd->cur_func, func); } } // // Stats Utility Functions // #ifdef NOT_NEEDED const char * func_addr_to_name(gpointer addr) { #define ALT #ifdef ALT const char * name = "Unknown"; Dl_info info; int rc = dladdr(addr, &info); if (rc) { name = info.dli_sname; } #else char * name = rtti_get_func_name_by_addr(addr); if (!name) name = "Unknown"; #endif return name; } #endif // // Create summary table // /** Adds the stats for one function on a thread to the summary record for all * threads for that function. * * Satisfies type GHFunc * * @oaram key function name (char*) * @param value pointer to Per_Thread_Function_Stats struct for the function on a thread * @data pointer to summary hash table of function names -> Per_Thread_Function_Stats struct */ void add_one_func_to_summary(gpointer key, gpointer cur_func_stats, gpointer data) { bool debug = false; DBGMSF(debug, "Starting. key=%p -> %s, cur_func_stats=%p, data=%p", key, key, cur_func_stats, data); Per_Thread_Function_Stats * cfs = (Per_Thread_Function_Stats*) cur_func_stats; assert(streq(key,cfs->function)); Function_Stats_Hash * summary_table = (GHashTable *) data; Per_Thread_Function_Stats * cur_summary_entry = g_hash_table_lookup(summary_table, cfs->function); if (!cur_summary_entry) { DBGMSF(debug, " Per_Thread_Function_Stats not found for %s", cfs->function); cur_summary_entry = calloc(1, sizeof(Per_Thread_Function_Stats)); cur_summary_entry->function = strdup(cfs->function); g_hash_table_insert(summary_table, strdup(cfs->function), cur_summary_entry); } cur_summary_entry->total_calls += cfs->total_calls; cur_summary_entry->total_nanosec += cfs->total_nanosec; DBGMSF(debug, "Done. cur_summary_entry=%p, total_calls=%d, total_nanosec=%d, function=%p->%s", cur_summary_entry, cur_summary_entry->total_calls, cur_summary_entry->total_nanosec, cur_summary_entry->function, cur_summary_entry->function); } /** Adds the stats for all functions on single thread to the summary record * for all functions on all threads * * @param ptd pointer to Per_Thread_Data struct for a thread * @param data pointer to summary */ void ptd_add_stats(Per_Thread_Data * ptd, void * data) { bool debug = false; DBGMSF(debug, "Starting. ptd=%p, data=%p", ptd, data); g_hash_table_foreach(ptd->function_stats, add_one_func_to_summary, data); DBGMSF(debug, "Done"); } /** Creates a hash table with the total stats for each function across all threads * * @return hash table with key = function name, value = Per_Thread_Function_Stats* */ Function_Stats_Hash * summarize_per_thread_stats() { Function_Stats_Hash * summary = g_hash_table_new_full( g_str_hash, g_str_equal, g_free, (GDestroyNotify) free_per_thread_function_stats); ptd_apply_all(ptd_add_stats, summary); // ptd_apply_all manages locking return summary; } /** Reports stats for one function on one thread, or reports the * summary record for one function on all threads * * Satisfies typedef GHFunc * * @oaram key function name (char*) * @param value pointer to Per_Thread_Function_Stats struct for the function * @data depth logical indentation depth */ static void ptd_report_one_func0(Per_Thread_Function_Stats * pts, void * arg) { // bool debug = false; int depth = GPOINTER_TO_INT(arg); // DBGMSF(debug, "pts=%p, pts->total_calls=%d", pts, pts->total_calls); // DBGMSF(debug, "pts=%p, pts->total_millisec=%d", pts, pts->total_millisec); // DBGMSF(debug, "pts=%p, pts->function=%p", pts, pts->function); rpt_vstring(depth, "%5d %8"PRIu64" %s", pts->total_calls, (pts->total_nanosec+500)/1000, pts->function); } static void ptd_report_one_func(gpointer key, gpointer value, gpointer user_data) { bool debug = false; DBGMSF(debug, "gpointer=%p->%s, value=%p, user_data=%p", key, key, value, user_data); Per_Thread_Function_Stats * pts = (Per_Thread_Function_Stats *) value; //const char * func_name = func_addr_to_name(pts->function); // DBGMSF(debug, "pts=%p, pts->total_calls=%d", pts, pts->total_calls); // DBGMSF(debug, "pts=%p, pts->total_millisec=%d", pts, pts->total_millisec); // DBGMSF(debug, "pts=%p, pts->function=%p", pts, pts->function); ptd_report_one_func0(pts, user_data); } // Reports function stats for a single thread void ptd_profile_function_report(Per_Thread_Data * ptd, gpointer depth) { int d0 = GPOINTER_TO_INT(depth); // int d1 = d0 + 1; rpt_vstring(d0, "Per-Thread Function Profile Report for thread %d:", ptd->thread_id); if (ptd->function_stats) { rpt_label(d0, "Count Microsec Function Name"); g_hash_table_foreach(ptd->function_stats, ptd_report_one_func, depth); } else rpt_label(d0, "No function stats"); rpt_nl(); } // Apply a function to all Per_Thread_Data records // typedef void (*Ptd_Func)(Per_Thread_Data * data, void * arg); // Template for function to apply void ptd_profile_report_all_threads(int depth) { bool debug = false; DBGMSF(debug, "Starting"); ptd_apply_all_sorted(ptd_profile_function_report, GINT_TO_POINTER(depth)); // rpt_nl(); DBGMSF(debug, "Done"); } gint gaux_scomp( gconstpointer a, gconstpointer b) { // DBGMSG("a=%p -> %s", a,a); // DBGMSG("b=%p -> %s", b,b); return g_ascii_strcasecmp(a,b); } typedef void (*Ptd_Stats_Func)(Per_Thread_Function_Stats * data, void * arg); // Template for function to apply /** Apply a given function to all #Per_Thread_Data structs, ordered by thread id. * Note that this report includes structs for threads that have been closed. * * @param func function to apply * @param arg pointer or integer value * * This is a multi-instance operation. */ void ptd_profile_apply_all_sorted(Function_Stats_Hash * function_stats_hash, Ptd_Stats_Func func, void * arg) { bool debug = false; DBGMSF(debug, "Starting"); assert(function_stats_hash); DBGMSF(debug, "hash table size = %d", g_hash_table_size(function_stats_hash)); GList * keys = g_hash_table_get_keys (function_stats_hash); GList * new_head = g_list_sort(keys, gaux_scomp); GList * l; for (l = new_head; l != NULL; l = l->next) { char * key = (char*) l->data; DBGMSF(debug, "Key: %s", key); Per_Thread_Function_Stats * data = g_hash_table_lookup(function_stats_hash, l->data); assert(data); func(data, arg); } g_list_free(new_head); // would keys also work? DBGMSF(debug, "Done"); } void ptd_profile_report_stats_summary(int depth) { bool debug = false; DBGMSF(debug, "Starting"); // int d1 = depth+1; rpt_label(depth, "Summary Function Profile Report for all Threads"); rpt_label(depth, "Count Microsec Function Name"); Function_Stats_Hash * summary_stats = summarize_per_thread_stats(); DBGMSF(debug, " summary_stats=%p", summary_stats); ptd_profile_apply_all_sorted(summary_stats, ptd_report_one_func0, GINT_TO_POINTER(depth)); g_hash_table_destroy(summary_stats); DBGMSF(debug, "Done"); } /** Initialize per_thread_data.c at program startup */ void init_per_thread_data() { per_thread_data_hash = g_hash_table_new_full(g_direct_hash, NULL, NULL, per_thread_data_destroy); // DBGMSG("per_thead_data_hash = %p", per_thread_data_hash); } ddcutil-2.2.0/src/base/rtti.c0000644000175000001440000000534014754153540011461 /* @file rtti.c * * Runtime trace information */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include "util/debug_util.h" #include "util/glib_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/rtti.h" static GHashTable * func_name_table = NULL; void rtti_func_name_table_add(void * func_addr, const char * func_name) { if (!func_name_table) func_name_table = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, g_free); g_hash_table_insert(func_name_table, func_addr, g_strdup(func_name)); } char * rtti_get_func_name_by_addr(void * ptr) { char * result = ""; if (func_name_table && ptr) { result = g_hash_table_lookup(func_name_table, ptr); if (!result) result = ""; } return result; } void * rtti_get_func_addr_by_name(const char * name) { bool debug = false; DBGF(debug, "func_name_table=%p, name=|%s|", func_name_table, name); void * result = NULL; if (func_name_table) { GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, func_name_table); while (g_hash_table_iter_next(&iter, &key, &value)) { if (streq(name, (char *) value)) { result = key; break; } } } DBGF(debug, "name=%s, returning %s", name, SBOOL(result)); return result; } void dbgrpt_rtti_func_name_table(int depth, bool show_internal) { if (show_internal) { rpt_vstring(depth, "Function name table at %p", func_name_table); depth=depth+1; } if (func_name_table) { GHashTableIter iter; gpointer key, value; GPtrArray * values = g_ptr_array_new(); g_hash_table_iter_init(&iter, func_name_table); while (g_hash_table_iter_next(&iter, &key, &value)) { if (show_internal) { rpt_vstring(depth, "%p: %s", key, (char *) value); } g_ptr_array_add(values, value); } g_ptr_array_sort(values, gaux_ptr_scomp); for (int ndx = 0; ndx < values->len; ndx++) { rpt_vstring(depth, " %s", (char *) g_ptr_array_index(values, ndx)); } g_ptr_array_free(values, true); } else { if (!show_internal) { rpt_label(depth, "None"); } } } void report_rtti_func_name_table(int depth, char * msg) { bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); if (msg) { rpt_label(depth, msg); depth++; } dbgrpt_rtti_func_name_table(depth, false); rpt_set_ornamentation_enabled(saved_prefix_report_output); } void terminate_rtti() { g_hash_table_destroy(func_name_table); } ddcutil-2.2.0/src/base/sleep.c0000644000175000001440000001052414754153540011607 /** @file sleep.c Basic Sleep Services * * Most of **ddcutil's** elapsed time is spent in sleeps mandated by the * DDC protocol. Basic sleep invocation is centralized here to perform sleep * tracing and and maintain sleep statistics. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include /** \endcond */ #include "util/common_inlines.h" #include "util/report_util.h" #include "util/timestamp.h" #include "base/core.h" #include "base/sleep.h" // // Sleep statistics // static Sleep_Stats sleep_stats; G_LOCK_DEFINE(sleep_stats); /** Sets all sleep statistics to 0. */ void init_sleep_stats() { G_LOCK(sleep_stats); sleep_stats.total_sleep_calls = 0; sleep_stats.requested_sleep_milliseconds = 0; sleep_stats.actual_sleep_nanos = 0; G_UNLOCK(sleep_stats); } /** Returns the current sleep statistics * * \return a copy of struct Sleep_Stats, containing thee current value * of the accumulated sleep stats * * \remark * N.B. Returns a copy of the struct on the stack, not a pointer to the struct. */ Sleep_Stats get_sleep_stats() { Sleep_Stats stats_copy; G_LOCK(sleep_stats); stats_copy = sleep_stats; G_UNLOCK(sleep_stats); return stats_copy;; } /** Reports the accumulated sleep statistics * * \param depth logical indentation depth */ void report_sleep_stats(int depth) { Sleep_Stats stats_copy = get_sleep_stats(); int d1 = depth+1; rpt_title("Sleep Call Stats:", depth); rpt_vstring(d1, "Total sleep calls: %10d", stats_copy.total_sleep_calls); rpt_vstring(d1, "Requested sleep time milliseconds : %10d", stats_copy.requested_sleep_milliseconds); rpt_vstring(d1, "Actual sleep milliseconds (nanosec): %10"PRIu64" (%13" PRIu64 ")", stats_copy.actual_sleep_nanos / (1000*1000), stats_copy.actual_sleep_nanos); } // // Perform Sleep // /** Sleep for the specified number of milliseconds and * record sleep statistics. * * \param milliseconds number of milliseconds to sleep */ void sleep_millis(int milliseconds) { uint64_t start_nanos = cur_realtime_nanosec(); usleep(milliseconds*1000); // usleep takes microseconds, not milliseconds G_LOCK(sleep_stats); sleep_stats.actual_sleep_nanos += (cur_realtime_nanosec()-start_nanos); sleep_stats.requested_sleep_milliseconds += milliseconds; sleep_stats.total_sleep_calls++; G_UNLOCK(sleep_stats); } /** Sleep for the specified number of milliseconds, record * sleep statistics, and perform tracing. * * Tracing occurs if trace group DDCA_TRC_SLEEP is enabled. * * \param milliseconds number of milliseconds to sleep * \param func name of function that invoked sleep * \param lineno line number in file where sleep was invoked * \param filename name of file from which sleep was invoked * \param message text to be appended to trace message */ void sleep_millis_with_trace( int milliseconds, const char * func, int lineno, const char * filename, const char * message) { bool debug = false; if (!message) message = ""; DBGTRC_EXECUTED(debug, DDCA_TRC_SLEEP, "Sleeping for %d milliseconds. %s", milliseconds, message); if (milliseconds > 0) sleep_millis(milliseconds); } // Special sleep function for watching display connection changes // TODO: Integrate with sleep_millis_with_trace() void dw_sleep_millis(DDCA_Syslog_Level level, const char * func, int line, const char * file, uint millis, const char * msg) { bool debug = false; DBGMSF(debug, "func=%s, millis=%d, micros=%ld", func, millis, MILLIS2MICROS(millis)); usleep((uint64_t)1000*millis); // Alternatively, use syslog() instead of SYSLOG2() to ensure that msg is // written to system log no matter what ddcutil log level cutoff is in effect #ifdef W_TID SYSLOG2(level, "[%d](%s) Slept for %d millisec: %s", tid(), func, millis, msg); #endif SYSLOG2(level, "(%s) %s: Slept for %d millisec", func, msg, millis); } ddcutil-2.2.0/src/base/stats.c0000644000175000001440000000126014572333721011631 // stats.c // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "stats.h" #ifndef STATS_H #define STATS_H static char * retry_type_descriptions[] = { "write only", "write-read", "multi-part read", "multi-part write" }; static char * retry_type_names[] = { "WRITE_ONLY_TRIES_OP", "WRITE_READ_TRIES_OP", "MULTI_PART_READ_OP", "MULTI_PART_WRITE_OP" }; const char * retry_type_name(Retry_Operation type_id) { return retry_type_names[type_id]; } const char * retry_type_description(Retry_Operation type_id) { return retry_type_descriptions[type_id]; } #endif ddcutil-2.2.0/src/base/trace_control.c0000644000175000001440000003151514754153540013340 /** @file trace_control.c * * Manage whether tracing is performed. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "config.h" #include "public/ddcutil_types.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/glib_util.h" #include "util/glib_string_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "rtti.h" #include "trace_control.h" static Value_Name_Title_Table trace_group_table = { VNT(DDCA_TRC_BASE, "BASE"), VNT(DDCA_TRC_I2C, "I2C"), VNT(DDCA_TRC_DDC, "DDC"), VNT(DDCA_TRC_USB, "USB"), VNT(DDCA_TRC_TOP, "TOP"), VNT(DDCA_TRC_ENV, "ENV"), VNT(DDCA_TRC_API, "API"), VNT(DDCA_TRC_UDF, "UDF"), VNT(DDCA_TRC_VCP, "VCP"), VNT(DDCA_TRC_DDCIO, "DDCIO"), VNT(DDCA_TRC_SLEEP, "SLEEP"), VNT(DDCA_TRC_RETRY, "RETRY"), VNT(DDCA_TRC_CONN, "CONN"), VNT(DDCA_TRC_SYSFS, "SYSFS"), VNT_END }; const int trace_group_ct = (ARRAY_SIZE(trace_group_table)-1); /** Given a trace group name, returns its identifier. * Case is ignored. * * @param name trace group name * @return trace group identifier * @retval TRC_NEVER unrecognized name * * /ingroup dbgtrace */ DDCA_Trace_Group trace_class_name_to_value(const char * name) { return (DDCA_Trace_Group) vnt_find_id( trace_group_table, name, true, // search title field true, // ignore-case DDCA_TRC_NONE); } DDCA_Trace_Group trace_levels = DDCA_TRC_NONE; // 0x00 /** Replaces the groups to be traced. * * @param trace_flags bit flags indicating groups to trace * * @ingroup dbgtrace */ void set_trace_groups(DDCA_Trace_Group trace_flags) { bool debug = false; if (debug) printf("(%s) trace_flags=0x%04x\n", __func__, trace_flags); trace_levels = trace_flags; } /** Adds to the groups to be traced. * * @param trace_flags bit flags indicating groups to trace * * @ingroup dbgtrace */ void add_trace_groups(DDCA_Trace_Group trace_flags) { bool debug = false; if (debug) printf("(%s) trace_flags=0x%04x\n", __func__, trace_flags); trace_levels |= trace_flags; } // traced_function_table and traced_file_table were initially implemented using // GHashTable. The implementation had bugs, and given that (a) these data structures // are used only for testing and (b) there will be at most a handful of entries in the // tables, a simpler GPtrArray implementation is used. static GPtrArray * traced_function_table = NULL; static GPtrArray * traced_file_table = NULL; static GPtrArray * traced_api_call_table = NULL; static GPtrArray * traced_callstack_call_table = NULL; void dbgrpt_traced_object_table(GPtrArray * table, const char * table_name, int depth) { if (table) { rpt_vstring(depth, "%s:", table_name); if (table->len == 0) rpt_vstring(depth, "%s: empty", table_name); else { for (int ndx = 0; ndx < table->len; ndx++) rpt_vstring(depth+1, g_ptr_array_index(table, ndx)); } } else { rpt_vstring(depth, "%s: NULL", table_name); } } void dbgrpt_traced_function_table(int depth) { dbgrpt_traced_object_table(traced_function_table, "traced_function_table", depth); } void dbgrpt_traced_callstack_call_table(int depth) { dbgrpt_traced_object_table(traced_callstack_call_table, "traced_callstack_call_table", depth); } /** Adds a function to the list of functions to be traced. * * @param funcname function name * @return true if funcname has been registered as a traceable function, * false if not * * @emark * If the **traced_function_table** does not already exist, it is created. */ bool add_traced_function(const char * funcname) { bool debug = false; if (debug) { DBG("Starting. funcname=|%s|", funcname); // report_rtti_func_name_table(2, "current function name table:"); } bool result = false; bool missing = false; if (rtti_get_func_addr_by_name(funcname)) { // if it's a traceable function DBGF(debug, "%s is a tracable function", funcname); if (!traced_function_table) traced_function_table = g_ptr_array_new(); // n. g_ptr_array_find_with_equal_func() requires glib 2.54 missing = (gaux_string_ptr_array_find(traced_function_table, funcname) < 0); if (missing) g_ptr_array_add(traced_function_table, g_strdup(funcname)); result = true; } DBGF(debug, "Done. funcname=|%s|, missing=%s, returning: %s", funcname, sbool(missing), sbool(result)); return result; } /** Adds an API function name to the list of API calls to be traced. * * @param funcname function name * @return true if the API function name has been registered as a traceable function, * false if not * * @remark * If the **traced_api_call_table** does not already exist, it is created. */ bool add_traced_api_call(const char * funcname) { bool debug = false; DBGF(debug, "Starting. funcname=|%s|", funcname); bool result = false; bool missing = false; if (rtti_get_func_addr_by_name(funcname)) { if (!traced_api_call_table) traced_api_call_table = g_ptr_array_new(); // n. g_ptr_array_find_with_equal_func() requires glib 2.54 bool missing = (gaux_string_ptr_array_find(traced_api_call_table, funcname) < 0); if (missing) g_ptr_array_add(traced_api_call_table, g_strdup(funcname)); result = true; } DBGF(debug, "Done. funcname=|%s|, missing=%s, returning: %s", funcname, sbool(missing), sbool(result)); return result; } /** Adds a function to the traced callstack call list. * * @param funcname function name * @return true if funcname has been registered as a traceable function, * false if not * * @emark * If the **traced_callstack_call_table** does not already exist, it is created. */ bool add_traced_callstack_call(const char * funcname) { bool debug = false; DBGF(debug, "Starting. funcname=|%s|", funcname); bool result = false; bool missing = false; if (rtti_get_func_addr_by_name(funcname)) { if (!traced_callstack_call_table) traced_callstack_call_table = g_ptr_array_new(); // n. g_ptr_array_find_with_equal_func() requires glib 2.54 missing = (gaux_string_ptr_array_find(traced_callstack_call_table, funcname) < 0); if (missing) g_ptr_array_add(traced_callstack_call_table, g_strdup(funcname)); result = true; } DBGF(debug, "Done. funcname=|%s|, missing=%s, returning: %s", funcname, sbool(missing), sbool(result)); return result; } /** Adds a file to the list of files to be traced. * * @param filename file name * * @remark * Only the basename portion of the specified file name is used. * @remark * If the file name does not end in ".c", that suffix is appended. * @remark * The file name is not checked for validity. */ void add_traced_file(const char * filename) { bool debug = false; DBGF(debug, "Starting. filename = |%s|", __func__, filename); if (!traced_file_table) traced_file_table = g_ptr_array_new(); // n. g_ptr_array_find_with_equal_func() requires glib 2.54 bool missing = false; gchar * bname = NULL; if (filename) { bname = g_path_get_basename(filename); if (!str_ends_with(bname, ".c")) { int newsz = strlen(bname) + 2 + 1; gchar * temp = calloc(1, newsz); strcpy(temp, bname); strcat(temp, ".c"); free(bname); bname = temp; } bool missing = (gaux_string_ptr_array_find(traced_file_table, bname) < 0); if (missing) g_ptr_array_add(traced_file_table, bname); else free(bname); } DBGF(debug, "Done. filename=|%s|, bname=|%s|, missing=%s", filename, bname, SBOOL(missing)); } // n.b. caller must free result static char * get_gptrarray_as_joined_string(GPtrArray * arry, bool sort) { char * result = NULL; if (arry) { if (sort) g_ptr_array_sort(arry, gaux_ptr_scomp); result = join_string_g_ptr_array(arry, ", "); } return result; } #ifdef OLD static char * get_traced_functions_as_joined_string() { char * result = NULL; if (traced_function_table) { g_ptr_array_sort(traced_function_table, gaux_ptr_scomp); result = join_string_g_ptr_array(traced_function_table, ", "); } return result; } static char * get_traced_api_calls_as_joined_string() { char * result = NULL; if (traced_api_call_table) { g_ptr_array_sort(traced_api_call_table, gaux_ptr_scomp); result = join_string_g_ptr_array(traced_api_call_table, ", "); } return result; } static char * get_traced_callstack_calls_as_joined_string() { char * result = NULL; if (traced_callstack_call_table) { g_ptr_array_sort(traced_callstack_call_table, gaux_ptr_scomp); result = join_string_g_ptr_array(traced_callstack_call_table, ", "); } return result; } static char * get_traced_files_as_joined_string() { char * result = NULL; if (traced_file_table) { g_ptr_array_sort(traced_file_table, gaux_ptr_scomp); result = join_string_g_ptr_array(traced_file_table, ", "); } return result; } #endif /** Checks if a function is being traced. * * @param funcname function name * @return **true** if the function is being traced, **false** if not */ bool is_traced_function(const char * funcname) { bool debug = false; bool result = (traced_function_table && gaux_string_ptr_array_find(traced_function_table, funcname) >= 0); DBGF(debug, "funcname=|%s|, returning: %s", funcname, SBOOL(result)); return result; } /** Checks if an API call function is being traced. * * @param funcname function name * @return **true** if the function is being traced, **false** if not */ bool is_traced_api_call(const char * funcname) { bool debug = false; if (debug) { DBG("Starting. funcname = %s", funcname); char * buf = get_gptrarray_as_joined_string(traced_api_call_table, true); DBG("traced_api_calls: %s", buf); free(buf); } bool result = (traced_api_call_table && gaux_string_ptr_array_find(traced_api_call_table, funcname) >= 0); DBGF(debug, "funcname=|%s|, returning: %s\n", funcname, SBOOL(result)); return result; } /** Checks if a function is in #traced_callstack_call_table. * * @param funcname function name * @return **true** if the function is in the table, **false** if not */ bool is_traced_callstack_call(const char * funcname) { bool debug = false; if (debug) { DBG("Starting. funcname = %s", funcname); char * buf = get_gptrarray_as_joined_string(traced_callstack_call_table, true); DBG("traced_callstack_calls: %s", buf ); free(buf); } bool result = (traced_callstack_call_table && gaux_string_ptr_array_find(traced_callstack_call_table, funcname) >= 0); DBGF(debug, "funcname=|%s|, returning: %s", __func__, funcname, SBOOL(result)); return result; } /** Checks if a file is being traced. * * @param filename file name * @return **true** if trace is enabled for all functions in the file, **false** if not */ bool is_traced_file(const char * filename) { bool result = false; if (filename) { char * bname = g_path_get_basename(filename); result = (traced_file_table && gaux_string_ptr_array_find(traced_file_table, bname) >= 0); // printf("(%s) filename=|%s|, bname=|%s|, returning: %s\n", __func__, filename, bname, SBOOL(result)); free(bname); } return result; } /** Reports the current trace settings. * * \param depth logical indentation depth */ void report_tracing(int depth) { int d1 = depth+1; rpt_label(depth, "Trace Options:"); #ifdef UNUSED show_trace_destination(); #endif char * buf = vnt_interpret_flags(trace_levels, trace_group_table, true /* use title */, ", "); rpt_vstring(d1, "Trace groups active: %s", (buf && strlen(buf)>0) ? buf : "none"); free(buf); buf = get_gptrarray_as_joined_string(traced_function_table, true); rpt_vstring(d1, "Traced functions: %s", (buf && strlen(buf)>0) ? buf : "none"); free(buf); buf = get_gptrarray_as_joined_string(traced_api_call_table, true); rpt_vstring(d1, "Traced API calls: %s", (buf && strlen(buf)>0) ? buf : "none"); free(buf); buf = get_gptrarray_as_joined_string(traced_callstack_call_table, true); rpt_vstring(d1, "Traced call stack calls: %s", (buf && strlen(buf)>0) ? buf : "none"); free(buf); buf = get_gptrarray_as_joined_string(traced_file_table, true); rpt_vstring(d1, "Traced files: %s", (buf && strlen(buf)>0) ? buf : "none"); free(buf); } ddcutil-2.2.0/src/base/tuned_sleep.c0000644000175000001440000003614714754153540013017 /** @file tuned_sleep.c * * Perform sleep. The sleep time is determined by io mode, sleep event time, * and applicable multipliers. */ // Copyright (C) 2019-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include "public/ddcutil_types.h" #include "base/core.h" #include "base/dsa2.h" #include "base/execution_stats.h" #include "base/per_display_data.h" #include "base/rtti.h" #include "base/sleep.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SLEEP; // // Deferred sleep // // If enabled, sleep is not performed immediately, but instead before the next // DDC call that requires that a wait has occurred. The elapsed time between // when the call is requested and when it actually occurs is subtracted from // the specified sleep time to obtain the actual sleep time. // // In testing, this has proven to have a negligible effect on elapsed // execution time. // static bool deferred_sleep_enabled = false; bool suppress_se_post_read = false; bool null_msg_adjustment_enabled = false; /** Enables or disables deferred sleep. * @param onoff new setting * @return old setting */ bool enable_deferred_sleep(bool onoff) { // DBGMSG("enable = %s", sbool(onoff)); bool old = deferred_sleep_enabled; deferred_sleep_enabled = onoff; return old; } /** Reports whether deferred sleep is enabled. * @return true/false */ bool is_deferred_sleep_enabled() { return deferred_sleep_enabled; } /** Given a sleep event type, return its sleep time in milliseconds as per the * DDC/CI spec, and also whether the sleep can be deferred. * * @param event_type * @param special_sleep_time_millis sleep time for SE_SPECIAL * @param is_deferrable_loc where to return flag indicating whether the sleep * can be deferred or must be performed immiediately */ static int get_sleep_time( Sleep_Event_Type event_type, int special_sleep_time_millis, bool* is_deferrable_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Sleep event type = %s, special_sleep_time_millis=%d", sleep_event_name(event_type), special_sleep_time_millis); int spec_sleep_time_millis = 0; bool deferrable_sleep = false; switch (event_type) { // Sleep events with values defined in DDC/CI spec case SE_WRITE_TO_READ: // 4.3 Get VCP Feature & VCP Feature Reply: // The host should wait at least 40 ms in order to enable the decoding and // and preparation of the reply message by the display // 4.6 Capabilities Request & Reply: // write to read interval unclear, assume 50 ms // Note: ddc_i2c_write_read_raw() is used for both normal VCP feature reads // and reads within a capabilities or table command. It can't distinguish a // normal write/read from one inside a multi part read. So this sleep time // is used for both. // spec_sleep_time_millis = DDC_TIMEOUT_MILLIS_BETWEEN_GETVCP_WRITE_READ; spec_sleep_time_millis = DDC_TIMEOUT_MILLIS_DEFAULT; // spec_sleep_time_millis = 0; // *** TEMP *** deferrable_sleep = deferred_sleep_enabled; break; case SE_POST_WRITE: // post SET VCP FEATURE write, between SET TABLE write fragments, after final? // 4.4 Set VCP Feature: // The host should wait at least 50ms to ensure next message is received by the display spec_sleep_time_millis = DDC_TIMEOUT_MILLIS_DEFAULT; deferrable_sleep = deferred_sleep_enabled; break; case SE_POST_READ: deferrable_sleep = deferred_sleep_enabled; spec_sleep_time_millis = DDC_TIMEOUT_MILLIS_DEFAULT; if (suppress_se_post_read) { DBGMSG("Suppressing SE_POST_READ"); spec_sleep_time_millis = 0; } break; case SE_POST_SAVE_SETTINGS: // 4.5 Save Current Settings: // The host should wait at least 200 ms before sending the next message to the display deferrable_sleep = deferred_sleep_enabled; spec_sleep_time_millis = DDC_TIMEOUT_MILLIS_POST_SAVE_SETTINGS; // per DDC spec break; case SE_PRE_MULTI_PART_READ: // before reading capabilities - this is based on testing, not defined in spec spec_sleep_time_millis = 200; break; case SE_POST_CAP_TABLE_SEGMENT: // 4.6 Capabilities Request & Reply: // The host should wait at least 50ms before sending the next message to the display // 4.8.1 Table Write // The host should wait at least 50ms before sending the next message to the display // 4.8.2 Table Read // The host should wait at least 50ms before sending the next message to the display spec_sleep_time_millis = DDC_TIMEOUT_MILLIS_BETWEEN_CAP_TABLE_FRAGMENTS; break; case SE_SPECIAL: // UNUSED // 4/2020: no current use spec_sleep_time_millis = special_sleep_time_millis; break; } *is_deferrable_loc = deferrable_sleep; DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %d, *is_deferrable_loc = %s", spec_sleep_time_millis, SBOOL(*is_deferrable_loc)); return spec_sleep_time_millis; } /** Calculates the sleep time to be used for a sleep event instance. * * First, a sleep multiplier is applied to the nominal "spec sleep time". * * If the current loop has 1 or more DDC Null Message replies, an * additional adjustment amount may be added. * * @param dh display handle * @param event_type sleep event type * @param spec_sleep_time_millis nominal sleep time * @param msg trace message * @param null_adjustent_added_loc where to return a boolean value * indicating whether an adjustment for * DDC null values was added * @return adjusted sleep time, in milliseconds * * The sleep-multiplier, as returned by #pdd_get_adjusted_sleep_multiplier() * is obtained from the dynamic sleep algorithm, if one is currently * active, a sleep-multiplier given on the command line or from the configuration * file, or the default sleep-multiplier (1.0). * * The nominal sleep time is: * - Sleep time for the event as given in the DDC/CI spec * - Sleep time for additional event types not in the spec * - For events of to SE_SPECIAL, the sleep time passed when * the sleep event was triggered. */ static int adjust_sleep_time( Display_Handle * dh, Sleep_Event_Type event_type, int spec_sleep_time_millis, const char * msg, bool * null_adjustment_added_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, event_type=%s, spec_sleep_time_millis=%d, msg=%s", dh_repr(dh), sleep_event_name(event_type), spec_sleep_time_millis, msg); int null_adjustment_millis = 0; *null_adjustment_added_loc = false; Per_Display_Data * pdd = dh->dref->pdd; double dsa_multiplier = pdd_get_adjusted_sleep_multiplier(pdd); // hack to test conjecture that dynamic sleep can set post write sleep time time low if (event_type == SE_POST_WRITE || event_type == SE_POST_SAVE_SETTINGS) { if (dsa_multiplier < 1.0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dh=%s, Replacing adjusted sleep multiplier %3.2f with 1.00 for SE_POST_WRITE or SE_POST_SAVE_SETTINGS", dh_repr(dh), dsa_multiplier); SYSLOG2(DDCA_SYSLOG_VERBOSE, "dh=%s, Replacing adjusted sleep multiplier %3.2f with 1.00 for SE_POST_WRITE or SE_POST_SAVE_SETTINGS", dh_repr(dh), dsa_multiplier); dsa_multiplier = 1.0; } else { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dh=%s, Keeping adjusted sleep multiplier %3.2f for SE_POST_WRITE or SE_POST_SAVE_SETTINGS", dh_repr(dh), dsa_multiplier); SYSLOG2(DDCA_SYSLOG_VERBOSE, "dh=%s, Keeping adjusted sleep multiplier %3.2f for SE_POST_WRITE or SE_POST_SAVE_SETTINGS", dh_repr(dh), dsa_multiplier); } } int adjusted_sleep_time_millis = spec_sleep_time_millis * dsa_multiplier; if (dh->dref->pdd->cur_loop_null_msg_ct > 0 && null_msg_adjustment_enabled) { switch(dh->dref->pdd->cur_loop_null_msg_ct) { case 1: null_adjustment_millis = 25; // 1 * DDC_TIMEOUT_MILLIS_NULL_RESPONSE_INCREMENT; break; case 2: null_adjustment_millis = 100; //2 * DDC_TIMEOUT_MILLIS_NULL_RESPONSE_INCREMENT; break; default: null_adjustment_millis = 200; //4 * DDC_TIMEOUT_MILLIS_NULL_RESPONSE_INCREMENT; break; } *null_adjustment_added_loc = true; adjusted_sleep_time_millis += null_adjustment_millis; char * s = g_strdup_printf( "Adding %d milliseconds for %d Null response(s), busno=%d, event_type=%s, adjusted_sleep_time=%d %s", null_adjustment_millis , dh->dref->pdd->cur_loop_null_msg_ct, dh->dref->io_path.path.i2c_busno, sleep_event_name(event_type), adjusted_sleep_time_millis, (msg) ? msg : ""); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s", s); SYSLOG2(DDCA_SYSLOG_WARNING, "%s", s); free(s); } DBGTRC_DONE(debug, TRACE_GROUP, "spec_sleep_time_millis = %d, dsa_multiplier=%5.2f, null_adjustment_millis=%d, " "Returning: %d, *null_adjustment_added_loc-%s", spec_sleep_time_millis, dsa_multiplier, null_adjustment_millis, adjusted_sleep_time_millis, sbool(*null_adjustment_added_loc)); return adjusted_sleep_time_millis; } /** Determine the for the period of time to sleep after a DDC IO operation, then * either sleep immediately or, if deferrable sleep is in effect, queue * the sleep for later execution. * * Steps: * - Determine the spec sleep time for the event type. * - Call adjust_sleep_time() to modify the sleep time based on the * sleep multiplier and the error rate. * - If deferrable sleep is not in effect (normal case) sleep for the * calculated time. * - If deferrable sleep is in effect, note in the thread-specific data the * earliest possible time for the next DDC operation in the current thread. * * @param event_type reason for sleep * @oaran special_sleep_time_millis sleep time for event_type SE_SPECIAL * @param func name of function that invoked sleep * @param lineno line number in file where sleep was invoked * @param filename name of file from which sleep was invoked * @param msg text to append to trace message */ void tuned_sleep_with_trace( Display_Handle * dh, Sleep_Event_Type event_type, int special_sleep_time_millis, const char * func, int lineno, const char * filename, const char * msg) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, sleep event type=%s, special_sleep_time_millis=%d", dh_repr(dh), sleep_event_name(event_type),special_sleep_time_millis); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Called from func=%s, filename=%s, lineno=%d, msg=|%s|", func, filename, lineno, msg); assert(dh); assert( (event_type != SE_SPECIAL && special_sleep_time_millis == 0) || (event_type == SE_SPECIAL && special_sleep_time_millis > 0) ); assert(dh->dref->io_path.io_mode == DDCA_IO_I2C); bool deferrable_sleep = false; int spec_sleep_time_millis = get_sleep_time(event_type, special_sleep_time_millis, &deferrable_sleep); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "After get_sleep_time(). spec_sleep_time_millis = %d, deferrable sleep: %s", spec_sleep_time_millis,SBOOL(deferrable_sleep)); bool null_adjustment_added = false; int adjusted_sleep_time_millis = adjust_sleep_time(dh, event_type, spec_sleep_time_millis, msg, &null_adjustment_added); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "After adjust_sleep_time(), adjusted_sleep_time_millis = %d", adjusted_sleep_time_millis); Per_Display_Data * pdd = dh->dref->pdd; if (null_adjustment_added) pdd->cur_loop_null_adjustment_occurred = true; if (null_msg_adjustment_enabled && pdd->cur_loop_null_msg_ct == 1) { // if (get_output_level() >= DDCA_OL_VERBOSE) { // f0printf(fout(), "Extended delay as recovery from DDC Null Response...\n"); // } MSG_W_SYSLOG(DDCA_SYSLOG_NOTICE, "(%s) Bus=%d. Extended delay as recovery from DDC NULL Response", __func__, dh->dref->io_path.path.i2c_busno); } record_sleep_event(event_type); if (deferrable_sleep) { uint64_t new_deferred_time = cur_realtime_nanosec() + (1000 *1000) * (int) adjusted_sleep_time_millis; if (new_deferred_time > dh->dref->next_i2c_io_after) { dh->dref->next_i2c_io_after = new_deferred_time; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Updated deferred sleep time, new_deferred_time=%"PRIu64"", new_deferred_time); } } else { char msg_buf[100]; const char * evname = sleep_event_name(event_type); if (msg) g_snprintf(msg_buf, 100, "Event type: %s, %s", evname, msg); else g_snprintf(msg_buf, 100, "Event_type: %s", evname); sleep_millis_with_trace(adjusted_sleep_time_millis, func, lineno, filename, msg_buf); pdd->total_sleep_time_millis += adjusted_sleep_time_millis; } DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Compares if the current clock time is less than the delayed io start time * for a display handle, and if so sleeps for the difference. * * The delayed io start time is stored in the display reference associated with * the display handle, so persists across open and close * * @param dh Display Handle * #param func name of function performing check * @param lineno line number of check * @param filename file from which the check is invoked */ void check_deferred_sleep( Display_Handle * dh, const char * func, int lineno, const char * filename) { bool debug = false; uint64_t curtime = cur_realtime_nanosec(); DBGTRC_STARTING(debug, TRACE_GROUP,"Checking from %s() at line %d in file %s", func, lineno, filename); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "curtime=%"PRIu64", next_i2c_io_after=%"PRIu64, curtime / (1000*1000), dh->dref->next_i2c_io_after/(1000*1000)); Display_Ref * dref = dh->dref; Per_Display_Data * pdd = dref->pdd; if (dref->next_i2c_io_after > curtime) { int sleep_time = (dh->dref->next_i2c_io_after - curtime)/ (1000*1000); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Sleeping for %d milliseconds", sleep_time); sleep_millis_with_trace(sleep_time, func, lineno, filename, "deferred"); pdd->total_sleep_time_millis += sleep_time; DBGTRC_DONE(debug, TRACE_GROUP,""); } else { DBGTRC_DONE(debug, TRACE_GROUP, "No sleep necessary"); } } /** Module initialization */ void init_tuned_sleep() { RTTI_ADD_FUNC(get_sleep_time); RTTI_ADD_FUNC(adjust_sleep_time); RTTI_ADD_FUNC(check_deferred_sleep); RTTI_ADD_FUNC(tuned_sleep_with_trace); } ddcutil-2.2.0/src/base/status_code_mgt.c0000644000175000001440000003467614634171455013703 /** \file status_code_mgt.c * * Status Code Management */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include /** \endcond */ #include "util/debug_util.h" #include "util/string_util.h" #include "base/ddc_errno.h" #include "base/linux_errno.h" #include "base/status_code_mgt.h" /* Notes on status code management. Status codes in the ddcutil have multiple sources: 1) Linux system calls. - In general, functions return 0 or a positive value to indicate success. - Values greater than 0 indicate something about a successful call, such as the number of bytes read. - Negative values indicate that an error occurred. In that case the special variable errno is typically the "error code", though some packages set the return code to -errno. - Errno values, listed in errno.h, are positive numbers ranging from 1 to apparently less than 200. 2) ADL - ADL functions return status codes, listed in file adl_defines.h - The value of these codes ranges from 4 to -21. 0 indicates normal success. - Positive values appear to be "ok, but". Not clear when these values occur or what to do about them. - Negative values indicate errors, some of which may reflect programming errors. 3) ddcutil specific status codes. Problem: Linux and ADL error numbers conflict. ddcutil error numbers can be assigned to a range out of conflict. Solution. Mulitplexing. */ // Describes a status code range typedef struct { Retcode_Range_Id id; int base; int max; Retcode_Description_Finder desc_finder; bool finder_arg_is_modulated; Retcode_Number_Finder number_finder; Retcode_Number_Finder base_number_finder; } Retcode_Range_Table_Entry; // order must be kept consistent with Retcode_Range_Id // For explainers in files that are included by this file, the explainer // can be filled in statically. For other files, register_retcode_desc_finder() // is called by the initializer function in those files. Retcode_Range_Table_Entry retcode_range_table[] = { {.id = RR_ERRNO, .base = RCRANGE_ERRNO_START, .max = RCRANGE_ERRNO_MAX, // .desc_finder = NULL, // will be filled in by call to ... // .finder_arg_is_modulated = false, // ... register_retcode_desc_finder() .desc_finder = get_negative_errno_info, .finder_arg_is_modulated = true, // finder_arg_is_modulated // .number_finder = errno_name_to_modulated_number, .number_finder = errno_name_to_number, .base_number_finder = errno_name_to_number }, {.id = RR_ADL, .base = RCRANGE_ADL_START, .max = RCRANGE_ADL_MAX, // .desc_finder = NULL, // will be filled in by call to ... // .finder_arg_is_modulated = false, // ... register_retcode_desc_finder() #ifdef ADL .desc_finder = get_adl_status_description, .finder_arg_is_modulated = false, // finder_arg_is_modulated .number_finder = adl_error_name_to_modulated_number, // mock implementation if not HAVE_ADL .base_number_finder = adl_error_name_to_number // mock implementation if not HAVE_ADL #endif }, {.id = RR_DDC, .base = RCRANGE_DDC_START, .max = RCRANGE_DDC_MAX, .desc_finder = ddcrc_find_status_code_info, .finder_arg_is_modulated = true, // .number_finder = ddc_error_name_to_modulated_number, .number_finder = ddc_error_name_to_number, .base_number_finder = ddc_error_name_to_number }, }; int retcode_range_ct = sizeof(retcode_range_table)/sizeof(Retcode_Range_Table_Entry); static void validate_retcode_range_table() { int ndx = 0; for (;ndx < retcode_range_ct; ndx++) { // printf("ndx=%d, id=%d, base=%d\n", ndx, retcode_range_table[ndx].id, retcode_range_table[ndx].base); assert( retcode_range_table[ndx].id == ndx); } } #ifdef OLD /** This function is called by modules for specific status code ranges * to register the explanation routines for their * status codes. It exists to avoid circular dependencies of includes. * * @param id status code range id * @param finder_func function to return #Status_Code_Info struct for a status code, * of type #Retcode_Description_Finder * @param finder_arg_is_modulated if true, **finder_func** takes a modulated * status code as an argument. If false, it * takes an unmodualted value. * * @remark * This function will be executed from module initialization functions, which are called * from main before the command line is parsed, so trace control not yet configured */ void register_retcode_desc_finder( Retcode_Range_Id id, Retcode_Description_Finder finder_func, bool finder_arg_is_modulated) { bool debug = false; if (debug) printf("(%s) registering callback description finder for range id %d, finder_func=%p, finder_arg_is_modulated=%s\n", __func__, id, finder_func, bool_repr(finder_arg_is_modulated)); retcode_range_table[id].desc_finder = finder_func; retcode_range_table[id].finder_arg_is_modulated = finder_arg_is_modulated; } #endif /** Shifts a status code in the RR_BASE range to a specified range. * * @param rc base status code to modulate * @param range_id range to which status code should be modulated * * @return modulated status code * * @remark * It is an error to pass an already modulated status code as an argument to * this function. */ int modulate_rc(int rc, Retcode_Range_Id range_id){ bool debug = false; if (debug) printf("(%s) rc=%d, range_id=%d\n", __func__, rc, range_id); assert(range_id == RR_ADL); // assert( abs(rc) <= RCRANGE_BASE_MAX ); int base = retcode_range_table[range_id].base; if (rc != 0) { if (rc < 0) rc -= base; else rc += base; } if (debug) printf("(%s) Returning: %d\n", __func__, rc); return rc; } /** Shifts a status code from the specified modulation range to the base range * * @param rc status code to demodulate * @param range_id a modulation range * * @return demodulated status code * * @remark * It is an error to pass an unmodulated status code as an * argument to this function. */ int demodulate_rc(int rc, Retcode_Range_Id range_id) { // TODO: check that rc is in the specified modulation range // assert( abs(rc) > RCRANGE_BASE_MAX ); assert(range_id == RR_ADL); int base = retcode_range_table[range_id].base; if (rc != 0) { if (rc < 0) rc = rc + base; // rc = -((-rc)-base); else rc = rc-base; } return rc; } /** Determines the modulation range for a status code. * * @param rc status code to check * * @return range identifier (#Retcode_Range_Id) */ Retcode_Range_Id get_modulation(Public_Status_Code rc) { int ndx = 0; int abs_rc = abs(rc); Retcode_Range_Id range_id = RR_ERRNO; // assignment to avoid compiler warning for (;ndx < retcode_range_ct; ndx++) { if (abs_rc >= retcode_range_table[ndx].base && abs_rc <= retcode_range_table[ndx].max) { range_id = retcode_range_table[ndx].id; assert (range_id == ndx); break; } } assert(ndx < retcode_range_ct); // fails if not found // printf("(%s) rc=%d, returning %d\n", __func__, rc, range_id); return range_id; } static Status_Code_Info ok_status_code_info = {0, "OK", "success"}; // N.B. Works equally well whether argument is a Global_Status_Code or a // Public_Status_Code. get_modulaetion() figures things out /** Given a #Public_Status_Code, returns a pointer to the #Status_Code_Info struct. * describing it. * * @param status_code global (modulated) status code * @return pointer to #Status_Code_Info for status code, NULL if not found */ Status_Code_Info * find_status_code_info(Public_Status_Code status_code) { bool debug = false && status_code; // use printf() instead of DBGMSG to avoid circular includes DBGF(debug, "Starting. rc = %d", status_code); Status_Code_Info * pinfo = NULL; if (status_code == 0) pinfo = &ok_status_code_info; else { Retcode_Range_Id modulation = get_modulation(status_code); DBGF(debug,"modulation=%d", modulation); Retcode_Description_Finder finder_func = retcode_range_table[modulation].desc_finder; assert(finder_func != NULL); bool finder_arg_is_modulated = retcode_range_table[modulation].finder_arg_is_modulated; int rawrc = (finder_arg_is_modulated) ? status_code : demodulate_rc(status_code, modulation); if (debug) printf("(%s) rawrc = %d\n", __func__, rawrc); pinfo = finder_func(rawrc); } if (debug) { printf("(%s) Done. Returning %p\n", __func__, (void*)pinfo); if (pinfo) report_status_code_info(pinfo); } return pinfo; } #define GSC_WORKBUF_SIZE 300 /** Returns only the description string for a #Public_Status_Code. * Synthesizes a description if information for the status code cannot be found. * * @param psc status code number * @return string description of status code * * @remark * The value returned is valid until the next call of this function in the * same thread. Caller should not free. */ char * psc_text(Public_Status_Code psc) { static GPrivate psc_desc_key = G_PRIVATE_INIT(g_free); char * workbuf = get_thread_fixed_buffer(&psc_desc_key, GSC_WORKBUF_SIZE); Status_Code_Info * pinfo = find_status_code_info(psc); if (pinfo) { if (pinfo->description) snprintf(workbuf, GSC_WORKBUF_SIZE, "%s", pinfo->description); else snprintf(workbuf, GSC_WORKBUF_SIZE, "%s", pinfo->name); } else { snprintf(workbuf, GSC_WORKBUF_SIZE, "%d", psc); } return workbuf; } char * psc_desc(Public_Status_Code psc) { static GPrivate psc_desc_key = G_PRIVATE_INIT(g_free); char * workbuf = get_thread_fixed_buffer(&psc_desc_key, GSC_WORKBUF_SIZE); Status_Code_Info * pinfo = find_status_code_info(psc); if (pinfo) { snprintf(workbuf, GSC_WORKBUF_SIZE, "%s(%d): %s", pinfo->name, psc, pinfo->description); } else { snprintf(workbuf, GSC_WORKBUF_SIZE, "%d", psc ); } return workbuf; } /** Returns a string containing the symbolic name of a #Public_Status_Code, * followed by its numeric value. * * If the code is not recognized, the string contains only the numeric value. * * @param psc status code number * @return string description of status code * * @remark * The value returned is valid until the next call of this function in the * same thread. Caller should not free. */ char * psc_name_code(Public_Status_Code psc) { static GPrivate psc_desc_key = G_PRIVATE_INIT(g_free); char * workbuf = get_thread_fixed_buffer(&psc_desc_key, GSC_WORKBUF_SIZE); Status_Code_Info * pinfo = find_status_code_info(psc); if (pinfo) { snprintf(workbuf, GSC_WORKBUF_SIZE, "%s(%d)", pinfo->name, psc); } else { snprintf(workbuf, GSC_WORKBUF_SIZE, "%d", psc); } return workbuf; } #undef GSC_WORKBUF_SIZE /** Returns the symbolic name of a #Public_Status_Code * * @param status_code status code value * @return symbolic name, or "" if not found */ char * psc_name(Public_Status_Code status_code) { Status_Code_Info * pdesc = find_status_code_info(status_code); char * result = (pdesc) ? pdesc->name : ""; return result; } /** Given a status code name, convert it to a unmodulated base status code * Valid only for those status code ranges which ... * * * @param status_code_name * @param p_error_number where to return status code number * @return true if conversion successful, false if unrecognized status code */ bool status_name_to_unmodulated_number( const char * status_code_name, int * p_error_number) { bool debug = false; DBGF(debug,"status_code_name |%s|", status_code_name); int status_code = 0; bool found = false; for (int ndx = 0; ndx < retcode_range_ct; ndx++) { if (retcode_range_table[ndx].base_number_finder) { found = retcode_range_table[ndx].base_number_finder(status_code_name, &status_code); if (found) break; } } *p_error_number = status_code; if (debug) printf("(%s) Returning %s, *p_error_number = %d\n", __func__, sbool(found), *p_error_number); return found; } /** Given a status code symbolic name, convert it to #Public_Status_Code value. * * If the name is for an ADL status code, the value is modulated. * * @param status_code_name * @param p_error_number where to return status code number * @return true if conversion successful, false if unrecognized status code */ bool status_name_to_modulated_number( const char * status_code_name, Public_Status_Code * p_error_number) { Public_Status_Code psc = 0; bool found = false; for (int ndx = 0; ndx < retcode_range_ct; ndx++) { if (retcode_range_table[ndx].number_finder) { found = retcode_range_table[ndx].number_finder(status_code_name, &psc); if (found) break; } } *p_error_number = psc; return found; } // // Initialization and debugging // /** Initialize this module. */ void init_status_code_mgt() { // N.B called before command line parsed, so command line trace control not in effect validate_retcode_range_table(); // uses asserts to check consistency // error_counts_hash = g_hash_table_new(NULL,NULL); // initialize_ddcrc_desc(); } /** Display the contents of a #Status_Code_Info struct. * This is a debugging function. * * @param pdesc pointer to #Status_Code_Info struct */ void report_status_code_info(Status_Code_Info * pdesc) { printf("Status_Code_Info struct at %p\n", (void*)pdesc); if (pdesc) { printf("code: %d\n", pdesc->code); printf("name: %p: %s\n", pdesc->name, pdesc->name); printf("description: %p: %s\n", pdesc->description, pdesc->description); // printf("memoized_description: %p: %s\n", pdesc->memoized_description, pdesc->memoized_description); } } ddcutil-2.2.0/src/base/vcp_version.c0000644000175000001440000002421614572333721013036 /** @file vcp_version.c * * VCP (aka MCCS) version specification */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/string_util.h" #include "base/core.h" #include "base/vcp_version.h" // // MCCS version constants and utilities // const DDCA_MCCS_Version_Spec DDCA_VSPEC_V10 = {1,0}; ///< MCCS version 1.0 const DDCA_MCCS_Version_Spec DDCA_VSPEC_V20 = {2,0}; ///< MCCS version 2.0 const DDCA_MCCS_Version_Spec DDCA_VSPEC_V21 = {2,1}; ///< MCCS version 2.1 const DDCA_MCCS_Version_Spec DDCA_VSPEC_V30 = {3,0}; ///< MCCS version 3.0 const DDCA_MCCS_Version_Spec DDCA_VSPEC_V22 = {2,2}; ///< MCCS version 2.2 const DDCA_MCCS_Version_Spec DDCA_VSPEC_UNKNOWN = {0,0}; ///< value for monitor has been queried unsuccessfully const DDCA_MCCS_Version_Spec DDCA_VSPEC_ANY = {0,0}; ///< used as query specifier const DDCA_MCCS_Version_Spec DDCA_VSPEC_UNQUERIED = {0xff, 0xff}; ///< indicates version not queried /* Tests if a #DDCA_MCCS_Version_Spec value represents a valid MCCS version, * i.e. 1.0, 2.0, 2.1, 3.0, or 2.2. * * @param vspec value to test * @param allow_unknown allow 0.0 * * @return true/false */ bool vcp_version_is_valid(DDCA_MCCS_Version_Spec vspec, bool allow_unknown) { bool debug = false; DBGMSF(debug, "Starting. vspec=%d.%d, allow_unknown=%s", vspec.major, vspec.minor, SBOOL(allow_unknown)); bool result = vcp_version_eq(vspec, DDCA_VSPEC_V10) || vcp_version_eq(vspec, DDCA_VSPEC_V20) || vcp_version_eq(vspec, DDCA_VSPEC_V21) || vcp_version_eq(vspec, DDCA_VSPEC_V30) || vcp_version_eq(vspec, DDCA_VSPEC_V22) || (allow_unknown && vcp_version_eq(vspec,DDCA_VSPEC_UNKNOWN)); DBGMSF(debug, "Returning: %s", SBOOL(result)); return result; } const char * valid_vcp_versions = "1.0, 2.0, 2.1, 3.0, 2.2"; /** \file * Note that MCCS (VCP) versioning forms a directed graph, not a linear ordering. * * The v3.0 spec is an extension of v2.1, not v2.2. * Both v3.0 and v2.2 are successors to v2.1. * * -- v3.0 * | * v1.0---v2.0---- v2.1 * | * -- v2.2 * */ /** Checks if one #DDCA_MCCS_Version_Spec is less than or equal * to another. * * @param v1 first version spec * @param v2 second version spec * * @retval true v1 is <= v2 * @retval false v1 > v2 * * @remark * Aborts if an attempt is made to compare v2.2 with v3.0 * @remark * Will require modification if a new spec appears */ bool vcp_version_le(DDCA_MCCS_Version_Spec v1, DDCA_MCCS_Version_Spec v2) { bool debug = false; bool result = false; assert( vcp_version_is_valid(v1,false) && vcp_version_is_valid(v2,false) ); assert( !(vcp_version_eq(v1, DDCA_VSPEC_V22) && vcp_version_eq(v2, DDCA_VSPEC_V30)) && !(vcp_version_eq(v2, DDCA_VSPEC_V22) && vcp_version_eq(v1, DDCA_VSPEC_V30)) ); if (v1.major < v2.major) result = true; else if (v1.major == v2.major) { if (v1.minor <= v2.minor) result = true; } DBGMSF(debug, "v1=%d.%d <= v2=%d.%d returning: %s", v1.major, v2.minor, v2.major, v2.minor, sbool(result)); return result; } /** CHecks if one #DDCA_MCCS_Version_Spec is greater than another. * * See \see vcp_version_le for discussion of version comparison * * @param val first version * @param min second version * @return true/false */ bool vcp_version_gt(DDCA_MCCS_Version_Spec val, DDCA_MCCS_Version_Spec min) { return !vcp_version_le(val,min); } /** Test if two DDCA_MCCS_VersionSpec values are identical. * @param v1 first version * @param v2 second version * @return true/false */ bool vcp_version_eq(DDCA_MCCS_Version_Spec v1, DDCA_MCCS_Version_Spec v2){ return (v1.major == v2.major) && (v1.minor == v2.minor); } bool vcp_version_lt(DDCA_MCCS_Version_Spec v1, DDCA_MCCS_Version_Spec v2){ return vcp_version_gt(v2, v1); } // use if (vcp_version_eq(vspec, DDCA_VSPEC_UNQUERIED)) #ifdef DEPRECATED /** Tests if a #DDCA_MCCS_Version_Spec represents "unqueried". * * Encapsulates the use of a magic number. * * @param vspec version spec to test * @result true/false */ bool vcp_version_is_unqueried(DDCA_MCCS_Version_Spec vspec) { return (vspec.major == 0xff && vspec.minor == 0xff); } #endif /** Converts a #DDCA_MCCS_Version_Spec to a printable string, * handling the special values for unqueried and unknown. * * @param vspec version spec * @return string in the form "2.0" * @retval "Unqueried" for VCP_SPEC_UNQUERIED * @retval "Unknown" for VCP_SPEC_UNKNOWN */ char * format_vspec(DDCA_MCCS_Version_Spec vspec) { static GPrivate format_vspec_key = G_PRIVATE_INIT(g_free); char * private_buffer = get_thread_fixed_buffer(&format_vspec_key, 20); if ( vcp_version_eq(vspec, DDCA_VSPEC_UNQUERIED) ) strcpy(private_buffer, "Unqueried"); else if ( vcp_version_eq(vspec, DDCA_VSPEC_UNKNOWN) ) strcpy(private_buffer, "Unknown"); else g_snprintf(private_buffer, 20, "%d.%d", vspec.major, vspec.minor); // DBGMSG("Returning: |%s|", private_buffer); return private_buffer; } char * format_vspec_verbose(DDCA_MCCS_Version_Spec vspec) { bool debug = false; DBGMSF(debug, "Starting. vspec=%d.%d", vspec.major, vspec.minor); static GPrivate format_vspec_verbose_key = G_PRIVATE_INIT(g_free); char * private_buffer = get_thread_fixed_buffer(&format_vspec_verbose_key, 30); if ( vcp_version_eq(vspec, DDCA_VSPEC_UNQUERIED) ) g_snprintf(private_buffer, 30, "Unqueried (%d.%d)", vspec.major, vspec.minor); else if ( vcp_version_eq(vspec, DDCA_VSPEC_UNKNOWN) ) g_snprintf(private_buffer, 30, "Unknown (%d.%d)", vspec.major, vspec.minor); else g_snprintf(private_buffer, 20, "%d.%d", vspec.major, vspec.minor); DBGMSF(debug, "Returning: |%s|", private_buffer); return private_buffer; } #ifdef MCCS_VERSION_ID Value_Name_Title_Table version_id_table = { VNT(DDCA_MCCS_V10, "1.0"), VNT(DDCA_MCCS_V20, "2.0"), VNT(DDCA_MCCS_V21, "2.1"), VNT(DDCA_MCCS_V30, "3.0"), VNT(DDCA_MCCS_V22, "2.2"), VNT(DDCA_MCCS_VNONE, "unknown"), VNT_END }; /** Converts a #DDCA_MCCS_Version_Id to a humanly readable form, * e.g. "2.0". * * @param version_id version id value * @return value in external form. */ char * format_vcp_version_id(DDCA_MCCS_Version_Id version_id) { char * result2 = vnt_title(version_id_table, version_id); #ifndef NDEBUG char * result = NULL; switch (version_id) { case DDCA_MCCS_V10: result = "1.0"; break; case DDCA_MCCS_V20: result = "2.0"; break; case DDCA_MCCS_V21: result = "2.1"; break; case DDCA_MCCS_V30: result = "3.0"; break; case DDCA_MCCS_V22: result = "2.2"; break; case DDCA_MCCS_VNONE: result = "unknown"; break; case DDCA_MCCS_VANY: result = "any"; break; } assert(streq(result, result2)); #endif return result2; } /** Returns the symbolic name of a #DDCA_MCCS_Version_Id value. * * @param version_id version id value * @return symbolic name, e.g. "DDCA_V20"; */ char * vcp_version_id_name(DDCA_MCCS_Version_Id version_id) { bool debug = false; DBGMSF(debug, "Starting. version_id=%d", version_id); char * result = vnt_name(version_id_table, version_id); DBGMSF(debug, "Returning: %s", result); return result; } #endif /** Converts a string representation of an MCCS version, e.g. "2.2" * to a version spec (integer pair). * * @param s string to convert * @return integer pair of major and minor versions * retval DDCA_UNKNOWN if invalid string */ DDCA_MCCS_Version_Spec parse_vspec(char * s) { DDCA_MCCS_Version_Spec vspec; int ct = sscanf(s, "%hhd . %hhd", &vspec.major, &vspec.minor); if (ct != 2 || vspec.major > 3 || vspec.minor > 2) { vspec = DDCA_VSPEC_UNKNOWN; } return vspec; } #ifdef MCCS_VERSION_SPEC /** Converts a MCCS version spec (integer pair) to a version id (enumeration). * * @param vspec version spec * @return version id * @retval #DDCA_VUNK if vspec does not represent a valid MCCS version */ DDCA_MCCS_Version_Id mccs_version_spec_to_id(DDCA_MCCS_Version_Spec vspec) { DDCA_MCCS_Version_Id result = DDCA_MCCS_VUNK; // initialize to avoid compiler warning if (vspec.major == 1 && vspec.minor == 0) result = DDCA_MCCS_V10; else if (vspec.major == 2 && vspec.minor == 0) result = DDCA_MCCS_V20; else if (vspec.major == 2 && vspec.minor == 1) result = DDCA_MCCS_V21; else if (vspec.major == 3 && vspec.minor == 0) result = DDCA_MCCS_V30; else if (vspec.major == 2 && vspec.minor == 2) result = DDCA_MCCS_V22; else if (vspec.major == 2 && vspec.minor == 1) result = DDCA_MCCS_V21; else if (vspec.major == 0 && vspec.minor == 0) result = DDCA_MCCS_VUNK; // case UNQUERIED should never arise else { PROGRAM_LOGIC_ERROR("Unexpected version spec value %d.%d", vspec.major, vspec.minor); assert(false); result = DDCA_MCCS_VUNK; // in case assertions turned off } return result; } /** Converts a MCCS version id (enumerated value) to * a version spec (integer pair). * * @param id version id * @return version spec */ DDCA_MCCS_Version_Spec mccs_version_id_to_spec(DDCA_MCCS_Version_Id id) { bool debug = false; DBGMSF(debug, "Starting. id=%d", id); DDCA_MCCS_Version_Spec vspec = DDCA_VSPEC_ANY; // use table instead? switch(id) { case DDCA_MCCS_VNONE: vspec = DDCA_VSPEC_UNKNOWN; break; case DDCA_MCCS_VANY: vspec = DDCA_VSPEC_ANY; break; case DDCA_MCCS_V10: vspec = DDCA_VSPEC_V10; break; case DDCA_MCCS_V20: vspec = DDCA_VSPEC_V20; break; case DDCA_MCCS_V21: vspec = DDCA_VSPEC_V21; break; case DDCA_MCCS_V30: vspec = DDCA_VSPEC_V30; break; case DDCA_MCCS_V22: vspec = DDCA_VSPEC_V22; break; } DBGMSF(debug, "Returning: %d.%d", vspec.major, vspec.minor); return vspec; } #endif ddcutil-2.2.0/src/base/per_display_data.c0000644000175000001440000007772514634376340014025 /** @file per_display_data.c */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include #include #include "util/debug_util.h" #include "util/glib_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/display_retry_data.h" // temp circular #include "base/displays.h" #include "base/dsa2.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/per_thread_data.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/per_display_data.h" #define TRACE_GROUP DDCA_TRC_NONE // Master table of sleep data for all displays GHashTable * per_display_data_hash = NULL; // // Locking // static GPrivate pdd_this_thread_has_lock; static GPrivate pdd_lock_depth; // GINT_TO_POINTER(0); static bool debug_mutex = false; static int pdd_lock_count = 0; static int pdd_unlock_count = 0; static int pdd_cross_thread_operation_blocked_count = 0; DDCA_Sleep_Multiplier default_user_sleep_multiplier = 1.0; // may be changed by --sleep-multiplier option User_Multiplier_Source default_user_multiplier_source = Default; void dbgrpt_per_display_data_locks(int depth) { rpt_vstring(depth, "pdd_lock_count: %-4d", pdd_lock_count); rpt_vstring(depth, "pdd_unlock_count: %-4d", pdd_unlock_count); rpt_vstring(depth, "pdd_cross_thread_operation_blocked_count: %-4d", pdd_cross_thread_operation_blocked_count); } static GMutex try_data_mutex; /** If **try_data_mutex** is not already locked by the current thread, * lock it. * * \remark * This function is necessary because the behavior if a GLib mutex is * relocked by the current thread is undefined. */ // avoids locking if this thread already owns the lock, since behavior undefined bool pdd_lock_if_unlocked() { bool debug = false; debug = debug || debug_mutex; bool lock_performed = false; bool thread_has_lock = GPOINTER_TO_INT(g_private_get(&pdd_this_thread_has_lock)); DBGMSF(debug, "Already locked: %s", sbool(thread_has_lock)); if (!thread_has_lock) { g_mutex_lock(&try_data_mutex); lock_performed = true; // should this be a depth counter rather than a boolean? g_private_set(&pdd_this_thread_has_lock, GINT_TO_POINTER(true)); if (debug) { intmax_t cur_thread_id = get_thread_id(); DBGMSG("Locked by thread %d", cur_thread_id); } } DBGMSF(debug, "Returning: %s", sbool(lock_performed) ); return lock_performed; } /** Unlocks the **try_data_mutex** set by a call to #lock_if_unlocked * * \param unlock_requested perform unlock */ void pdd_unlock_if_needed(bool unlock_requested) { bool debug = false; debug = debug || debug_mutex; DBGMSF(debug, "unlock_requested=%s", sbool(unlock_requested)); if (unlock_requested) { // is it actually locked? bool currently_locked = GPOINTER_TO_INT(g_private_get(&pdd_this_thread_has_lock)); DBGMSF(debug, "currently_locked = %s", sbool(currently_locked)); if (currently_locked) { g_private_set(&pdd_this_thread_has_lock, GINT_TO_POINTER(false)); if (debug) { intmax_t cur_thread_id = get_thread_id(); DBGMSG("Unlocked by thread %d", cur_thread_id); } g_mutex_unlock(&try_data_mutex); } } DBGMSF(debug, "Done"); } static bool cross_thread_operation_active = false; static GMutex cross_thread_operation_mutex; static pid_t cross_thread_operation_owner; // The locking strategy relies on the fact that in practice conflicts // will be rare, and critical sections short. // Operations are blocked only using a spin-lock. // The groups of operations: // - Operations that operate on the single Per_Display_Data instance // associated with the currently executing thread. // - Operations that operate on a single Per_Display_Data instance, // but possibly not from the thread associated with the Per_Display_Data instance. ??? // - Operations that operate on multiple Per_Display_Data instances. // These are referred to as cross thread operations. // Alt, perhaps clearer, refer to them as multi-thread data instances. /** */ bool pdd_cross_display_operation_start(const char * caller) { // Only 1 cross display action can be active at one time. // All per_display actions must wait bool debug = false; debug = debug || debug_mutex; bool lock_performed = false; int display_lock_depth = GPOINTER_TO_INT(g_private_get(&pdd_lock_depth)); DBGTRC_STARTING(debug, DDCA_TRC_NONE, "Caller %s, lock depth: %d. pdd_lock_count=%d, pdd_unlock_count=%d", caller, display_lock_depth, pdd_lock_count, pdd_unlock_count); if (display_lock_depth == 0) { // (A) // if (!thread_has_lock) { // display_lock_depth is per-thread, so must be unchanged from (A) g_mutex_lock(&cross_thread_operation_mutex); lock_performed = true; cross_thread_operation_active = true; pdd_lock_count++; Thread_Output_Settings * thread_settings = get_thread_settings(); intmax_t cur_thread_id = thread_settings->tid; // alt: get_thread_id() cross_thread_operation_owner = cur_thread_id; DBGMSF(debug, " Locked performed by thread %d", cur_thread_id); sleep_millis(10); // give all per-thread functions time to finish } display_lock_depth+=1; g_private_set(&pdd_lock_depth, GINT_TO_POINTER(display_lock_depth)); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Caller: %s, pdd_display_lock_depth=%d, pdd_lock_count=%d, pdd_unlock_cound=%d, Returning lock_performed: %s,", caller, display_lock_depth, pdd_lock_count, pdd_unlock_count, sbool(lock_performed)); return lock_performed; } void pdd_cross_display_operation_end(const char * caller) { bool debug = false; int display_lock_depth = GPOINTER_TO_INT(g_private_get(&pdd_lock_depth)); DBGTRC_STARTING(debug, DDCA_TRC_NONE, "Caller: %s, display_lock_depth=%d, pdd_lock_count=%d, pdd_unlock_count=%d", caller, display_lock_depth, pdd_lock_count, pdd_unlock_count); assert(display_lock_depth >= 1); g_private_set(&pdd_lock_depth, GINT_TO_POINTER(display_lock_depth-1)); if (display_lock_depth == 1) { cross_thread_operation_active = false; cross_thread_operation_owner = 0; pdd_unlock_count++; assert(pdd_lock_count == pdd_unlock_count); g_mutex_unlock(&cross_thread_operation_mutex); } else { assert( pdd_lock_count > pdd_unlock_count ); } display_lock_depth -= 1; DBGTRC_DONE(debug, DDCA_TRC_NONE, "Caller: %s, display_lock_depth=%d, pdd_lock_count=%d, pdd_unlock_count=%d", caller, display_lock_depth, pdd_lock_count, pdd_unlock_count); } /** Block execution of single Per_Display_Data operations when an operation * involving multiple Per_Thead_Data instances is active. */ void pdd_cross_display_operation_block(const char * caller) { // intmax_t cur_displayid = get_display_id(); Thread_Output_Settings * thread_settings = get_thread_settings(); intmax_t cur_displayid = thread_settings->tid; if (cross_thread_operation_active && cur_displayid != cross_thread_operation_owner) { __sync_fetch_and_add(&pdd_cross_thread_operation_blocked_count, 1); do { sleep_millis(10); } while (cross_thread_operation_active); } } // GDestroyNotify: void (*GDestroyNotify) (gpointer data); void per_display_data_destroy(void * data) { if (data) { Per_Display_Data * pdd = data; free(pdd); } } // // Sleep Multiplier Factor // const char * user_multiplier_source_name(User_Multiplier_Source source) { char * s = NULL; switch(source) { case Default: s = "Implicit"; break; case Explicit: s = "Explicit"; break; case Reset: s = "Reset"; break; } return s; } /** Sets the default sleep multiplier factor, used for the creation of any new displays. * This is a global value and is a floating point number. * * @param multiplier * * @remark Intended for use only during program initialization. If used * more generally, get and set of default sleep multiplier needs to * be protected by a lock. * @todo * Add Sleep_Event_Type bitfield to make sleep factor dependent on event type? */ void pdd_set_default_sleep_multiplier_factor( DDCA_Sleep_Multiplier multiplier, User_Multiplier_Source source) { bool debug = false; DBGTRC(debug, DDCA_TRC_NONE, "Executing. Setting default_sleep_multiplier_factor = %6.3f, explicit = %s", multiplier, user_multiplier_source_name(source)); assert(multiplier >= 0); // still needed? // if (multiplier == 0.0f) // multiplier = .01; default_user_sleep_multiplier = multiplier; default_user_multiplier_source = source; } /** Gets the default sleep multiplier factor. * * @return sleep multiplier factor */ DDCA_Sleep_Multiplier pdd_get_default_sleep_multiplier_factor() { bool debug = false; DBGTRC(debug, DDCA_TRC_NONE, "Returning default_sleep_multiplier_factor = %6.3f", default_user_sleep_multiplier); return default_user_sleep_multiplier; } #ifdef UNUSED /** Sets the sleep multiplier factor for the current display. * * @param factor sleep multiplier factor */ void pdd_set_sleep_multiplier_factor(Per_Display_Data * data, DDCA_Sleep_Multiplier factor) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "factor = %6.3f", factor); assert(factor >= 0); data->default_user_sleep_multiplier = factor; DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } /** Gets the sleep multiplier factor for the current display. * * @return sleep multiplier factor */ DDCA_Sleep_Multiplier pdd_get_sleep_multiplier_factor(Per_Display_Data * data) { bool debug = false; DDCA_Sleep_Multiplier result = data->default_user_sleep_multiplier; DBGTRC(debug, DDCA_TRC_NONE, "Returning %6.3f", result ); return result; } #endif #ifdef UNUSED // apply the sleep-multiplier to any existing displays // it will be set for new displays from global_sleep_multiplier_factor void set_sleep_multiplier_factor_all(DDCA_Sleep_Multiplier factor) { // needs mutex bool debug = false; DBGMSF(debug, "Starting. factor = %5.2f", factor); if (display_sleep_data_hash) { GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter,display_sleep_data_hash); while (g_hash_table_iter_next (&iter, &key, &value)) { Per_Display_Data * data = value; DBGMSF(debug, "Thread id: %d", data->display_id); data->default_user_sleep_multiplier = factor; } } } default_dynamic_sleep_enabled void set_global_sleep_multiplier_factor(DDCA_Sleep_Multiplier factor) { bool debug = false; DBGMSF(debug, "factor = %5.2f", factor); global_sleep_multiplier_factor = factor; // set_sleep_multiplier_factor_all(factor); // only applies to new displays, do not change existing displays } DDCA_Sleep_Multiplier get_global_sleep_multiplier_factor() { return global_sleep_multiplier_factor; } #endif /** Initializes a newly allocated #Per_Display_Data struct * * @oaram pdd pointer to instance to initialize */ void pdd_init_pdd(Per_Display_Data * pdd) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "Initializing Per_Display_Data for %s", dpath_repr_t(&pdd->dpath)); pdd->user_sleep_multiplier = default_user_sleep_multiplier; pdd->user_multiplier_source = default_user_multiplier_source; pdd->initial_adjusted_sleep_multiplier = -1.0f; pdd->final_successful_adjusted_sleep_multiplier = -1.0f; pdd->most_recent_adjusted_sleep_multiplier = -1.0f; pdd->total_sleep_time_millis = 0; pdd->dsa2_enabled = pdd->dpath.io_mode == DDCA_IO_I2C && dsa2_is_enabled(); if (pdd->dsa2_enabled) { pdd->dsa2_data = dsa2_get_results_table_by_busno(pdd->dpath.path.i2c_busno, true); } pdd->dynamic_sleep_active = true; for (int ndx=0; ndx < RETRY_OP_COUNT; ndx++) { pdd->try_stats[0].retry_op = WRITE_ONLY_TRIES_OP; pdd->try_stats[1].retry_op = WRITE_READ_TRIES_OP; pdd->try_stats[2].retry_op = MULTI_PART_READ_OP; pdd->try_stats[3].retry_op = MULTI_PART_WRITE_OP; } pdd->min_successful_sleep_multiplier = -1.0; pdd->max_successful_sleep_multiplier = -1.0; pdd->total_successful_sleep_multiplier = 0; pdd->successful_sleep_multiplier_ct = 0; DBGTRC_DONE(debug, DDCA_TRC_NONE, "Device = %s, user_sleep_multiplier=%4.2f", dpath_repr_t(&pdd->dpath), pdd->user_sleep_multiplier); if (debug) dbgrpt_per_display_data(pdd, 1); } /** Gets the #Per_Display_Data struct for a specified display. * If the struct does not already exist, it is allocated and initialized. * * @param dpath device access path * @return pointer to #Per_Display_Data struct * * @remark * Historical comment from per-thread data. Does this still matter? * The structs are maintained centrally rather than using a thread-local pointer * to a block on the heap because the of a problems when the thread is closed. * Valgrind complains of access errors for closed threads, even though the * struct is on the heap and still readable. */ Per_Display_Data * pdd_get_per_display_data(DDCA_IO_Path dpath, bool create_if_not_found) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Getting per display data for %s, create_if_not_found = %s", dpath_repr_t(&dpath), sbool(create_if_not_found)); bool this_function_owns_lock = pdd_lock_if_unlocked(); assert(per_display_data_hash); // allocated by init_display_data_module() int hval = dpath_hash(dpath); Per_Display_Data * pdd = g_hash_table_lookup(per_display_data_hash, GINT_TO_POINTER(hval)); if (!pdd && create_if_not_found) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Per_Display_Data not found for %s", dpath_repr_t(&dpath)); pdd = g_new0(Per_Display_Data, 1); pdd->dpath = dpath; g_private_set(&pdd_lock_depth, GINT_TO_POINTER(0)); pdd_init_pdd(pdd); g_hash_table_insert(per_display_data_hash, GINT_TO_POINTER(hval), pdd); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Created Per_Display_Data struct for %s", dpath_repr_t(&pdd->dpath)); DBGMSF(debug, "per_display_data_hash size=%d", g_hash_table_size(per_display_data_hash)); if (debug) dbgrpt_per_display_data(pdd, 1); } pdd_unlock_if_needed(this_function_owns_lock); DBGTRC_NOPREFIX( debug, TRACE_GROUP, "Device dpath:%s", dpath_repr_t(&dpath) ); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, Per_Display_Data, dbgrpt_per_display_data, pdd); return pdd; } /** Controls whether dynamic sleep is to be applied to sleep multiplier * calls, even when dynamic sleep is enabled. * * Used to temporarily suspend dynamic sleep multiplier adjustment. * * @param pdd #Per_Display_Data instance * @param onoff */ bool pdd_set_dynamic_sleep_active(Per_Display_Data * pdd, bool onoff) { bool old = pdd->dynamic_sleep_active; pdd->dynamic_sleep_active = onoff; return old; } bool pdd_is_dynamic_sleep_active(Per_Display_Data * pdd) { return pdd->dynamic_sleep_active; } /** Notes use of the current sleep multiplier. * * Updates both the most_recent_adjusted_sleep_multiplier and * if the use was successful, final_adjusted_sleep_multiplier. * * @param pdd #Per_Display_Data instance * @param successful was the use successful */ void pdd_record_adjusted_sleep_multiplier(Per_Display_Data * pdd, bool successful) { assert(pdd); bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "bus=%d, initial_adjusted_sleep_multiplier = %4.2f", pdd->dpath.path.i2c_busno, pdd->initial_adjusted_sleep_multiplier); DDCA_Sleep_Multiplier cur_sleep_multiplier = pdd_get_adjusted_sleep_multiplier(pdd); if (cur_sleep_multiplier >= 0) { if (pdd->initial_adjusted_sleep_multiplier < 0.0f) // if not yet set pdd->initial_adjusted_sleep_multiplier = cur_sleep_multiplier; if (successful) { pdd->final_successful_adjusted_sleep_multiplier = cur_sleep_multiplier; pdd->successful_sleep_multiplier_ct ++; pdd->total_successful_sleep_multiplier += cur_sleep_multiplier; if (pdd->max_successful_sleep_multiplier < 0) { pdd->max_successful_sleep_multiplier = cur_sleep_multiplier; } else { if (cur_sleep_multiplier > pdd->max_successful_sleep_multiplier) pdd->max_successful_sleep_multiplier = cur_sleep_multiplier; } if (pdd->min_successful_sleep_multiplier < 0) { pdd->min_successful_sleep_multiplier = cur_sleep_multiplier; } else { if (cur_sleep_multiplier < pdd->min_successful_sleep_multiplier) pdd->min_successful_sleep_multiplier = cur_sleep_multiplier; } } } DBGTRC_DONE(debug, DDCA_TRC_NONE, "cur_sleep_multiplier=%4.2f, initial_adjusted_sleep_multiplier = %4.2f, final_successful_adjusted_sleep_multiplier=%4.2f", cur_sleep_multiplier, pdd->initial_adjusted_sleep_multiplier, pdd->final_successful_adjusted_sleep_multiplier); } /** Output a debug report of a #Per_Display_Data struct. * * @param data pointer to #Per_Display_Data struct * @param depth logical indentation level * * // relies on caller for possible blocking */ void dbgrpt_per_display_data(Per_Display_Data * pdd, int depth) { int d1 = depth+1; rpt_structure_loc("Per_Display_Data", pdd, depth); //rpt_int( "sizeof(Per_Display_Data)", NULL, sizeof(Per_Display_Data), d1); rpt_vstring(d1, "dpath : %s", dpath_repr_t(&pdd->dpath) ); rpt_vstring(d1, "dsa2_enabled : %s", sbool(pdd->dsa2_enabled)); // Sleep multiplier adjustment: rpt_vstring(d1, "user_sleep_multiplier : %3.2f", pdd->user_sleep_multiplier); rpt_vstring(d1, "user_multiplier_source : %s", user_multiplier_source_name(pdd->user_multiplier_source)); rpt_vstring(d1, "initial_adjusted_sleep_multiplier : %3.2f", pdd->initial_adjusted_sleep_multiplier); rpt_vstring(d1, "final_successful_adjusted_sleep_multiplier : %3.2f", pdd->final_successful_adjusted_sleep_multiplier); rpt_vstring(d1, "most_recent_adjusted_sleep_multiplier : %3.2f", pdd->most_recent_adjusted_sleep_multiplier); rpt_vstring(d1, "total_sleep_multiplier_millis : %d", pdd->total_sleep_time_millis); rpt_vstring(d1, "cur_loop_null_msg_ct : %d", pdd->cur_loop_null_msg_ct); rpt_vstring(d1, "dsa2_enabled : %s", sbool(pdd->dsa2_enabled)); rpt_vstring(d1, "dynamic_sleep_active : %s", sbool(pdd->dynamic_sleep_active)); rpt_vstring(d1, "cur_loop_null_adjustment_occurred : %s", sbool(pdd->cur_loop_null_adjustment_occurred)); rpt_vstring(d1, "successful_sleep_multiplier_ct : %d", pdd->successful_sleep_multiplier_ct); rpt_vstring(d1, "total_successful_sleep_multiplier : %5.2f", pdd->total_successful_sleep_multiplier); rpt_vstring(d1, "average successful sleep _multiplier : %3.2f", pdd->total_successful_sleep_multiplier/pdd->successful_sleep_multiplier_ct); rpt_vstring(d1, "min_successful_sleep_multiplier : %3.2f", pdd->min_successful_sleep_multiplier); rpt_vstring(d1, "max_successful_sleep_multiplier : %3.2f", pdd->max_successful_sleep_multiplier); // Maxtries history for (int retry_type = 0; retry_type < 4; retry_type++) { char * buf = int_array_to_string( pdd->try_stats[retry_type].counters, MAX_MAX_TRIES+1); rpt_vstring(d1, "try_stats[%d=%-27s].counters = %s", retry_type, retry_type_name(retry_type), buf); free(buf); } } /** Applies a specified function with signature GFunc to all * #Per_Display_Data instances. * * @param func function to apply * \parm arg an arbitrary argument passed as a pointer * * This is a multi-instance operation. */ void pdd_apply_all(Pdd_Func func, void * arg) { pdd_cross_display_operation_start(__func__); bool debug = false; assert(per_display_data_hash); // allocated by init_display_data_module() GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter,per_display_data_hash); while (g_hash_table_iter_next (&iter, &key, &value)) { Per_Display_Data * data = value; DBGMSF(debug, "Thread id: %d", data->dpath); func(data, arg); } pdd_cross_display_operation_end(__func__); } /** Apply a given function to all #Per_Display_Data structs, ordered by display id. * Note that this report includes structs for displays that have been closed. * * @param func function to apply * @param arg pointer or integer value * * This is a multi-instance operation. */ void pdd_apply_all_sorted(Pdd_Func func, void * arg) { bool debug = false; DBGMSF(debug, "Starting"); pdd_cross_display_operation_start(__func__); assert(per_display_data_hash); DBGMSF(debug, "hash table size = %d", g_hash_table_size(per_display_data_hash)); GList * keys = g_hash_table_get_keys (per_display_data_hash); GList * new_head = g_list_sort(keys, gaux_ptr_intcomp); GList * l; for (l = new_head; l != NULL; l = l->next) { int key = GPOINTER_TO_INT(l->data); DBGMSF(debug, "Key: %d", key); Per_Display_Data * data = g_hash_table_lookup(per_display_data_hash, l->data); assert(data); func(data, arg); } g_list_free(new_head); // would keys also work? pdd_cross_display_operation_end(__func__); DBGMSF(debug, "Done"); } // typedef void (*Pdd_Func)(Per_Display_Data * data, void * arg); void pdd_enable_dynamic_sleep(Per_Display_Data * pdd, void * arg) { pdd->dsa2_enabled = true; } void pdd_disable_dynamic_sleep(Per_Display_Data * pdd, void * arg) { pdd->dsa2_enabled = false; } void pdd_enable_dynamic_sleep_all(bool onoff) { dsa2_enable(onoff); if (onoff) { pdd_apply_all(pdd_enable_dynamic_sleep, NULL); } else { pdd_apply_all(pdd_disable_dynamic_sleep, NULL); } } bool pdd_is_dynamic_sleep_enabled() { return dsa2_is_enabled(); } #ifdef UNUSED void pdd_reset_per_display_data(Per_Display_Data * data, void* arg ) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "data = %p, dpath=%s", data, dpath_repr_t(&data->dpath)); Per_Display_Data * pdd = data; pdd->total_sleep_time_millis = 0.0; #ifdef NO // does not apply if (pdd->dsa0_data) dsa0_reset(pdd->dsa0_data); if (pdd->dsa1_data) dsa1_reset_data(pdd->dsa1_data); if (dsa2_enabled) dsa2_reset(pdd->dsa2_data); #endif for (int retry_type = 0; retry_type < 4; retry_type++) { for (int ndx = 0; ndx < MAX_MAX_TRIES+2; ndx++) { pdd->try_stats[retry_type].counters[ndx] = 0; } } DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } void pdd_reset_all() { pdd_cross_display_operation_block(__func__); pdd_apply_all(pdd_reset_per_display_data, NULL); pdd_cross_display_operation_end(__func__); } #endif #ifdef UNUSED /** Emits a brief summary of a #Per_Display_Data instance, * showing the display id number and description. * * pdd pointer to #Per_Display_Data instance * arg logical indentation * * @note * This function has a GFunc signature * @note * Called only by multi-display-data functions that hold lock */ void pdd_display_summary(Per_Display_Data * pdd, void * arg) { int depth = GPOINTER_TO_INT(arg); int d1 = depth+1; pdd_cross_display_operation_block(__func__); // simple but ugly // rpt_vstring(depth, "Thread: %d. Description:%s", // pdd->display_id, pdd->description); // rpt_vstring(depth, "Thread: %d", pdd->display_id); // char * header = "Description: "; char header[100]; g_snprintf(header, 100, "Display path %s: ", dpath_repr_t(&pdd->dpath)); rpt_vstring(d1, "%s", header); } /** Emits a brief summary (display id and description) for each * #Per_Display_Data instance. * * @param depth logical indentation depth */ void pdd_list_displays(int depth) { // bool this_function_owns_lock = pdd_lock_if_unlocked(); int d1 = depth +1; // rpt_label(depth, "Have data for displays:"); rpt_label(depth, "Report has per-display data for displays:"); pdd_apply_all_sorted(pdd_display_summary, GINT_TO_POINTER(d1)); rpt_nl(); } #endif /** Function called for option "--vstats errors" * * @oaram depth logical indentation depth */ void pdd_report_all_per_display_error_counts(int depth) { bool debug = false; DBGMSF(debug, "Starting"); rpt_label(depth, "No per-display status code statistics are collected"); rpt_nl(); DBGMSF(debug, "Done"); } /** Function called for option "--vstats calls" * * @oaram depth logical indentation depth */ void pdd_report_all_per_display_call_stats(int depth) { bool debug = false; DBGMSF(debug, "Starting"); rpt_label(depth, "No per-display call statistics are collected"); rpt_nl(); DBGMSF(debug, "Done"); } /** Reports "--vstats elapsed" or "--istats elapsed" data for a single display * * @param pdd Per_Display_Data * @param include_dsa_internal report internal dsa stats, if available * @oaram depth logical indentation depth */ void pdd_report_elapsed(Per_Display_Data * pdd, bool include_dsa_internal, int depth) { // DBGMSG("include_dsa_internal=%s", sbool(include_dsa_internal)); // bool debug = false; rpt_vstring(depth, "Elapsed time report for display %s", dpath_short_name_t(&pdd->dpath)); int d1 = depth+1; const char * s0 = user_multiplier_source_name(pdd->user_multiplier_source); char * s1 = (pdd->dsa2_enabled && dsa2_is_from_cache(pdd->dsa2_data) ? " from cache" : "" ); rpt_vstring(d1, "User sleep multiplier factor: %7.2f %s", pdd->user_sleep_multiplier, s0); rpt_vstring(d1, "Initial adjusted multiplier: %7.2f%s", pdd->initial_adjusted_sleep_multiplier, s1); if (pdd->final_successful_adjusted_sleep_multiplier < 0.0) rpt_vstring(d1, "Final adjusted multiplier: Not set"); else rpt_vstring(d1, "Final adjusted multiplier: %7.2f", pdd->final_successful_adjusted_sleep_multiplier); rpt_vstring(d1, "Total sleep time (milliseconds): %5d", pdd->total_sleep_time_millis); rpt_nl(); char buf[20]; #define FVAL(_title, _val) \ do { \ if (_val == -1.0f) \ strcpy(buf, "Not set"); \ else \ g_snprintf(buf, 20, "%3.2f", _val); \ rpt_vstring(d1, _title " %s", buf); \ } while (0) rpt_vstring(d1, "Successful sleep multiplier count: %d", pdd->successful_sleep_multiplier_ct); FVAL("Minimum successful sleep multiplier:", pdd->min_successful_sleep_multiplier); FVAL("Maximum successful sleep multiplier:", pdd->max_successful_sleep_multiplier); double avg = (pdd->successful_sleep_multiplier_ct == 0) ? -1.0f : pdd->total_successful_sleep_multiplier/ pdd->successful_sleep_multiplier_ct; FVAL("Average successful sleep multiplier:", avg); #undef FVAL rpt_nl(); if (include_dsa_internal) { if (pdd->dsa2_enabled) { dsa2_report_internal(pdd->dsa2_data, d1); // detailed internal info rpt_nl(); } } } /** Reports "--vstats elapsed" or "--istats elapsed" data for all displays * * @param pdd Per_Display_Data * @param include_dsa_internal report internal dsa stats, if available * @oaram depth logical indentation depth */ void pdd_report_all_per_display_elapsed_stats(bool include_dsa_internal, int depth) { rpt_label(depth, "Per display elapsed time"); for (int ndx = 0; ndx <= I2C_BUS_MAX; ndx++) { DDCA_IO_Path dpath; dpath.io_mode = DDCA_IO_I2C; dpath.path.i2c_busno = ndx; Per_Display_Data * pdd = pdd_get_per_display_data(dpath, false); if (pdd) pdd_report_elapsed(pdd, include_dsa_internal, depth+1); } } /** Resets the sleep-multiplier value for a display * * @param pdd #Per_Display_Data instance * @param multiplier new sleep-multiplier value */ void pdd_reset_multiplier(Per_Display_Data * pdd, DDCA_Sleep_Multiplier multiplier) { pdd->user_sleep_multiplier = multiplier; pdd->user_multiplier_source = Reset; if (pdd->dsa2_enabled) { dsa2_reset_results_table(pdd->dpath.path.i2c_busno, multiplier); } } /** Returns the sleep-multiplier in effect for the specified display. * * The sleep-multiplier is, in descending order * - Obtained from the dynamic sleep algorithm, if one is in effect * - Obtained from the command line or configuration file * - Default sleep-multiplier (1.0) * * @param pdd Per_Display_Data for the display * @return sleep-multiplier */ DDCA_Sleep_Multiplier pdd_get_adjusted_sleep_multiplier(Per_Display_Data * pdd) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "pdd=%p, cur_loop_null_msg_ct=%d", pdd,pdd->cur_loop_null_msg_ct); float result = 1.0f; if (pdd->dynamic_sleep_active && pdd->dsa2_enabled) { result = dsa2_get_adjusted_sleep_mult(pdd->dsa2_data); } else { result = pdd->user_sleep_multiplier; } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %5.2f", result); return result; } /** Called from the retry loop when a retryable failure occurs in a write-read operation. * * Note this is NOT called when the final try in a write-read loop fails. * * @param pdd per display data instance * @param ddcrc status code of write-read operation * @param remaining_tries tries remaining in loop * * */ void pdd_note_retryable_failure(Per_Display_Data * pdd, DDCA_Status ddcrc, int remaining_tries) { if (pdd->dynamic_sleep_active) { if (pdd->dsa2_enabled) { dsa2_note_retryable_failure(pdd->dsa2_data, ddcrc, remaining_tries); } pdd_record_adjusted_sleep_multiplier(pdd, false); if (ddcrc == DDCRC_NULL_RESPONSE) pdd->cur_loop_null_msg_ct++; } } /** Called after then final try in a write-read retry loop, which may have succeeded or failed. * * @param pdd * @param ddcrc * @param tries number of tries that occurred * * Resets the per-loop counters for the next retryable operation. */ void pdd_record_final(Per_Display_Data * pdd, DDCA_Status ddcrc, int tries) { if (pdd->dynamic_sleep_active) { if (pdd->dsa2_enabled) { dsa2_record_final(pdd->dsa2_data, ddcrc, tries, pdd->cur_loop_null_adjustment_occurred); } pdd_record_adjusted_sleep_multiplier(pdd, ddcrc==0); } pdd->cur_loop_null_msg_ct = 0; pdd->cur_loop_null_adjustment_occurred = false; } // // Wrappers invoking Per_Display_Data functions by Display_Handle // void pdd_reset_multiplier_by_dh( Display_Handle * dh, DDCA_Sleep_Multiplier multiplier) { pdd_reset_multiplier(dh->dref->pdd, multiplier); } DDCA_Sleep_Multiplier pdd_get_sleep_multiplier_by_dh(Display_Handle * dh) { return pdd_get_adjusted_sleep_multiplier(dh->dref->pdd); } void pdd_note_retryable_failure_by_dh( Display_Handle * dh, DDCA_Status ddcrc, int remaining_tries) { pdd_note_retryable_failure(dh->dref->pdd, ddcrc, remaining_tries); } void pdd_record_final_by_dh(Display_Handle * dh, DDCA_Status ddcrc, int retries) { pdd_record_final(dh->dref->pdd, ddcrc, retries); } // // Initialization and Termination // void init_per_display_data() { RTTI_ADD_FUNC(pdd_get_per_display_data); RTTI_ADD_FUNC(pdd_cross_display_operation_start); RTTI_ADD_FUNC(pdd_cross_display_operation_end); RTTI_ADD_FUNC(pdd_get_adjusted_sleep_multiplier); per_display_data_hash = g_hash_table_new_full(g_direct_hash, NULL, NULL, per_display_data_destroy); } void terminate_per_display_data() { if (per_display_data_hash) { g_hash_table_destroy(per_display_data_hash); } } ddcutil-2.2.0/src/base/display_retry_data.c0000644000175000001440000002610114634171455014362 /** \file display_retry_data.c * * Maintains retry counts and max try settings on a per thread basis. */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "public/ddcutil_status_codes.h" #include #include #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/displays.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/stats.h" #include "base/display_retry_data.h" // // Maxtries // // Initial values are ddcutil default values, then can be changed // to different user default values // But distinction not maxtries values do not vary by thread.! // duplicate of default_maxtries = ddc_try_stats.c, unify static int default_maxtries[] = { INITIAL_MAX_WRITE_ONLY_EXCHANGE_TRIES, INITIAL_MAX_WRITE_READ_EXCHANGE_TRIES, INITIAL_MAX_MULTI_EXCHANGE_TRIES, INITIAL_MAX_MULTI_EXCHANGE_TRIES }; /** Sets the maxtries value to be used for a given retry type when creating * new #Per_Display_Data instances. * * \param retry_type * \param maxtries value to set */ void drd_set_default_max_tries(Retry_Operation rcls, uint16_t maxtries) { bool debug = false; DBGMSF(debug, "Executing. rcls = %s, new_maxtries=%d", retry_type_name(rcls), maxtries); default_maxtries[rcls] = maxtries; } static void wrap_report_display_retry_data(Per_Display_Data * data, void * arg) { int depth = GPOINTER_TO_INT(arg); rpt_vstring(depth, "Retry data for display on %s:", dpath_short_name_t(&data->dpath)); report_display_all_types_data_by_data(false, // for_all_displays data, depth); } /** Report all #Per_Display_Data structs. Note that this report includes * structs for displays that may have been disconnected. * * \param depth logical indentation depth */ void drd_report_all_display_retry_data(int depth) { bool debug = false; DBGMSF(debug, "Starting"); rpt_label(depth, "Per display retry data"); assert(per_display_data_hash); pdd_cross_display_operation_block(__func__); // bool this_function_locked = pdd_lock_if_unlocked(); pdd_apply_all_sorted(&wrap_report_display_retry_data, GINT_TO_POINTER(depth+1) ); // pdd_unlock_if_needed(this_function_locked); DBGMSF(debug, "Done"); } // // Try Stats // #ifdef UNUSED // n. caller always locks static void drd_reset_tries_by_data(Per_Display_Data * data) { // pdd_cross_display_operation_block(); // bool this_function_locked = pdd_lock_if_unlocked(); for (int ndx = 0; ndx < RETRY_OP_COUNT; ndx++) { for (int ctrndx = 0; ctrndx < MAX_MAX_TRIES+2; ctrndx++) { // counters[ctrndx] = 0; data->try_stats[ndx].counters[ctrndx] = 0; } } // pdd_unlock_if_needed(this_function_locked); } // reset counts for current display void drd_reset_display_tries(Per_Display_Data * pdd) { // bool this_function_locked = pdd_lock_if_unlocked(); // pdd_cross_display_operation_block(); // Per_Display_Data * data = drd_get_display_retry_data(); drd_reset_tries_by_data(pdd); // pdd_unlock_if_needed(this_function_locked); } // GFunc signature static void drd_wrap_reset_tries_by_data(Per_Display_Data * data, void * arg) { drd_reset_tries_by_data(data); } void drd_reset_all_displays_tries() { // call tries_cur_display_reset_stats() // needs mutex bool debug = false; DBGMSF(debug, "Starting. "); if (per_display_data_hash) { pdd_apply_all_sorted(&drd_wrap_reset_tries_by_data, NULL ); // handles locking } DBGMSF(debug, "Done"); } #endif #ifdef UNUSED // static void drd_record_display_successful_tries(Per_Display_Data * data, Retry_Operation type_id, int tryct) { bool debug = false; DBGMSF(debug, "type_id=%d - %s, tryct=%d, Per_Display_Data: %p", type_id, retry_type_name(type_id), tryct, data); data->try_stats[type_id].counters[tryct+1]++; DBGMSF(debug, "new counters value: %d", data->try_stats[type_id].counters[tryct+1]); } // static void drd_record_display_failed_max_tries(Per_Display_Data * data, Retry_Operation type_id) { data->try_stats[type_id].counters[1]++; } // static void drd_record_display_failed_fatally(Per_Display_Data * data, Retry_Operation type_id) { data->try_stats[type_id].counters[0]++; } #endif void drd_record_display_tries(Per_Display_Data * pdd, Retry_Operation type_id, int rc, int tryct) { bool debug = false; DBGMSF(debug, "Executing. %s type_id=%d=%s, rc=%d, tryct=%d", dpath_repr_t(&pdd->dpath), type_id, retry_type_name(type_id), rc, tryct); int index = 0; if (rc == 0) { index = tryct+1; } // fragile, but eliminates testing for max_tries: else if (rc == DDCRC_RETRIES || rc == DDCRC_ALL_TRIES_ZERO) { index = 1; } else { // failed fatally index = 0; } pdd->try_stats[type_id].counters[index]+= 1; } int get_display_total_tries_for_one_type_by_data(Retry_Operation retry_type, Per_Display_Data * data) { pdd_cross_display_operation_block(__func__); int total_attempts = 0; for (int counter_ndx = 0; counter_ndx < MAX_MAX_TRIES + 2; counter_ndx++) { total_attempts += data->try_stats[retry_type].counters[counter_ndx]; } return total_attempts; } #ifdef UNUSED /** Calculates the total number of tries for all exchange type on a single thread. * * \param data per-thread data record * \param return total attempts for all exchange types */ int get_display_total_tries_for_all_types_by_data(Per_Display_Data * data) { pdd_cross_display_operation_block(); // bool this_function_locked = pdd_lock_if_unlocked(); int total_attempts = 0; for (int typendx = 0; typendx < RETRY_OP_COUNT; typendx++) { // Per_Display_Try_Stats * typedata = &data->try_stats[typendx]; for (int counter_ndx = 0; counter_ndx < MAX_MAX_TRIES + 2; counter_ndx++) { // total_attempts += typedata->counters[counter_ndx]; total_attempts += data->try_stats[typendx].counters[counter_ndx]; } } // pdd_unlock_if_needed(this_function_locked); return total_attempts; } #endif /** Determines the index of the highest try counter for a given operation, * i.e. other than 0 or 1, with a non-zero value, i.e. the highest try * count needed to successfully perform the operation. * * @param try count table * @return highest try count for successful requests */ uint16_t display_index_of_highest_non_zero_counter(uint16_t* counters) { int result = 1; for (int kk = MAX_MAX_TRIES+1; kk > 1; kk--) { if (counters[kk] != 0) { result = kk; break; } } // DBGMSG("Returning: %d", result); return result; } /** Reports a single type of transaction (write-only, write-read, etc. * for a given display. * * This function is also used to report summary data stored in a * summary Per_Display_Data instance. * * \param retry_type type of transaction being reported * \param for_all_displays indicates whether this call is for a real display, * or for a synthesized data record containing data that * summarizes all displays * \param data pointer to per-thread data * \param depth logical indentation depth */ void report_display_try_typed_data_by_data( Retry_Operation retry_type, bool for_all_displays_total, Per_Display_Data * data, int depth) { // bool debug = false; int d1 = depth+1; int d2 = depth+2; ASSERT_IFF( (retry_type == -1), for_all_displays_total ); // bool this_function_locked = pdd_lock_if_unlocked(); int total_attempts_for_one_type = get_display_total_tries_for_one_type_by_data(retry_type, data); if (for_all_displays_total) { // reporting a synthesized summary record rpt_vstring(depth, "Total %s retry statistics for all displays", retry_type_name(retry_type) ); } else { // normal case, reporting one thread if (total_attempts_for_one_type) rpt_vstring(depth, "Retry data for %s tries", retry_type_description(retry_type)); else rpt_vstring(depth, "Retry data for %s tries: No tries attempted", retry_type_description(retry_type)); } #ifdef OUT // only use of highest_maxtries if (debug) { int upper_bound = data->highest_maxtries[retry_type] + 1; assert(upper_bound <= MAX_MAX_TRIES + 1); char * buf = int_array_to_string( data->try_stats[retry_type].counters, upper_bound); rpt_vstring(d1, "try_stats[%d=%-27s].counters = %s", retry_type, retry_type_name(retry_type), buf); free(buf); } #endif if ( total_attempts_for_one_type == 0) { // rpt_vstring(d1, "No tries attempted"); } else { // Per_Display_Try_Stats try_stats[4]; Per_Display_Try_Stats* typedata =& data->try_stats[ retry_type ]; int last_index3 = display_index_of_highest_non_zero_counter(data->try_stats[retry_type].counters); int total_successful_attempts = 0; for (int ndx = 2; ndx <= last_index3; ndx++) total_successful_attempts += typedata->counters[ndx]; int all_attempts = total_successful_attempts + typedata->counters[0] + typedata->counters[1]; assert(all_attempts == total_attempts_for_one_type); bool force_detail = false; // true for debugging if (all_attempts == 0 && !force_detail) { rpt_vstring(d1, "Total attempts %2d", all_attempts); } else { rpt_vstring(d1, "Successful attempts by number of tries required:"); if (last_index3 <= 1) rpt_label(d2, " None"); else { for (int ndx=2; ndx <= last_index3; ndx++) { rpt_vstring(d2, "%2d: %3d", ndx-1, typedata->counters[ndx]); } } // pdd_unlock_if_needed(this_function_locked); rpt_vstring(d1, "Total successful: %3d", total_successful_attempts); rpt_vstring(d1, "Failed due to max tries exceeded: %3d", typedata->counters[1]); rpt_vstring(d1, "Failed due to fatal error: %3d", typedata->counters[0]); rpt_vstring(d1, "Total attempts: %3d", total_attempts_for_one_type); } } rpt_nl(); } /** Reports all try statistics for a single display * * \param for_all_displays indicates whether this call is for a real display, * or for a synthesized data record containing data that * summarizes all displays * \param data pointer to record for one display * \param depth logical indentation depth */ void report_display_all_types_data_by_data( bool for_all_displays, // controls message Per_Display_Data* data, int depth) { for (int try_type_ndx = 0; try_type_ndx < RETRY_OP_COUNT; try_type_ndx++) { Retry_Operation type_id = (Retry_Operation) try_type_ndx; report_display_try_typed_data_by_data( type_id, for_all_displays, data, depth+1); } } ddcutil-2.2.0/src/base/temp/0000775000175000001440000000000014754576332011370 5ddcutil-2.2.0/src/base/temp/tuned_sleep.h0000664000175000001440000000267414754576332014001 /** @file tuned_sleep.h * * Perform sleep. The sleep time is determined by io mode, sleep event time, * and applicable multipliers. */ // Copyright (C) 2019-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef TUNED_SLEEP_H_ #define TUNED_SLEEP_H_ #include #include "base/sleep.h" #include "base/execution_stats.h" // Sleep time adjustments void lock_default_sleep_multiplier_factor(); void unlock_default_sleep_multiplier_factor(); void set_default_sleep_multiplier_factor(double multiplier); double get_default_sleep_multiplier_factor(); void set_sleep_multiplier_factor(double multiplier); double get_sleep_multiplier_factor(); void set_sleep_multiplier_ct(int multiplier); int get_sleep_multiplier_ct(); // Perform tuned sleep void tuned_sleep_with_tracex( DDCA_IO_Mode io_mode, Sleep_Event_Type event_type, const char * func, int lineno, const char * filename, const char * msg); // Convenience functions and macros: void tuned_sleep_dh(Display_Handle* dh, Sleep_Event_Type event_type); #define TUNED_SLEEP_WITH_TRACE(_io_mode, _event_type, _msg) \ tuned_sleep_with_tracex(_io_mode, _event_type, __func__, __LINE__, __FILE__, _msg) #define TUNED_SLEEP_I2C_WITH_TRACE(_event_type, _msg) \ tuned_sleep_with_tracex(DDCA_IO_I2C, _event_type, __func__, __LINE__, __FILE__, _msg) #endif /* TUNED_SLEEP_H_ */ ddcutil-2.2.0/src/base/temp/persistent_stats.h0000644000175000001440000000113214754576332015072 /** \f persistent_stats.h */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PERSISTENT_STATS_H_ #define PERSISTENT_STATS_H_ #include "private/ddcutil_types_private.h" #include "util/error_info.h" bool enable_stats_cache(bool onoff); char * get_stats_cache_file_name(); char * get_persistent_stats(DDCA_Monitor_Model_Key* mmk); void set_persistent_stats(DDCA_Monitor_Model_Key* mmk, const char * stats); void dbgrpt_stats_hash(int depth, const char * msg); void init_persistent_stats(); #endif /* PERSISTENT_STATS_H_ */ ddcutil-2.2.0/src/base/clang_output_koVrth0000644000175000001440000000036214754576332014326 dsa1.c:189:16: error: incompatible integer to pointer conversion initializing 'DSA1_Data *' with an expression of type 'int' [-Wint-conversion] DSA1_Data * dsa1 = dsa1_from_dh(dh); ^ ~~~~~~~~~~~~~~~~ 1 error generated. ddcutil-2.2.0/src/base/build_info.h0000644000175000001440000000067114754576332012630 /** \file build_info.h * * Build Information: version, compilation options, etc. */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BUILD_INFO_H_ #define BUILD_INFO_H_ const char * get_base_ddcutil_version(); const char * get_ddcutil_version_suffix(); const char * get_full_ddcutil_version(); void report_build_options(int depth); #endif /* BUILD_INFO_H_ */ ddcutil-2.2.0/src/base/core_per_thread_settings.h0000644000175000001440000000446114754576332015564 /** \f core_per_thread_settings.h * * Maintains certain output settings on a per-thread basis. * These are: * fout - normally stdout * ferr - normally stderr * output level (OL_NORMAL etc.) * * These are maintained on per-thread basis because they are changeable on * an API thread, and a change in one thread should not affect other threads. * However, output level can be set on the ddcutil command line, and should * apply to all threads. Hence the ability to set a value for all threads. * * There is no way to modify fout and ferr on the ddcutil command line, but * they are handled similarly to output level, with default levels for all * threads. Also fout and ferr can be modified by api initialization. * * Additionally, struct Thread_Output_Settings maintains the DDCA_Error_Detail * chain for the thread. This is always initialized to NULL, so requires no * special initialization handling. * */ // Copyright (C)2014 -2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef CORE_PER_THREAD_SETTINGS_H_ #define CORE_PER_THREAD_SETTINGS_H_ #include #include #include "ddcutil_types.h" typedef struct { FILE * fout; FILE * ferr; DDCA_Output_Level output_level; // bool report_ddc_errors; // unused, ddc error reporting left as global DDCA_Error_Detail * error_detail; intmax_t tid; } Thread_Output_Settings; Thread_Output_Settings * get_thread_settings(); // get settings for the current thread // // Output redirection // // Note: FILE * externs FOUT and FERR were eliminated when output redirection // was made thread specific. Use fout() and ferr() instead. // These are used within functions that are part of the shared library. void set_fout(FILE * fout); void set_ferr(FILE * ferr); void set_fout_to_default(); void set_ferr_to_default(); FILE * fout(); FILE * ferr(); // // Message level control // DDCA_Output_Level get_output_level(); DDCA_Output_Level set_output_level(DDCA_Output_Level newval); void set_default_thread_output_level(DDCA_Output_Level ol); // const adding "const" would require api change to ddca_output_level_name() char * output_level_name(DDCA_Output_Level val); #endif /* CORE_PER_THREAD_SETTINGS_H_ */ ddcutil-2.2.0/src/base/ddc_command_codes.h0000644000175000001440000000223414754576332014120 /** \file ddc_command_codes.h * DDC/CI command codes */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_COMMAND_CODES_H_ #define DDC_COMMAND_CODES_H_ #include "util/coredefs.h" // // DDC/CI Command and Response Codes // // Used in 3 ways: // - to identify commands within ddcutil // - as identifiers in command request and response packets // - in capabilities string #define CMD_VCP_REQUEST 0x01 #define CMD_VCP_RESPONSE 0x02 #define CMD_VCP_SET 0x03 #define CMD_TIMING_REPLY 0x06 #define CMD_TIMING_REQUEST 0x07 #define CMD_VCP_RESET 0x09 #define CMD_SAVE_SETTINGS 0x0c #define CMD_SELF_TEST_REPLY 0xa1 #define CMD_SELF_TEST_REQUEST 0xb1 #define CMD_ID_REPLY 0xe1 #define CMD_TABLE_READ_REQUST 0xe2 #define CMD_CAPABILITIES_REPLY 0xe3 #define CMD_TABLE_READ_REPLY 0xe4 #define CMD_TABLE_WRITE 0xe7 #define CMD_ID_REQUEST 0xf1 #define CMD_CAPABILITIES_REQUEST 0xf3 #define CMD_ENABLE_APP_REPORT 0xf5 char * ddc_cmd_code_name(Byte command_id); #endif /* DDC_COMMAND_CODES_H_ */ ddcutil-2.2.0/src/base/ddc_errno.h0000644000175000001440000000117014754576332012450 /** \file * Error codes internal to **ddcutil**. */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_ERRNO_H_ #define DDC_ERRNO_H_ #include "public/ddcutil_status_codes.h" #include "base/status_code_mgt.h" Status_Code_Info * ddcrc_find_status_code_info(int rc); bool ddc_error_name_to_number(const char * errno_name, Status_DDC * errnum_loc); // Returns status code description: char * ddcrc_desc_t(int rc); bool ddcrc_is_derived_status_code(Public_Status_Code gsc); bool ddcrc_is_not_error(Public_Status_Code gsc); #endif /* DDC_ERRNO_H_ */ ddcutil-2.2.0/src/base/feature_lists.h0000644000175000001440000000203214754576332013360 /** @file feature_lists.h */ // Copyright (C) 2018=2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef FEATURE_LISTS_H_ #define FEATURE_LISTS_H_ #include #include "ddcutil_types.h" void feature_list_clear( DDCA_Feature_List* vcplist); void feature_list_add( DDCA_Feature_List* vcplist, uint8_t vcp_code); bool feature_list_contains( DDCA_Feature_List* vcplist, uint8_t vcp_code); DDCA_Feature_List feature_list_or( DDCA_Feature_List* vcplist1, DDCA_Feature_List* vcplist2); DDCA_Feature_List feature_list_and( DDCA_Feature_List* vcplist1, DDCA_Feature_List* vcplist2); DDCA_Feature_List feature_list_and_not( DDCA_Feature_List* vcplist1, DDCA_Feature_List* vcplist2); int feature_list_count( DDCA_Feature_List* feature_list); const char * feature_list_string( DDCA_Feature_List* feature_list, const char * value_prefix, const char * sepstr); #endif /* FEATURE_LISTS_H_ */ ddcutil-2.2.0/src/base/linux_errno.h0000644000175000001440000000144614754576332013063 /** \file linux_errno.h * Linux errno descriptions */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BASE_LINUX_ERRNO_H_ #define BASE_LINUX_ERRNO_H_ #include "base/status_code_mgt.h" void init_linux_errno(); // Interpret system error number // not thread safe, always points to same internal buffer, contents overwritten on each call char * linux_errno_name(int error_number); char * linux_errno_desc(int error_number); Status_Code_Info * get_errno_info(int errnum); Status_Code_Info * get_negative_errno_info(int errnum); bool errno_name_to_number(const char * errno_name, int * perrno); bool errno_name_to_modulated_number(const char * errno_name, Public_Status_Code * p_error_number); #endif /* BASE_LINUX_ERRNO_H_ */ ddcutil-2.2.0/src/base/base_services.h0000644000175000001440000000051214754576332013325 /** \file base_services.h" * Initialize and release base services. */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BASE_SERVICES_H_ #define BASE_SERVICES_H_ void init_base_services(); void terminate_base_services(); #endif /* BASE_SERVICES_H_ */ ddcutil-2.2.0/src/base/ddc_packets.h0000644000175000001440000001653714754576332012772 /** @file ddc_packets.h * * Functions for creating DDC packets and interpreting DDC response packets. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_PACKETS_H_ #define DDC_PACKETS_H_ /** \cond */ #include /** \endcond */ #include "ddcutil_types.h" #include "util/data_structures.h" #include "base/status_code_mgt.h" #include "base/core.h" // max capabilities or table fragment size #define MAX_DDC_MULTI_PART_FRAGMENT_SIZE 32 #define MAX_DDC_MULTI_PART_DATA_SIZE 35 // +3 for op-code, offset-high-byte, offset-low-byte #define MAX_DDC_DATA_SIZE 35 // capabilities/table response is largest possible data size #define MAX_DDC_PACKET_WO_CHECKSUM 38 // +3 for dest-addr, source-addr, length byte #define MAX_DDC_PACKET_INC_CHECKSUM 39 #define MAX_DDC_PACKET_SIZE 39 #define MAX_DDC_TAG 39 #ifdef NEW // apparently unused typedef struct { Byte vcp_opcode; Byte vcp_type_code; Byte parse_status; Byte mh; Byte ml; Byte sh; Byte sl; void * interpretation; // specific to VCP_opcode } Parsed_VCP_Response_Data; #endif /** Interpretation of a packet of type DDC_PACKET_TYPE_QUERY_VCP_RESPONSE */ typedef struct { Byte vcp_code; ///< VCP feature code bool valid_response; ///< bool supported_opcode; ///< is opcode supported? Byte mh; ///< max value high order byte Byte ml; ///< max value low order byte Byte sh; ///< current value high order byte Byte sl; ///< current value low order byte } Parsed_Nontable_Vcp_Response; #define HI_LO_BYTES_TO_SHORT(hi,lo) ( (hi)<<8 | (lo)) #define RESPONSE_CUR_VALUE(response) (response->sh<<8 | response->sl) #define RESPONSE_MAX_VALUE(response) (response->mh<<8 | response->ml) static inline bool value_bytes_zero(Parsed_Nontable_Vcp_Response * parsed_val) { return (parsed_val->mh == 0 && parsed_val->ml == 0 && parsed_val->sh == 0 && parsed_val->sl == 0); } /** For digesting capabilities or table read fragment */ typedef struct { Byte fragment_type; // DDC_PACKET_TYPE_CAPABILITIES_RESPONSE || DDC_PACKET_TYPE_TABLE_READ_RESPONSE int fragment_offset; int fragment_length; // without possible terminating '\0' // add 1 to allow for appending a terminating '\0' in case of DDC_PACKET_TYPE_CAPABILITIES_RESPONSE Byte bytes[MAX_DDC_MULTI_PART_FRAGMENT_SIZE+1]; } Interpreted_Multi_Part_Read_Fragment; // Keep in sync with list in ddc_command_codes.h typedef Byte DDC_Packet_Type; #define DDC_PACKET_TYPE_NONE 0x00 #define DDC_PACKET_TYPE_QUERY_VCP_REQUEST 0x01 #define DDC_PACKET_TYPE_QUERY_VCP_RESPONSE 0x02 #define DDC_PACKET_TYPE_SET_VCP_REQUEST 0x03 // n. no reply message #define DDC_PACKET_TYPE_SAVE_CURRENT_SETTINGS 0x0C // n. no reply message #define DDC_PACKET_TYPE_CAPABILITIES_REQUEST 0xf3 #define DDC_PACKET_TYPE_CAPABILITIES_RESPONSE 0xe3 #define DDC_PACKET_TYPE_ID_REQUEST 0xf1 #define DDC_PACKET_TYPE_ID_RESPONSE 0xe1 #define DDC_PACKET_TYPE_TABLE_READ_REQUEST 0xe2 #define DDC_PACKET_TYPE_TABLE_READ_RESPONSE 0xe4 #define DDC_PACKET_TYPE_TABLE_WRITE_REQUEST 0xe7 /** Packet bytes and interpretation */ typedef struct { Buffer * raw_bytes; ///< raw packet bytes char tag[MAX_DDC_TAG+1]; ///< debug string describing packet, +1 for \0 DDC_Packet_Type type; ///< packet type union { Parsed_Nontable_Vcp_Response * nontable_response; Interpreted_Multi_Part_Read_Fragment * multi_part_read_fragment; void * raw_parsed; } parsed; // additional fields for new way of parsing result data // Parsed_Response_Data * parsed_response; } DDC_Packet; void dbgrpt_packet(DDC_Packet * packet, int depth); void free_ddc_packet(DDC_Packet * packet); bool is_double_byte(Byte * pb); // Byte xor_bytes(Byte * bytes, int len); Byte ddc_checksum(Byte * bytes, int len, bool altmode); #ifdef UNUSED bool valid_ddc_packet_checksum(Byte * readbuf); #endif // void test_checksum(); typedef struct { DDCA_Vcp_Value_Type response_type; Parsed_Nontable_Vcp_Response * non_table_response; Buffer * table_response; } Parsed_Vcp_Response; void dbgrpt_parsed_vcp_response(Parsed_Vcp_Response * response,int depth); Status_DDC create_ddc_base_response_packet( Byte * i2c_response_bytes, int response_bytes_buffer_size, const char * tag, DDC_Packet ** packet_ptr); Status_DDC create_ddc_typed_response_packet( Byte * i2c_response_bytes, int response_bytes_buffer_size, Byte expected_type, Byte expected_subtype, const char * tag, DDC_Packet ** packet_ptr_addr); DDC_Packet * create_ddc_capabilities_request_packet( int offset, const char * tag); DDC_Packet * create_ddc_multi_part_read_request_packet( Byte request_type, Byte request_subtype, int offset, const char * tag); DDC_Packet * create_ddc_multi_part_write_request_packet( Byte request_type, // always DDC_PACKET_TYPE_WRITE_REQUEST Byte request_subtype, // VCP code int offset, Byte * bytes_to_write, int bytect, const char * tag); void update_ddc_capabilities_request_packet_offset( DDC_Packet * packet, int offset); void update_ddc_multi_part_read_request_packet_offset( DDC_Packet * packet, int offset); Status_DDC create_ddc_capabilities_response_packet( Byte * i2c_response_bytes, int response_bytes_buffer_size, const char * tag, DDC_Packet ** packet_ptr); Status_DDC interpret_capabilities_response( Byte * data_bytes, int bytect, Interpreted_Multi_Part_Read_Fragment * aux_data, bool debug); extern Byte alt_source_addr; DDC_Packet * create_ddc_getvcp_request_packet( Byte vcp_code, const char * tag); Status_DDC create_ddc_getvcp_response_packet( Byte * i2c_response_bytes, int response_bytes_buffer_size, Byte expected_vcp_opcode, const char * tag, DDC_Packet ** packet_ptr); DDC_Packet * create_ddc_setvcp_request_packet( Byte vcp_code, int new_value, const char * tag); DDC_Packet * create_ddc_save_settings_request_packet( const char * tag); Status_DDC get_interpreted_vcp_code( DDC_Packet * packet, bool make_copy, Parsed_Nontable_Vcp_Response ** interpreted_loc); void dbgrpt_interpreted_multi_read_fragment( Interpreted_Multi_Part_Read_Fragment * interpreted, int depth); void dbgrpt_interpreted_nontable_vcp_response( Parsed_Nontable_Vcp_Response * interpreted, int depth); #ifdef OLD void report_interpreted_aux_data(Byte response_type, void * interpreted); #endif Byte * get_packet_start(DDC_Packet * packet); int get_packet_len( DDC_Packet * packet); Byte * get_data_start( DDC_Packet * packet); int get_data_len( DDC_Packet * packet); void init_ddc_packets(); #endif /* DDC_PACKETS_H_ */ ddcutil-2.2.0/src/base/display_retry_data.h0000644000175000001440000000212314754576332014373 /** @file display_retry_data.h * * Maintain retry counts on a per-display basis. */ // Copyright (C) 2020-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DISPLAY_RETRY_DATA_H_ #define DISPLAY_RETRY_DATA_H_ #include "public/ddcutil_types.h" #include "base/per_display_data.h" // Maintain max_tries void drd_set_default_max_tries( Retry_Operation type_id, uint16_t new_maxtries); // Try Stats void drd_record_display_tries( Per_Display_Data * pdd, Retry_Operation type_id, int rc, int tryct); void report_display_try_typed_data_by_data( Retry_Operation try_type_id, bool for_all_displays_total, Per_Display_Data * data, int depth); void report_display_all_types_data_by_data( bool for_all_displays, // controls message Per_Display_Data * data, int depth); void drd_report_all_display_retry_data(int depth); #endif /* DISPLAY_RETRY_DATA_H_ */ ddcutil-2.2.0/src/base/execution_stats.h0000644000175000001440000000553314754576332013741 /** \file execution_stats.h * * Record the count and elapsed time of system calls. * * These stats are global, not per thread */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef EXECUTION_STATS_H_ #define EXECUTION_STATS_H_ /** \cond */ #include #include /** \endcond */ #include "util/timestamp.h" #include "base/displays.h" #include "base/status_code_mgt.h" // Initialization void init_execution_stats(); void terminate_execution_stats(); void reset_execution_stats(); // Global Stats void report_elapsed_stats(int depth); void report_elapsed_summary(int depth); // IO Event Tracking /** IO Event type identifiers. * * Statistics for each event type are recorded separately. */ typedef enum { IE_FILEIO_WRITE, ///< i2c writes using write() IE_FILEIO_READ, ///< i2c reads using read() IE_IOCTL_WRITE, ///< i2c writes using ioctl() IE_IOCTL_READ, ///< i2c reads using ioctl() IE_OPEN, ///< device file open IE_CLOSE, ///< device file close IE_OTHER ///< other IO event } IO_Event_Type; const char * io_event_name(IO_Event_Type event_type); void log_io_call( const IO_Event_Type event_type, const char * location, uint64_t start_time_nanos, uint64_t end_time_nanos); #define RECORD_IO_EVENT(_fd, _event_type, _cmd_to_time) { \ uint64_t _start_time = cur_realtime_nanosec(); \ _cmd_to_time; \ log_io_call(_event_type, __func__, _start_time, cur_realtime_nanosec()); \ } void report_io_call_stats(int depth); // Record Status Code Occurrence Public_Status_Code log_status_code(Public_Status_Code rc, const char * caller_name); Public_Status_Code log_retryable_status_code(Public_Status_Code rc, const char * caller_name); #define COUNT_STATUS_CODE(rc) log_status_code(rc,__func__) #define COUNT_RETRYABLE_STATUS_CODE(rc) log_retryable_status_code(rc,__func__) void report_all_status_counts(int depth); // Sleep events /** Sleep event type */ typedef enum { SE_WRITE_TO_READ, ///< between I2C write and read SE_POST_WRITE, ///< after I2C write without subsequent read SE_POST_READ, ///< after I2C read SE_POST_SAVE_SETTINGS, ///< after DDC Save Current Settings command SE_PRE_MULTI_PART_READ, ///< before reading capabilities or table SE_POST_CAP_TABLE_SEGMENT,///< after each segment of Capabilities or a Table command SE_SPECIAL ///< explicit time specified } Sleep_Event_Type; const char * sleep_event_name(Sleep_Event_Type event_type); void reset_sleep_event_counts(); void record_sleep_event(Sleep_Event_Type event_type); void report_execution_stats(int depth); void terminate_execution_stats(); #endif /* EXECUTION_STATS_H_ */ ddcutil-2.2.0/src/base/monitor_quirks.h0000644000175000001440000000107214754576332013577 /** @file monitor_quirks.h */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef MONITOR_QUIRKS_H_ #define MONITOR_QUIRKS_H_ #include "base/monitor_model_key.h" typedef enum { MQ_NONE = 0, MQ_NO_SETTING = 1, MQ_NO_MFG_RANGE = 2, MQ_OTHER = 4, } Monitor_Quirk_Type; typedef struct { Monitor_Quirk_Type quirk_type; char * quirk_msg; } Monitor_Quirk_Data; Monitor_Quirk_Data * get_monitor_quirks(Monitor_Model_Key * mmk); #endif /* MONITOR_QUIRKS_H_ */ ddcutil-2.2.0/src/base/rtti.h0000644000175000001440000000120014754576332011465 /* @file rtti.h * Runtime trace information */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef RTTI_H_ #define RTTI_H_ #include #define RTTI_ADD_FUNC(_NAME) rtti_func_name_table_add(_NAME, #_NAME); void rtti_func_name_table_add(void * func_addr, const char * func_name); char * rtti_get_func_name_by_addr(void * ptr); void * rtti_get_func_addr_by_name(const char * name); void dbgrpt_rtti_func_name_table(int depth, bool show_internal); void report_rtti_func_name_table(int depth, char * msg); void terminate_rtti(); #endif /* RTTI_H_ */ ddcutil-2.2.0/src/base/stats.h0000644000175000001440000000161114754576332011647 /** @file stats.h */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef STATS_H_ #define STATS_H_ #include // // Retry management // //! I2C retry types typedef enum{ WRITE_ONLY_TRIES_OP, /**< write-only operation tries */ WRITE_READ_TRIES_OP, /**< read-write operation tries */ MULTI_PART_READ_OP, /**< multi-part read operation tries */ MULTI_PART_WRITE_OP /**< multi-part write operation tries */ } Retry_Operation; #define RETRY_OP_COUNT 4 typedef uint16_t Retry_Op_Value; const char * retry_type_name(Retry_Operation stat_id); const char * retry_type_description(Retry_Operation retry_class); typedef struct { Retry_Operation retry_type; uint16_t max_highest_maxtries; uint16_t min_lowest_maxtries; } Global_Maxtries_Accumulator; #endif /* STATS_H_ */ ddcutil-2.2.0/src/base/tuned_sleep.h0000644000175000001440000000276014754576332013026 /** @file tuned_sleep.h * * Perform sleep. The sleep time is determined by io mode, sleep event time, * and applicable multipliers. */ // Copyright (C) 2019-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef TUNED_SLEEP_H_ #define TUNED_SLEEP_H_ /** \cond */ #include // #include "public/ddcutil_types.h" /** \endcond */ #include "base/displays.h" #include "base/execution_stats.h" // for Sleep_Event_Type extern bool suppress_se_post_read; extern bool null_msg_adjustment_enabled; bool enable_deferred_sleep(bool enable); bool is_deferred_sleep_enabled(); void check_deferred_sleep( Display_Handle * dh, const char * func, int lineno, const char * filename); void tuned_sleep_with_trace( Display_Handle * dh, Sleep_Event_Type event_type, int special_sleep_time_millis, const char * func, int lineno, const char * filename, const char * msg); // Convenience macros: #define CHECK_DEFERRED_SLEEP(_dh) \ check_deferred_sleep(_dh, __func__, __LINE__, __FILE__) #define TUNED_SLEEP_WITH_TRACE(_dh, _event_type, _msg) \ tuned_sleep_with_trace(_dh, _event_type, 0, __func__, __LINE__, __FILE__, _msg) #define SPECIAL_TUNED_SLEEP_WITH_TRACE(_dh, _time_millis, _msg) \ tuned_sleep_with_trace(_dh, SE_SPECIAL, _time_millis, __func__, __LINE__, __FILE__, _msg) void init_tuned_sleep(); #endif /* TUNED_SLEEP_H_ */ ddcutil-2.2.0/src/base/dsa2.h0000644000175000001440000000420114754576332011340 /** @file dsa2.h Dynamic sleep algorithm 2 */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DSA2_H_ #define DSA2_H_ #include #include "public/ddcutil_types.h" #include "util/error_info.h" #include "base/core.h" #include "base/status_code_mgt.h" extern int dsa2_step_floor; void dsa2_enable(bool yesno); bool dsa2_is_enabled(); bool dsa2_set_greatest_tries_upper_bound(int tries); bool dsa2_set_average_tries_upper_bound(DDCA_Sleep_Multiplier avg_tries); int dsa2_multiplier_to_step(DDCA_Sleep_Multiplier multiplier); DDCA_Sleep_Multiplier dsa2_step_to_multiplier(int step); DDCA_Sleep_Multiplier dsa2_get_minimum_multiplier(); struct Results_Table * dsa2_get_results_table_by_busno(int busno, bool create_if_not_found); bool dsa2_is_from_cache(struct Results_Table * dpath); void dsa2_reset_multiplier(DDCA_Sleep_Multiplier multiplier); void dsa2_reset_results_table(int busno, DDCA_Sleep_Multiplier sleep_multiplier); DDCA_Sleep_Multiplier dsa2_get_adjusted_sleep_mult(struct Results_Table * rtable); void dsa2_note_retryable_failure( struct Results_Table * rtable, DDCA_Status ddcrc, int remaining_tries); void dsa2_record_final( struct Results_Table * rtable, DDCA_Status ddcrc, int retries, bool null_adjustment_occurred); char * dsa2_stats_cache_file_name(); Status_Errno dsa2_save_persistent_stats(); Status_Errno dsa2_erase_persistent_stats(); Error_Info * dsa2_restore_persistent_stats(); void dsa2_report_internal(struct Results_Table * rtable, int depth); void dsa2_report_internal_all(int depth); void init_dsa2(); void terminate_dsa2(); // release all resources #endif /* DSA2_H_ */ ddcutil-2.2.0/src/base/status_code_mgt.h0000644000175000001440000000734614754576332013710 /** \file status_code_mgt.h * * Status Code Management */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef STATUS_CODE_MGT_H_ #define STATUS_CODE_MGT_H_ /** \cond */ #include /** \endcond */ #include "public/ddcutil_status_codes.h" // Called from the mainline to perform initialization void init_status_code_mgt(); /** Describes one status code. * * @remark * Code could be simplified by using a #Value_Name_Title table instead, * but left as is because we might want to add additional fields. */ typedef struct { int code; char * name; char * description; // idea: add flags for NOT_AN_ERROR, DERIVED ? } Status_Code_Info; // debugging function: void report_status_code_info(Status_Code_Info * pdesc); // For distinguishing types of return codes. // C does not enforce type checking, but useful for documentation // trying different styles for readability, consistency w standards typedef int Status_Errno; ///< negative Linux errno values typedef int Status_DDC; ///< DDC specific status codes typedef int Status_Errno_DDC; ///< union(Status_Errno,Status_DDC) typedef int Base_Status_ADL; ///< unmodulated ADL status codes typedef int Modulated_Status_ADL; ///< modulated ADL status codes typedef int Public_Status_Code; ///< union(Status_Errno, Status_DDC, Modulated_Status_ADL) /** Pointer to function that finds the #Status_Code_Info for a status code * @param rc status code * @return ponter to #Status_Code_Info for the code, NULL if not found * */ typedef Status_Code_Info * (*Retcode_Description_Finder)(int rc); /** Pointer to a function that converts a symbolic status code name * to its integer value * * @param name status code symbolic name * @param p_number where to return status code * @return true if conversion succeeded, false if name not found */ typedef bool (*Retcode_Number_Finder)(const char * name, int * p_number); // // Status codes ranges // // #define RCRANGE_BASE_START 0 // #define RCRANGE_BASE_MAX 999 // #define RCRANGE_ERRNO_START 1000 #define RCRANGE_ERRNO_START 0 #define RCRANGE_ERRNO_MAX 1999 #define RCRANGE_ADL_START 2000 #define RCRANGE_ADL_MAX 2999 // #define RCRANGE_DDC_START 3000 #define RCRANGE_DDC_MAX 3999 /** Status code range identifiers * * @remark * - must be kept consistent with table in status_code_mgt.c */ typedef enum { // RR_BASE, ///< indicates unmodulated status code RR_ERRNO, ///< range id for Linux errno values RR_ADL, ///< range id for modulated ADL error codes RR_DDC ///< range id for **ddcutil**-specific error codes } Retcode_Range_Id; int modulate_rc( int unmodulated_rc, Retcode_Range_Id range_id); int demodulate_rc(int modulated_rc, Retcode_Range_Id range_id); Retcode_Range_Id get_modulation(int rc); // int demodulate_any_rc(int modulated_rc); // unimplemented Status_Code_Info * find_status_code_info(Public_Status_Code status_code); // Return status code description and name. Do not free after use. char * psc_desc( Public_Status_Code status_code); char * psc_name_code(Public_Status_Code status_code); char * psc_name( Public_Status_Code status_code); char * psc_text(Public_Status_Code psc); bool status_name_to_unmodulated_number( const char * status_code_name, int * p_error_number); bool status_name_to_modulated_number( const char * status_code_name, Public_Status_Code * p_error_number); #ifdef FUTURE // Future: bool status_code_name_to_psc_number( const char * status_code_name, Public_Status_Code * p_error_number); #endif #endif /* STATUS_CODE_MGT_H_ */ ddcutil-2.2.0/src/base/per_display_data.h0000644000175000001440000001102714754576332014017 /** @file per_display_data.h * * Maintains per-display settings and statistics. * * The dependencies between this file and thread_retry_data.c and thread_sleep.data * are not unidirectional. The functionality has been split into 3 files for clarity. */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PER_DISPLAY_DATA_H_ #define PER_DISPLAY_DATA_H_ #include #include #include #include #include "base/core.h" #include "base/parms.h" #include "base/displays.h" #include "base/stats.h" // use struct instead of #include "dsa2.h", etc. to avoid circular includes struct DSA0_Data; struct Results_Table; extern GHashTable * per_display_data_hash; // extern GMutex per_display_data_mutex; // temp, replace by function calls typedef enum { Default, Explicit, Reset } User_Multiplier_Source; const char * user_multiplier_source_name(User_Multiplier_Source source); extern DDCA_Sleep_Multiplier default_user_sleep_multiplier; typedef struct { Retry_Operation retry_op; // nice as a consistency check, but has to be initialized to non-zero value uint16_t counters[MAX_MAX_TRIES+2]; } Per_Display_Try_Stats; typedef struct Per_Display_Data { DDCA_IO_Path dpath; DDCA_Sleep_Multiplier user_sleep_multiplier; // set by user User_Multiplier_Source user_multiplier_source; struct Results_Table * dsa2_data; int total_sleep_time_millis; int cur_loop_null_msg_ct; Per_Display_Try_Stats try_stats[4]; DDCA_Sleep_Multiplier initial_adjusted_sleep_multiplier; DDCA_Sleep_Multiplier final_successful_adjusted_sleep_multiplier; DDCA_Sleep_Multiplier most_recent_adjusted_sleep_multiplier; // may have failed DDCA_Sleep_Multiplier min_successful_sleep_multiplier; DDCA_Sleep_Multiplier max_successful_sleep_multiplier; DDCA_Sleep_Multiplier total_successful_sleep_multiplier; int successful_sleep_multiplier_ct; bool dsa2_enabled; bool dynamic_sleep_active; bool cur_loop_null_adjustment_occurred; } Per_Display_Data; // For new displays void pdd_set_default_sleep_multiplier_factor( DDCA_Sleep_Multiplier multiplier, User_Multiplier_Source source); DDCA_Sleep_Multiplier pdd_get_default_sleep_multiplier_factor(); bool pdd_cross_display_operation_start(const char * msg); void pdd_cross_display_operation_end(const char * msg); void pdd_cross_display_operation_block(const char * msg); void pdd_init_pdd(Per_Display_Data * pdd); Per_Display_Data * pdd_get_per_display_data(DDCA_IO_Path, bool create_if_not_found); // Apply a function to all Per_Display_Data records typedef void (*Pdd_Func)(Per_Display_Data * data, void * arg); // Template for function to apply void pdd_apply_all(Pdd_Func func, void * arg); void pdd_apply_all_sorted(Pdd_Func func, void * arg); void pdd_reset_all(); void pdd_enable_dynamic_sleep_all(bool onoff); bool pdd_is_dynamic_sleep_enabled(); void dbgrpt_per_display_data(Per_Display_Data * data, int depth); void dbgrpt_per_display_data_locks(int depth); void pdd_report_all_per_display_error_counts(int depth); void pdd_report_all_per_display_call_stats(int depth); void pdd_report_elapsed(Per_Display_Data * pdd, bool include_dsa_internal, int depth); void pdd_report_all_per_display_elapsed_stats(bool include_dsa_internal, int depth); void pdd_record_adjusted_sleep_multiplier(Per_Display_Data * pdd, bool successful); bool pdd_set_dynamic_sleep_active(Per_Display_Data * pdd, bool onoff); bool pdd_is_dynamic_sleep_active(Per_Display_Data * pdd); void pdd_reset_multiplier(Per_Display_Data * pdd, DDCA_Sleep_Multiplier multiplier); DDCA_Sleep_Multiplier pdd_get_adjusted_sleep_multiplier(Per_Display_Data* pdd); void pdd_note_retryable_failure(Per_Display_Data * pdd, DDCA_Status ddcrc, int remaining_tries); void pdd_record_final(Per_Display_Data * pdd, DDCA_Status ddcrc, int retries); void pdd_reset_multiplier_by_dh(Display_Handle * dh, DDCA_Sleep_Multiplier multiplier); DDCA_Sleep_Multiplier pdd_get_sleep_multiplier_by_dh(Display_Handle * dh); void pdd_note_retryable_failure_by_dh(Display_Handle * dh, DDCA_Status ddcrc, int remaining_tries); void pdd_record_final_by_dh(Display_Handle * dh, DDCA_Status ddcrc, int retries); void init_per_display_data(); void terminate_per_display_data(); #endif /* PER_DISPLAY_DATA_H_ */ ddcutil-2.2.0/src/base/build_timestamp.h0000644000175000001440000000052114754576332013672 /** \file build_timestamp.h * * Timestamp generated at each build. */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BUILD_TIMESTAMP_H_ #define BUILD_TIMESTAMP_H_ extern const char * BUILD_DATE; extern const char * BUILD_TIME; #endif /* BUILD_TIMESTAMP_H_ */ ddcutil-2.2.0/src/base/core.h0000644000175000001440000006032114754576332011444 /** @file core.h * Core functions and global variables. * * File core.c provides a collection of inter-dependent services at the core * of the **ddcutil** application. * * These include * - standard function call options * - debug and trace messages * - abnormal termination */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BASE_CORE_H_ #define BASE_CORE_H_ #include "config.h" /** \cond */ #ifdef TARGET_BSD #else #include #endif #include #include #include #include #include /** \endcond */ #include "public/ddcutil_types.h" #include "util/common_inlines.h" #include "util/common_printf_formats.h" #include "util/coredefs.h" #include "util/error_info.h" #include "util/failsim.h" #include "util/msg_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/traced_function_stack.h" #include "base/parms.h" // ensure available to any file that includes core.h #include "base/core_per_thread_settings.h" #include "base/linux_errno.h" #include "base/status_code_mgt.h" #include "base/trace_control.h" // so don't need to repeatedly include trace_control.h // // Common macros // #define ASSERT_MARKER(_struct_ptr, _marker_value) \ assert(_struct_ptr && memcmp(_struct_ptr->marker, _marker_value, 4) == 0) // Indicates that all tracing facilities have been configured extern bool tracing_initialized; extern bool library_disabled; // // Standard function call arguments and return values // /** Byte of standard call options */ typedef Byte Call_Options; #define CALLOPT_NONE 0x00 ///< no options #define CALLOPT_ERR_MSG 0x80 ///< issue message if error // #define CALLOPT_ERR_ABORT 0x40 ///< terminate execution if error #define CALLOPT_RDONLY 0x20 ///< open read-only #define CALLOPT_WARN_FINDEX 0x10 ///< issue warning msg re hiddev_field_info.field_index change #define CALLOPT_FORCE 0x08 ///< ignore various validity checks #define CALLOPT_WAIT 0x04 ///< wait on locked resources, if false then fail #define CALLOPT_FORCE_SLAVE_ADDR 0x02 ///< use op I2C_SLAVE_FORCE (not currently used) char * interpret_call_options_t(Call_Options calloptions); #ifdef FUTURE // A way to return both a status code and a pointer. // Has the benefit of avoiding the "Something** parm" construct, // but requires a cast by the caller, so loses type checking. // How useful will this be? typedef struct { int rc; void * result; } RC_And_Result; #endif // // Trace message control // extern __thread int trace_api_call_depth; extern __thread unsigned int trace_callstack_call_depth; // extern __thread char * trace_callstack[100]; // void set_libddcutil_output_destination(const char * filename, const char * traced_unit); typedef uint16_t Dbgtrc_Options; #define DBGTRC_OPTIONS_NONE 0x00 #define DBGTRC_OPTIONS_SYSLOG 0x01 #define DBGTRC_OPTIONS_SEVERE 0x02 #define DBGTRC_OPTIONS_API_CALL 0x04 // used for tracing API #define DBGTRC_OPTIONS_STARTING 0x08 #define DBGTRC_OPTIONS_DONE 0x10 bool is_tracing(DDCA_Trace_Group trace_group, const char * filename, const char * funcname); // // Error_Info reporting // extern bool report_freed_exceptions; // // DDC data error reporting // // Controls display of messages regarding I2C error conditions that can be retried. // Applies to all threads. bool enable_report_ddc_errors(bool onoff); // thread safe bool is_report_ddc_errors_enabled(); bool is_reporting_ddc( DDCA_Trace_Group trace_group, const char * filename, const char * funcname); #define IS_REPORTING_DDC() is_reporting_ddc(TRACE_GROUP, __FILE__, __func__) bool ddcmsg( DDCA_Trace_Group trace_group, const char* funcname, const int lineno, const char* filename, char* format, ...); /** Variant of **DDCMSG** that takes an explicit trace group as an argument. * * @param debug_flag * @param trace_group * @param format * @param ... */ #define DDCMSGX(debug_flag, trace_group, format, ...) \ ddcmsg(( (debug_flag) ) ? 0xff : (trace_group), \ __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) /** Macro that wrappers function ddcmsg(), passing the current TRACE_GROUP, * file name, line number, and function name as arguments. * * @param debug_flag * @param format * @param ... */ #define DDCMSG(debug_flag, format, ...) \ ddcmsg(( (debug_flag) ) ? 0xff : (TRACE_GROUP), \ __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) bool logable_msg(DDCA_Syslog_Level log_level, const char * funcname, const int lineno, const char * filename, char * format, ...); #define LOGABLE_MSG(importance, format, ...) \ logable_msg(importance, __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) // Show report levels for all types void show_reporting(); // report ddcutil version void show_ddcutil_version(); // // Issue messages of various types // bool dbgtrc( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * fn, char * format, ...); bool dbgtrc_ret_ddcrc( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * fn, int rc, char * format, ...); #ifdef UNNECESSARY // use ddbgtrc_returning_string() bool dbgtrc_ret_bool( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * fn, bool result, char * format, ...); #endif bool dbgtrc_returning_errinfo( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * fn, Error_Info * errs, char * format, ...); bool dbgtrc_returning_string( DDCA_Trace_Group trace_group, Dbgtrc_Options options, const char * funcname, const int lineno, const char * fn, const char * retval_expression, char * format, ...); /* __assert_fail() is not part of the C spec, it is part of the Linux * implementation of assert(), etc., which are macros. * It is reported to not exist on Termux. * However, if "assert(#_assertion);" is used instead of "__assert_fail(...);", * the program does not terminate. */ // n. using ___LINE__ instead of line in __assert_fail() causes compilation error #ifdef NDEBUG #define TRACED_ASSERT(_assertion) \ do { \ } while (0) #else #define TRACED_ASSERT(_assertion) \ do { \ if (_assertion) { \ ; \ } \ else { \ /* int line = __LINE__; */ \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_NONE, __func__, __LINE__, __FILE__, \ "Assertion failed: \"%s\" in file %s at line %d", \ #_assertion, __FILE__, __LINE__); \ SYSLOG2(DDCA_SYSLOG_ERROR, "Assertion failed: \"%s\" in file %s at line %d", \ #_assertion, __FILE__, __LINE__); \ /* assert(#_assertion); */ \ /* __assert_fail(#_assertion, __FILE__, line, __func__); */ \ /* don't need assertion info, dbgtrc() and dbgtrc() have been called */ \ exit(1); \ } \ } while (0) #endif #ifndef TRACED_ASSERT_IFF #define TRACED_ASSERT_IFF(_cond1, _cond2) \ TRACED_ASSERT( ( (_cond1) && (_cond2) ) || ( !(_cond1) && !(_cond2) ) ) #endif #ifdef UNUSED #define TRACED_ABORT(_assertion) \ do { \ int line = __LINE__; \ dbgtrc(true, __func__, __LINE__, __FILE__, \ "Assertion failed: \"%s\" in file %s at line %d", \ #_assertion, __FILE__, __LINE__); \ syslog(LOG_ERR, "Assertion failed: \"%s\" in file %s at line %d", \ #_assertion, __FILE__, __LINE__); \ __assert_fail(#_assertion, __FILE__, line, __func__); \ } while (0) #endif #define CLOSE_W_ERRMSG(_fd) \ do \ { \ int close_rc = close(fd); \ if (close_rc < 0) { \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_SEVERE, __func__, __LINE__, __FILE__, \ "Unexpected error on close(): fd=%d, filename=%s, errno=%s at line %d in file %s", \ _fd, filename_for_fd_t(_fd), linux_errno_name(errno), __LINE__, __FILE__); \ } \ } while(0) #define SEVEREMSG(format, ...) \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_SEVERE, \ __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) #define DBGMSG( format, ...) \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_NONE, \ __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) #define DBGMSF(debug_flag, format, ...) \ do { if (debug_flag) dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_NONE, \ __func__, __LINE__, __FILE__, format, ##__VA_ARGS__); } while(0) // For messages that are issued either if tracing is enabled for the appropriate trace group or // if a debug flag is set. #define DBGTRC(debug_flag, trace_group, format, ...) \ dbgtrc( (debug_flag) ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_NONE, \ __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) #ifdef UNUSED #define DBGTRC_SYSLOG(debug_flag, trace_group, format, ...) \ dbgtrc( (debug_flag) ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_SYSLOG, \ __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) #endif #define DBGTRC_STARTING(debug_flag, trace_group, format, ...) \ do { \ push_traced_function(__func__); \ dbgtrc( (debug_flag) || trace_callstack_call_depth > 0 || is_traced_callstack_call(__func__) \ ? DDCA_TRC_ALL : (trace_group), \ DBGTRC_OPTIONS_STARTING, \ __func__, __LINE__, __FILE__, "Starting "format, ##__VA_ARGS__); \ } while(0) #define DBGTRC_DONE(debug_flag , trace_group, format, ...) \ do { \ dbgtrc( (debug_flag) || trace_callstack_call_depth > 0 \ ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, "Done "format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while (0) #define DBGTRC_DONE_WO_TRACED_FUNCTION_STACK(debug_flag , trace_group, format, ...) \ do { \ dbgtrc( (debug_flag) || trace_callstack_call_depth > 0 \ ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, "Done "format, ##__VA_ARGS__); \ } while (0) #define DBGTRC_EXECUTED(debug_flag, trace_group, format, ...) \ dbgtrc( (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_STARTING | DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, "Executed "format, ##__VA_ARGS__) #define DBGTRC_NOPREFIX(debug_flag, trace_group, format, ...) \ dbgtrc( (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_NONE, \ __func__, __LINE__, __FILE__, " "format, ##__VA_ARGS__) #define DBGTRC_RET_STRING(debug_flag, trace_group, _result, format, ...) \ do { \ dbgtrc_returning_string( \ (debug_flag) || trace_callstack_call_depth > 0 \ ? DDCA_TRC_ALL : (trace_group), \ DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, _result, format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while (0) /* Notes on macros that have ENABLE_FAILSIM variants. * * Care must be taken with the DBGTRC_ macros that have ENABLE_FAILSIM variants. * * - The macros are passed the name of a variable that may be modified by a * failure simulation function. Therefore, what is specified in the return * value field of these macros must be a simple variable that can be the * lvalue of an assignment, not an expression or a constant. * * - DBGTRC__2() variants of the macros specify an lvalue expression that is to be * set to NULL if an error is injected. The supports the common case * where the return code is 0 or NULL iff the lvalue is non-null. */ #ifdef ENABLE_FAILSIM #define DBGTRC_RET_DDCRC(debug_flag, trace_group, rc, format, ...) \ do { \ if (failsim_enabled && rc != 0) { \ int injected = fsim_int_injector(rc, __FILE__, __func__); \ if (injected) { \ rc = injected; \ printf("(%s) failsim: injected error %s\n", __func__, psc_desc(rc)); \ } \ } \ dbgtrc_ret_ddcrc( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, rc, format, ##__VA_ARGS__); \ pop_traced_function(__func__); } while (0) #define DBGTRC_RET_DDCRC2(debug_flag, trace_group, _rc, _data_pointer, format, ...) \ do { \ if (failsim_enabled && _rc == 0) { \ int injected = fsim_int_injector(_rc, __FILE__, __func__); \ if (injected) { \ _rc = injected; \ printf("(%s) failsim: injected error %s, setting %s = NULL\n", __func__, psc_desc(_rc), #_data_pointer); \ if (_data_pointer) { \ free(_data_pointer); \ _data_pointer = NULL; \ } \ } \ } \ dbgtrc_ret_ddcrc( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, _rc, format, ##__VA_ARGS__); \ pop_traced_function(__func__); } while (0) #else #define DBGTRC_RET_DDCRC(debug_flag, trace_group, rc, format, ...) \ do { \ dbgtrc_ret_ddcrc( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), \ DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, rc, format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while (0) #define DBGTRC_RET_DDCRC2(debug_flag, trace_group, rc, data_pointer, format, ...) \ do { \ dbgtrc_ret_ddcrc( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, rc, format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while (0) #endif #ifdef ENABLE_FAILSIM #define DBGTRC_RET_ERRINFO(debug_flag, trace_group, errinfo_result, format, ...) \ do { \ if (failsim_enabled && !errinfo_result) { \ Error_Info * injected = fsim_errinfo_injector(errinfo_result, __FILE__, __func__); \ if (injected) { \ errinfo_result = injected; \ printf("(%s) Injected error %s\n", __func__, errinfo_summary(injected)); \ } \ } \ dbgtrc_returning_errinfo( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, errinfo_result, format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while(0) #define DBGTRC_RET_ERRINFO2(debug_flag, trace_group, errinfo_result, data_pointer, format, ...) \ do { \ if (failsim_enabled && !errinfo_result) { \ Error_Info * injected = fsim_errinfo_injector(errinfo_result, __FILE__, __func__); \ if (injected) { \ errinfo_result = injected; \ if (data_pointer) { \ free(data_pointer); \ data_pointer = NULL; \ } \ printf("(%s) Injected error %s, setting %s = NULL\n", __func__, errinfo_summary(injected), #data_pointer); \ } \ } \ dbgtrc_returning_errinfo( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, errinfo_result, format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while(0) #else #define DBGTRC_RET_ERRINFO(debug_flag, trace_group, errinfo_result, format, ...) \ do { \ dbgtrc_returning_errinfo( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), \ DBGTRC_OPTIONS_DONE, __func__, __LINE__, __FILE__, errinfo_result, format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while (0) #define DBGTRC_RET_ERRINFO2(debug_flag, trace_group, errinfo_result, pointer, format, ...) \ do { \ dbgtrc_returning_errinfo( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), \ DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, errinfo_result, format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while (0) #endif // can only pass a variable, not an expression or constant, to DBGTRC_RET_BOOL() // because failure simulation may assign a new value to the variable #define DBGTRC_RET_BOOL(debug_flag, trace_group, bool_result, format, ...) \ do { \ dbgtrc_returning_string( \ (debug_flag) || trace_callstack_call_depth > 0 ? DDCA_TRC_ALL : (trace_group), \ DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, SBOOL(bool_result), format, ##__VA_ARGS__); \ pop_traced_function(__func__); \ } while (0) // typedef (*dbg_struct_func)(void * structptr, int depth); #define DBGMSF_RET_STRUCT(_debug_flag, _structname, _dbgfunc, _structptr) \ do { \ if ((_debug_flag) || trace_callstack_call_depth > 0) { \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_DONE, __func__, __LINE__, __FILE__, \ "Returning %s at %p", #_structname, _structptr); \ if (_structptr) { \ _dbgfunc(_structptr, 1); \ } \ } \ pop_traced_function(__func__); \ } while (0) #define DBGTRC_RET_STRUCT(_flag, _trace_group, _structname, _dbgfunc, _structptr) \ do { \ if ( (_flag) || trace_callstack_call_depth > 0 || is_tracing(_trace_group, __FILE__, __func__) ) { \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, \ "Returning %s at %p", #_structname, _structptr); \ if (_structptr) { \ _dbgfunc(_structptr, 1); \ } \ } \ pop_traced_function(__func__); \ } while(0) #define DBGTRC_RET_STRUCT_VALUE(_flag, _trace_group, _structname, _dbgfunc, _structval) \ do { \ if ( (_flag) || trace_callstack_call_depth > 0 || is_tracing(_trace_group, __FILE__, __func__) ) { \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, \ "Returning %s value:", #_structname); \ _dbgfunc(_structval, 2); \ } \ pop_traced_function(__func__); \ } while(0) #define DBGTRC_RET_ERRINFO_STRUCT(_debug_flag, _trace_group, _errinfo_result, \ _structptr_loc, _dbgfunc) \ do { \ if ( (_debug_flag || trace_callstack_call_depth > 0 ) || is_tracing(_trace_group, __FILE__, __func__) ) { \ dbgtrc_returning_errinfo(DDCA_TRC_ALL, DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, \ _errinfo_result, "*%s = %p", #_structptr_loc, *_structptr_loc); \ if (*_structptr_loc) { \ _dbgfunc(*_structptr_loc, 1); \ } \ } \ pop_traced_function(__func__); \ } while(0) // // Error handling // #define REPORT_IOCTL_ERROR(_ioctl_name, _errnum) \ dbgtrc(DDCA_TRC_ALL, DBGTRC_OPTIONS_SEVERE, __func__, __LINE__, __FILE__, \ "Error in ioctl(%s), %s", _ioctl_name, linux_errno_desc(_errnum)); // reports a program logic error void program_logic_error( const char * funcname, const int lineno, const char * fn, char * format, ...); /** @def PROGRAM_LOGIC_ERROR(format,...) * Wraps call to program_logic_error() * * Reports an error in program logic. * @ingroup abnormal_termination */ #define PROGRAM_LOGIC_ERROR(format, ...) \ program_logic_error(__func__, __LINE__, __FILE__, format, ##__VA_ARGS__) void set_default_thread_output_settings(FILE * fout, FILE * ferr); #ifdef UNUSED void core_errmsg_emitter( GPtrArray* errmsgs, GPtrArray * errinfo_accum, bool verbose, int rc, const char * func, const char * msg, ...); #endif // // Use of system log // extern bool msg_to_syslog_only; extern bool enable_syslog; extern DDCA_Syslog_Level syslog_level; DDCA_Syslog_Level syslog_level_name_to_value(const char * name); const char * syslog_level_name(DDCA_Syslog_Level level); bool test_emit_syslog(DDCA_Syslog_Level msg_level); int syslog_importance_from_ddcutil_syslog_level(DDCA_Syslog_Level level); extern const char * valid_syslog_levels_string; /** Checks that the specified ddcutil severity level is at least as great * as the severity cutoff level currently in effect. If so, the ddcutil * severity is converted to a syslog severity, and the messages is written * to the system log. * * @param _ddcutil_severity e.g. DDCA_SYSLOG_ERROR * @param fmt message format * @param ... message arguments */ #define DECORATED_SYSLOG(_ddcutil_severity, format, ...) \ do { \ if (test_emit_syslog(_ddcutil_severity)) { \ int syslog_priority = syslog_importance_from_ddcutil_syslog_level(_ddcutil_severity); \ if (syslog_priority >= 0) { \ char * body = g_strdup_printf(format, ##__VA_ARGS__); \ char prefix[100] = {0}; \ if (rpt_get_ornamentation_enabled() ) { \ get_msg_decoration(prefix, 100, true); \ } \ syslog(syslog_priority, "%s%s%s", prefix, body, (tag_output) ? " (N)" : "" ); \ free(body); \ } \ } \ } while(0) #define SYSLOG2(_ddcutil_severity, format, ...) \ do { \ if (test_emit_syslog(_ddcutil_severity)) { \ int syslog_priority = syslog_importance_from_ddcutil_syslog_level(_ddcutil_severity); \ if (syslog_priority >= 0) { \ char * body = g_strdup_printf(format, ##__VA_ARGS__); \ syslog(syslog_priority, PRItid" %s%s", (intmax_t) tid(), body, (tag_output) ? " (P)" : "" ); \ free(body); \ } \ } \ } while(0) /** Writes a message to the current ferr() or fout() device and, depending on * the specified ddcutil severity and current syslog level, to the system log. * * @param _ddcutil_severity e.g. DDCA_SYSLOG_ERROR * @param fmt message format * @param ... message arguments * * Messages with ddcutil severity DDCA_SYSLOG_WARNING or more severe are * written to the ferr() device. Others are written to the fout() device. * * Messages are written to the system log with the syslog priority * corresponding to the ddcutil severity. * * If global **msg_to_syslog_only** is set, the message is written only * to the system log, not to the terminal. This is avoid duplicate messages * in the system log if terminal output is redirected to the system log, * as is the case for KDE applications. */ #define MSG_W_SYSLOG(_ddcutil_severity, format, ...) \ do { \ if (!msg_to_syslog_only) { \ FILE * f = (_ddcutil_severity <= DDCA_SYSLOG_WARNING) ? ferr() : fout(); \ fprintf(f, format, ##__VA_ARGS__); \ fprintf(f, "\n"); \ } \ if (test_emit_syslog(_ddcutil_severity)) { \ int syslog_priority = syslog_importance_from_ddcutil_syslog_level(_ddcutil_severity); \ if (syslog_priority >= 0) { \ char * body = g_strdup_printf(format, ##__VA_ARGS__); \ syslog(syslog_priority, PRItid" %s%s", (intmax_t) tid(), body, (tag_output) ? " (Q)" : "" ); \ free(body); \ } \ } \ } while(0) void base_errinfo_free_with_report( Error_Info * erec, bool report, const char * func); #define BASE_ERRINFO_FREE_WITH_REPORT(_erec, _report) \ base_errinfo_free_with_report(_erec, (_report), __func__) // // Output capture // void start_capture(DDCA_Capture_Option_Flags flags); char * end_capture(void); Null_Terminated_String_Array end_capture_as_ntsa(); // // Initialization // void detect_stdout_stderr_redirection(); void init_core(); #endif /* BASE_CORE_H_ */ ddcutil-2.2.0/src/base/ddcutil_types_internal.h0000644000175000001440000000451114754576332015263 /** @file ddcutil_types_internal.h * * Declarations removed from ddcutil_types.h * because they no longer need to public. */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDCUTIL_TYPES_INTERNAL_H_ #define DDCUTIL_TYPES_INTERNAL_H_ /** Callback function to report VCP value change */ typedef void (*DDCA_Notification_Func)(DDCA_Status psc, DDCA_Any_Vcp_Value* valrec); typedef int (*Simple_Callback_Func)(int val); // // I2C Protocol Control // //! I2C retry limit types typedef enum{ DDCA_WRITE_ONLY_TRIES, /**< Maximum write-only operation tries */ DDCA_WRITE_READ_TRIES, /**< Maximum read-write operation tries */ DDCA_MULTI_PART_TRIES /**< Maximum multi-part operation tries */ } DDCA_Retry_Type; //! Trace Control //! //! Used as bitflags to specify multiple trace types typedef enum { DDCA_TRC_BASE = 0x0080, /**< base functions */ DDCA_TRC_I2C = 0x0040, /**< I2C layer */ DDCA_TRC_ADL = 0x0020, /**< @deprecated ADL layer */ DDCA_TRC_DDC = 0x0010, /**< DDC layer */ DDCA_TRC_USB = 0x0008, /**< USB connected display functions */ DDCA_TRC_TOP = 0x0004, /**< ddcutil mainline */ DDCA_TRC_ENV = 0x0002, /**< environment command */ DDCA_TRC_API = 0x0001, /**< top level API functions */ DDCA_TRC_UDF = 0x0100, /**< user-defined, aka dynamic, features */ DDCA_TRC_VCP = 0x0200, /**< VCP layer, feature definitions */ DDCA_TRC_DDCIO = 0x0400, /**< DDC IO functions */ DDCA_TRC_SLEEP = 0x0800, /**< low level sleeps */ DDCA_TRC_RETRY = 0x1000, /**< successful retries, subset of DDCA_TRC_DDCIO */ DDCA_TRC_CONN = 0x2000, /**< watch for display connection/disconnection */ DDCA_TRC_SYSFS = 0x0400, /**< access /sys */ DDCA_TRC_NONE = 0x0000, /**< all tracing disabled */ DDCA_TRC_ALL = 0xffff /**< all tracing enabled */ } DDCA_Trace_Group; #ifdef ADL /** @deprecated ADL adapter number/display number pair, which identifies a display */ typedef struct { int iAdapterIndex; /**< adapter number */ int iDisplayIndex; /**< display number */ } DDCA_Adlno; #endif // uses -1,-1 for unset #endif /* DDCUTIL_TYPES_INTERNAL_H_ */ ddcutil-2.2.0/src/base/display_lock.h0000644000175000001440000000306114754576332013167 /* @file display_lock.h */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DISPLAY_LOCK_H_ #define DISPLAY_LOCK_H_ #include #include #include "ddcutil_types.h" #include "util/error_info.h" #include "base/core.h" #include "base/displays.h" typedef enum { DDISP_NONE = 0x00, ///< No flags set DDISP_WAIT = 0x01 ///< If set, #lock_display() should wait } Display_Lock_Flags; #define DISPLAY_LOCK_MARKER "DDSC" typedef struct { char marker[4]; DDCA_IO_Path io_path; GMutex display_mutex; GThread * display_mutex_thread; // thread owning mutex intmax_t linux_thread_id; } Display_Lock_Record; Display_Lock_Record * create_display_lock_record(DDCA_IO_Path io_path); void terminate_i2c_display_lock(); Error_Info * lock_display(Display_Lock_Record * id, Display_Lock_Flags flags); Error_Info * lock_display_by_dpath(DDCA_IO_Path dpath, Display_Lock_Flags flags); Error_Info * unlock_display(Display_Lock_Record * id); #ifdef UNUSED Error_Info * lock_display2(Display_Lock_Record * dlr, Display_Lock_Flags flags); Error_Info * unlock_display2(Display_Lock_Record * dlr); #endif Error_Info * unlock_display_by_dpath(DDCA_IO_Path dpath); void dbgrpt_display_locks(int depth); char * interpret_display_lock_flags_t(Display_Lock_Flags lock_flags); void init_i2c_display_lock(void); #endif /* DISPLAY_LOCK_H_ */ ddcutil-2.2.0/src/base/displays.h0000644000175000001440000002752114754576332012351 /** @file displays.h Display Specification */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DISPLAYS_H_ #define DISPLAYS_H_ /** \cond **/ #include #include #include "util/coredefs.h" #include "util/edid.h" /** \endcond */ #include "public/ddcutil_types.h" #include "core.h" #include "ddcutil_types_internal.h" #include "dynamic_features.h" #include "feature_set_ref.h" #include "monitor_model_key.h" #include "vcp_version.h" extern bool terminate_watch_thread; extern GPtrArray * all_display_refs; // all detected displays, array of Display_Ref * extern GMutex all_display_refs_mutex; extern bool debug_locks; /** \file Display Specification Monitors are specified in different ways in different contexts: 1) Display_Identifier contains the identifiers specified on the command line. 2) Display_Ref is a logical display identifier. It can be an I2C identifier or a USB identifier. For Display_Identifiers containing a busno (for I2C) or hiddev device number (USB), the translation from Display_Identier to Display_Ref is direct. Otherwise, displays are searched to find the monitor. 3) Display_Handle is passed as an argument to "open" displays. For I2C displays, the device must be opened. Display_Handle then contains the open file handle. */ // *** Initialization *** void init_displays(); void terminate_displays(); // *** DDCA_IO_Path *** #define BUSNO_NOT_SET 255 char * io_mode_name(DDCA_IO_Mode val); bool dpath_eq(DDCA_IO_Path p1, DDCA_IO_Path p2); char * dpath_short_name_t(DDCA_IO_Path * dpath); char * dpath_repr_t(DDCA_IO_Path * dpath); // value valid until next call int dpath_hash(DDCA_IO_Path path); DDCA_IO_Path i2c_io_path(int busno); DDCA_IO_Path usb_io_path(int hiddev_devno); // *** Display_Identifier *** /** Display_Identifier type */ typedef enum { DISP_ID_BUSNO, ///< /dev/i2c bus number DISP_ID_MONSER, ///< monitor mfg id, model name, and/or serial number DISP_ID_EDID, ///< 128 byte EDID DISP_ID_DISPNO, ///< ddcutil assigned display number DISP_ID_USB, ///< USB bus/device number pair DISP_ID_HIDDEV ///< /dev/usb/hiddev device number } Display_Id_Type; char * display_id_type_name(Display_Id_Type val); #define DISPLAY_IDENTIFIER_MARKER "DPID" /** Specifies the identifiers to be used to select a display. */ typedef struct { char marker[4]; // always "DPID" Display_Id_Type id_type; int dispno; int busno; char mfg_id[EDID_MFG_ID_FIELD_SIZE]; char model_name[EDID_MODEL_NAME_FIELD_SIZE]; char serial_ascii[EDID_SERIAL_ASCII_FIELD_SIZE]; int usb_bus; int usb_device; int hiddev_devno; // 4/1027 Byte edidbytes[128]; char * repr; } Display_Identifier; Display_Identifier* create_dispno_display_identifier(int dispno); Display_Identifier* create_busno_display_identifier(int busno); Display_Identifier* create_edid_display_identifier(const Byte* edidbytes); Display_Identifier* create_mfg_model_sn_display_identifier(const char* mfg_code, const char* model_name, const char* serial_ascii); Display_Identifier* create_usb_display_identifier(int bus, int device); Display_Identifier* create_usb_hiddev_display_identifier(int hiddev_devno); char * did_repr(Display_Identifier * pdid); void dbgrpt_display_identifier(Display_Identifier * pdid, int depth); void free_display_identifier(Display_Identifier * pdid); // #ifdef FUTURE // new way #define DISPLAY_SELECTOR_MARKER "DSEL" typedef struct { char marker[4]; // always "DSEL" int dispno; int busno; char * mfg_id; char * model_name; char * serial_ascii; int usb_bus; int usb_device; Byte * edidbytes; // always 128 bytes } Display_Selector; #ifdef FUTURE Display_Selector * dsel_new(); void dsel_free( Display_Selector * dsel); Display_Selector * dsel_set_display_number(Display_Selector* dsel, int dispno); Display_Selector * dsel_set_i2c_busno( Display_Selector* dsel, int busno); Display_Selector * dsel_set_usb_numbers( Display_Selector* dsel, int bus, int device); Display_Selector * dsel_set_mfg_id( Display_Selector* dsel, char* mfg_id); Display_Selector * dsel_set_model_name( Display_Selector* dsel, char* model_name); Display_Selector * dsel_set_sn( Display_Selector* dsel, char * serial_ascii); Display_Selector * dsel_set_edid_bytes( Display_Selector* dsel, Byte * edidbytes); Display_Selector * dsel_set_edid_hex( Display_Selector* dsel, char * hexstring); bool dsel_validate( Display_Selector * dsel); #endif // *** Display_Ref *** extern bool ddc_never_uses_null_response_for_unsupported; // extern bool ddc_always_uses_null_response_for_unsupported; // Must be kept in sync with dref_flags_table typedef uint16_t Dref_Flags; #define DREF_DDC_COMMUNICATION_CHECKED 0x0001 #define DREF_DDC_COMMUNICATION_WORKING 0x0002 #define DREF_DDC_IS_MONITOR_CHECKED 0x0004 #define DREF_DDC_IS_MONITOR 0x0008 #define DREF_UNSUPPORTED_CHECKED 0x0010 #define DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED 0x0020 #define DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED 0x0040 #define DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED 0x0080 #define DREF_DDC_DOES_NOT_INDICATE_UNSUPPORTED 0x0100 #define DREF_DYNAMIC_FEATURES_CHECKED 0x0200 #define DREF_TRANSIENT 0x0400 #define DREF_OPEN 0x0800 #define DREF_DDC_BUSY 0x1000 #define DREF_REMOVED 0x2000 #define DREF_DDC_DISABLED 0x4000 #define DREF_DPMS_SUSPEND_STANDBY_OFF 0x8000 char * interpret_dref_flags_t(Dref_Flags flags); // define in ddcutil_types.h?, or perhaps use -1 for generic invalid, put type of invalid in Dref_Flags? #define DISPNO_NOT_SET 0 #define DISPNO_INVALID -1 #define DISPNO_PHANTOM -2 #define DISPNO_REMOVED -3 #define DISPNO_BUSY -4 #define DISPNO_DDC_DISABLED -5 #define DISPLAY_REF_MARKER "DREF" /** A **Display_Ref** is a logical display identifier. * It can contain an I2C bus number or a USB bus number/device number pair. */ typedef struct _display_ref { char marker[4]; uint dref_id; DDCA_IO_Path io_path; int usb_bus; int usb_device; char * usb_hiddev_name; DDCA_MCCS_Version_Spec vcp_version_xdf; DDCA_MCCS_Version_Spec vcp_version_cmdline; Dref_Flags flags; char * capabilities_string; // added 4/2017, private copy Parsed_Edid * pedid; // added 4/2017 Monitor_Model_Key * mmid; // will be set iff pedid int dispno; void * detail; // I2C_Bus_Info or Usb_Monitor_Info Dynamic_Features_Rec * dfr; // user defined feature metadata uint64_t next_i2c_io_after; // nanosec struct _display_ref * actual_display; // if dispno == -2 DDCA_IO_Path * actual_display_path; // alt to actual_display #ifdef OLD char * driver_name; // #endif struct Per_Display_Data* pdd; char * drm_connector; // e.g. card0-HDMI-A-1 // REDUNDANT - IDENTICAL TO Bus_Info.drm_connector int drm_connector_id; // identical to Bus_Info.drm_connector_id char * communication_error_summary; uint64_t creation_timestamp; GMutex access_mutex; } Display_Ref; void dbgrpt_published_dref_hash(const char * msg, int depth); void init_published_dref_hash(); void reset_published_dref_hash(); void add_published_dref_id_by_dref(Display_Ref * dref); Display_Ref * dref_from_published_ddca_dref(DDCA_Display_Ref ddca_dref); DDCA_Display_Ref dref_to_ddca_dref(Display_Ref * dref); #define DREF_BUSNO(_dref) ((_dref)->io_path.path.i2c_busno) #define ASSERT_DREF_IO_MODE(_dref, _mode) \ assert(_dref && \ memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0) && \ _dref->io_path.io_mode == _mode) Display_Ref * create_base_display_ref(DDCA_IO_Path io_path); Display_Ref * create_bus_display_ref(int busno); Display_Ref * create_usb_display_ref(int bus, int device, char * hiddev_devname); void dbgrpt_display_ref(Display_Ref * dref, bool include_businfo, int depth); void dbgrpt_display_ref0(Display_Ref * dref, int depth); void dbgrpt_display_ref_summary(Display_Ref * dref, bool include_businfo, int depth); char * dref_short_name_t(Display_Ref * dref); char * dref_repr_t(Display_Ref * dref); // value valid until next call char * dref_reprx_t(Display_Ref * dref); // value valid until next call char * ddci_dref_repr_t(DDCA_Display_Ref * ddca_dref); // value valid until next call DDCA_Status free_display_ref(Display_Ref * dref); Display_Ref * copy_display_ref(Display_Ref * dref); void dref_lock(Display_Ref * dref); void dref_unlock(Display_Ref * dref); // Do two Display_Ref's identify the same device? bool dref_eq(Display_Ref* this, Display_Ref* that); const char * dref_get_i2c_driver(Display_Ref* dref); #ifdef UNUSED bool dref_set_alive(Display_Ref * dref, bool alive); bool dref_get_alive(Display_Ref * dref); #endif Display_Ref* get_dref_by_busno_or_connector(int busno, const char * connector, bool ignore_invalid); #define GET_DREF_BY_BUSNO(_busno, _ignore) \ get_dref_by_busno_or_connector(_busno,NULL, (_ignore)) #define GET_DREF_BY_CONNECTOR(_connector_name, _ignore_invalid) \ get_dref_by_busno_or_connector(-1, _connector_name, _ignore_invalid) // *** Display_Handle *** #define DISPLAY_HANDLE_MARKER "DSPH" /** Describes an open display device. */ typedef struct { char marker[4]; Display_Ref* dref; int fd; // file descriptor char * repr; char * repr_p; bool testing_unsupported_feature_active; } Display_Handle; Display_Handle * create_base_display_handle(int fd, Display_Ref * dref); void dbgrpt_display_handle(Display_Handle * dh, const char * msg, int depth); char * dh_repr(Display_Handle * dh); char * dh_repr_p(Display_Handle * dh); void free_display_handle(Display_Handle * dh); // For internal display selection functions #define DISPSEL_NONE 0x00 #define DISPSEL_VALID_ONLY 0x80 #ifdef FUTURE #define DISPSEL_I2C 0x40 #define DISPSEL_USB 0x10 #define DISPSEL_ANY (DISPSEL_I2C | DISPSEL_USB) #endif //* Option flags for display selection functions */ typedef Byte Display_Selection_Options; int hiddev_name_to_number(const char * hiddev_name); #ifdef UNUSED char * hiddev_number_to_name(int hiddev_number); #endif /** For recording /dev/i2c and hiddev open errors */ typedef struct { DDCA_IO_Mode io_mode; int devno; // i2c bus number or hiddev device number int error; char * detail; } Bus_Open_Error; void free_bus_open_error(Bus_Open_Error * boe); typedef enum { Watch_Mode_Dynamic, Watch_Mode_Poll, Watch_Mode_Xevent, Watch_Mode_Udev, } DDC_Watch_Mode; const char * watch_mode_name(DDC_Watch_Mode mode); bool add_disabled_display(Monitor_Model_Key * mmk); bool add_disabled_mmk_by_string(const char * mmid); void dbgrpt_ddc_disabled_table(int depth); bool is_disabled_mmk(Monitor_Model_Key mmk); #endif /* DISPLAYS_H_ */ ddcutil-2.2.0/src/base/drm_connector_state.h0000644000175000001440000000214014754576332014543 /** @file drm_connector_state.h */ // Copyright (C) 2020-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DRM_CONNECTOR_STATE_H_ #define DRM_CONNECTOR_STATE_H_ /** \cond */ #include #include #include #include #include #include "util/drm_common.h" #include "util/edid.h" /** \endcond */ typedef struct { int cardno; int connector_id; uint32_t connector_type; uint32_t connector_type_id; drmModeConnection connection; Parsed_Edid * edid; uint64_t link_status; uint64_t dpms; uint64_t subconnector; } Drm_Connector_State; void redetect_drm_connector_states(); void report_drm_connector_states(int depth); void report_drm_connector_states_basic(bool refresh, int depth); Drm_Connector_State * find_drm_connector_state(Drm_Connector_Identifier cid); void init_drm_connector_state(); #endif /* DRM_CONNECTOR_STATE_H_ */ ddcutil-2.2.0/src/base/dynamic_features.h0000644000175000001440000000640514754576332014041 /** @file dynamic_features.h * * Dynamic Feature Record definition, creation, destruction, and conversion */ // Copyright (C) 2022-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BASE_DYNAMIC_FEATURES_H_ #define BASE_DYNAMIC_FEATURES_H_ /** \cond */ #include #include /** \endcond */ #include "ddcutil_types.h" #include "util/error_info.h" typedef enum { DFR_FLAGS_NONE = 0, DFR_FLAGS_NOT_FOUND = 1, DFR_FLAG_EXCLUDE_FROM_API = 2, } DFR_Flags; // Replaces use of DDCA_Feature_Metadata for representing dynamic spec read from file #define DYN_FEATURE_METADATA_MARKER "DMET" /** Describes a VCP feature code, as read from a dynamic feature record. */ typedef struct { char marker[4]; /**< always "DMET" */ DDCA_Vcp_Feature_Code feature_code; /**< VCP feature code */ DDCA_MCCS_Version_Spec vcp_version; /**< MCCS version */ // DDCA_Feature_Flags feature_flags; /**< feature type description */ DDCA_Global_Feature_Flags global_feature_flags; DDCA_Version_Feature_Flags version_feature_flags; DDCA_Feature_Value_Entry * sl_values; /**< valid when DDCA_SIMPLE_NC set */ void * unused; /** no longer used, was latest_sl_values */ char * feature_name; /**< feature name */ char * feature_desc; /**< feature description */ // possibly add pointers to formatting functions } Dyn_Feature_Metadata; #define DYNAMIC_FEATURES_REC_MARKER "DFRC" typedef struct { char marker[4]; char * mfg_id; // [EDID_MFG_ID_FIELD_SIZE]; char * model_name; // [EDID_MODEL_NAME_FIELD_SIZE]; uint16_t product_code; char * filename; // source filename, if applicable DDCA_MCCS_Version_Spec vspec; DFR_Flags flags; GHashTable * features; // hash table of Dyn_Feature_Metadata } Dynamic_Features_Rec; // value valid until next call: char * dfr_repr_t( Dynamic_Features_Rec * dfr); Dynamic_Features_Rec * dfr_new( const char * mfg_id, const char * model_name, uint16_t product_code, const char * filename); void dfr_free( Dynamic_Features_Rec * frec); Error_Info * create_dynamic_features_rec( const char * mfg_id, const char * model_name, uint16_t product_code, GPtrArray * lines, const char * filename, // may be NULL Dynamic_Features_Rec ** dynamic_features_loc); Dyn_Feature_Metadata * dyn_get_dynamic_feature_metadata( Dynamic_Features_Rec * dfr, uint8_t feature_code); // satisfies glib signature void dyn_free_feature_metadata( Dyn_Feature_Metadata* data); // castable to GDestroyNotify void dbgrpt_dynamic_features_rec( Dynamic_Features_Rec* dfr, int depth); void init_base_dynamic_features(); #endif /* BASE_DYNAMIC_FEATURES_H_ */ ddcutil-2.2.0/src/base/feature_metadata.h0000644000175000001440000001232014754576332014003 /* @file feature_metadata.h * * Functions for external and internal representation of * display-specific feature metadata. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef FEATURE_METADATA_H_ #define FEATURE_METADATA_H_ /** \cond */ #include #include /** \endcond */ #include "ddcutil_types.h" #include "util/data_structures.h" #include "base/dynamic_features.h" #include "base/feature_set_ref.h" /** Simple stripped-down version of Parsed_Nontable_Vcp_Response */ typedef struct { DDCA_Vcp_Feature_Code vcp_code; gushort max_value; gushort cur_value; // for new way Byte mh; Byte ml; Byte sh; Byte sl; } Nontable_Vcp_Value; char * nontable_vcp_value_repr_t(Nontable_Vcp_Value * vcp_value); // Prototypes for functions that format feature values typedef bool (*Format_Normal_Feature_Detail_Function) ( Nontable_Vcp_Value* code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); typedef bool (*Format_Normal_Feature_Detail_Function2) ( Nontable_Vcp_Value* code_info, // Display_Ref * dref, // DDCA_MCCS_Version_Spec vcp_version, DDCA_Feature_Value_Entry * sl_values, char * buffer, int bufsz); typedef bool (*Format_Table_Feature_Detail_Function) ( Buffer * data_bytes, DDCA_MCCS_Version_Spec vcp_version, char ** p_result_buffer); // combines Format_Normal_Feature_Detail_Fucntion, Format_Normal_Detail_Function2 // for future use typedef bool (*Format_Normal_Feature_Detail_Function3) ( Nontable_Vcp_Value* code_info, DDCA_MCCS_Version_Spec vcp_version, DDCA_Feature_Value_Entry * sl_values, char * buffer, int bufsz); //typedef //bool (*Format_Table_Feature_Detail_Functionx) ( // Buffer * data_bytes, // DDCA_MCCS_Version_Spec vcp_version, // char ** p_result_buffer); // Feature value table functions void dbgrpt_sl_value_table(DDCA_Feature_Value_Entry * table, char * title, int depth); DDCA_Feature_Value_Entry * copy_sl_value_table(DDCA_Feature_Value_Entry * oldtable); void free_sl_value_table(DDCA_Feature_Value_Entry * table); char * sl_value_table_lookup(DDCA_Feature_Value_Entry * value_entries, Byte value_id); // Feature Flags // char * interpret_feature_flags_t(DDCA_Version_Feature_Flags flags); const char * interpret_ddca_feature_flags_symbolic_t(DDCA_Feature_Flags flags); const char * interpret_ddca_global_feature_flags_symbolic_t(DDCA_Feature_Flags flags); const char * interpret_ddca_version_feature_flags_symbolic_t(DDCA_Feature_Flags flags); // DDCA_Feature_Metadata void dbgrpt_ddca_feature_metadata(DDCA_Feature_Metadata * md, int depth); void dbgrpt_dyn_feature_metadata(Dyn_Feature_Metadata * md, int depth); void free_ddca_feature_metadata(DDCA_Feature_Metadata * metadata); // Display_Feature_Metadata #define DISPLAY_FEATURE_METADATA_MARKER "DFMD" /** Internal version of display specific feature metadata, includes formatting functions * * Represents merged internal metadata from vcp_code_tables.c, synthetic metadata, * and user defined features, for a specific VCP version. * */ typedef struct { char marker[4]; DDCA_Display_Ref display_ref; // needed? DDCA_Vcp_Feature_Code feature_code; DDCA_MCCS_Version_Spec vcp_version; // needed - yes, used in ddcui gushort vcp_spec_groups; VCP_Feature_Subset vcp_subsets; char * feature_name; char * feature_desc; DDCA_Feature_Value_Entry * sl_values; /**< valid when DDCA_SIMPLE_NC set */ // DDCA_Feature_Flags feature_flags; DDCA_Feature_Flags global_feature_flags; DDCA_Feature_Flags version_feature_flags; Format_Normal_Feature_Detail_Function nontable_formatter; Format_Normal_Feature_Detail_Function2 nontable_formatter_sl; Format_Normal_Feature_Detail_Function3 nontable_formatter_universal; // the future Format_Table_Feature_Detail_Function table_formatter; } Display_Feature_Metadata; void dbgrpt_display_feature_metadata(Display_Feature_Metadata * meta, int depth); void dfm_free(Display_Feature_Metadata * meta); Display_Feature_Metadata * dfm_new(DDCA_Vcp_Feature_Code feature_code); #ifdef UNUSED void dfm_set_feature_name(Display_Feature_Metadata * meta, const char * feature_name); void dfm_set_feature_desc(Display_Feature_Metadata * meta, const char * feature_desc); #endif // Conversion functions DDCA_Feature_Metadata * dfm_to_ddca_feature_metadata(Display_Feature_Metadata * dfm); Display_Feature_Metadata * dfm_from_dyn_feature_metadata(Dyn_Feature_Metadata * meta); void init_feature_metadata(); #endif /* FEATURE_METADATA_H_ */ ddcutil-2.2.0/src/base/feature_set_ref.h0000644000175000001440000000664214754576332013664 /* \file feature_sets.h * * Feature set identifiers */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef FEATURE_SET_REF_H_ #define FEATURE_SET_REF_H_ /** \cond */ #include #include "util/coredefs.h" #include "util/data_structures.h" /** \endcond */ // If ids are added to or removed from this enum, be sure to update the // corresponding tables in feature_sets.c, cmd_parser_aux.c typedef enum { // ddcutil defined groups // 0x80000000, // unusable, error if high bit set VCP_SUBSET_PROFILE = 0x40000000, VCP_SUBSET_COLOR = 0x20000000, VCP_SUBSET_LUT = 0x10000000, // MCCS spec groups VCP_SUBSET_CRT = 0x08000000, VCP_SUBSET_TV = 0x04000000, VCP_SUBSET_AUDIO = 0x02000000, VCP_SUBSET_WINDOW = 0x01000000, VCP_SUBSET_DPVL = 0x00800000, VCP_SUBSET_PRESET = 0x00400000, // uses VCP_SPEC_PRESET // Subsets by feature type VCP_SUBSET_SCONT = 0x00100000, // simple Continuous feature VCP_SUBSET_CCONT = 0x00080000, // complex Continuous feature VCP_SUBSET_CONT = 0x00040000, // Continuous feature VCP_SUBSET_SNC = 0x00020000, // simple NC feature VCP_SUBSET_CNC = 0x00010000, // complex NC feature VCP_SUBSET_NC_WO = 0x00008000, // write-only NC feature VCP_SUBSET_NC_CONT = 0x00004000, // combines reserved values with a continuous subrange VCP_SUBSET_NC = 0x00002000, // Non-Continuous feature VCP_SUBSET_TABLE = 0x00001000, // is a table feature VCP_SUBSET_XNC = 0x00000800, // extended NC feature (user defined only) // subsets used only on command processing, not in feature descriptor table VCP_SUBSET_SCAN = 0x00000040, // VCP_SUBSET_ALL = 0x00000040, // VCP_SUBSET_SUPPORTED = 0x00000020, VCP_SUBSET_KNOWN = 0x00000020, VCP_SUBSET_MFG = 0x00000010, // mfg specific codes VCP_SUBSET_UDF = 0x00000008, // user defined features VCP_SUBSET_SINGLE_FEATURE = 0x00000002, VCP_SUBSET_MULTI_FEATURES = 0x00000001, // user defined collection of features VCP_SUBSET_NONE = 0x00000000, } VCP_Feature_Subset; extern const int vcp_subset_count; // number of VCP_Feature_Subset values char * feature_subset_name(VCP_Feature_Subset subset_id); char * feature_subset_names(VCP_Feature_Subset subset_ids); typedef struct { VCP_Feature_Subset subset; // Byte specific_feature; Bit_Set_256 features; // for VCP_SUBSET_MULTI_FEATURES } Feature_Set_Ref; typedef enum { // apply to multiple feature feature sets FSF_SHOW_UNSUPPORTED = 0x01, FSF_NOTABLE = 0x02, FSF_RW_ONLY = 0x04, FSF_RO_ONLY = 0x08, FSF_WO_ONLY = 0x10, #ifdef UNUSED // applies to single feature feature set FSF_FORCE = 0x20, #endif FSF_CHECK_UDF = 0x40, } Feature_Set_Flags; #define FSF_READABLE_ONLY (FSF_RW_ONLY | FSF_RO_ONLY) char * feature_set_flag_names_t(Feature_Set_Flags flags); void dbgrpt_feature_set_ref(Feature_Set_Ref * fsref, int depth); char * fsref_repr_t(Feature_Set_Ref * fsref); #endif /* FEATURE_SET_REF_H_ */ ddcutil-2.2.0/src/base/flock.h0000644000175000001440000000105114754576332011605 /** @file flock.h */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef FLOCK_H_ #define FLOCK_H_ #include #include "public/ddcutil_status_codes.h" extern int flock_poll_millisec; extern int flock_max_wait_millisec; extern bool debug_flock; void i2c_enable_cross_instance_locks(bool yesno); Status_Errno flock_lock_by_fd(int fd, const char * filename, bool wait); Status_Errno flock_unlock_by_fd(int fd); void init_flock(); #endif /* FLOCK_H_ */ ddcutil-2.2.0/src/base/i2c_bus_base.h0000644000175000001440000001372614754576332013043 /** @file i2c_bus_base.h * */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_BUS_BASE_H_ #define I2C_BUS_BASE_H_ #include #include #include "util/data_structures.h" #include "util/edid.h" #include "util/error_info.h" #include "base/display_lock.h" extern bool primitive_sysfs; // Retrieve and inspect bus information // Keep in sync with i2c_bus_flags_table #define I2C_BUS_EXISTS 0x0001 // #define I2C_BUS_VALID_NAME_CHECKED 0x---- // #define I2C_BUS_HAS_VALID_NAME 0x---- // #define I2C_BUS_DRM_CONNECTOR_CHECKED 0x---- #define I2C_BUS_LVDS_OR_EDP 0x0002 #define I2C_BUS_APPARENT_LAPTOP 0x0004 // #define I2C_BUS_EDP 0x---- ///< bus associated with eDP display // #define I2C_BUS_LVDS 0x---- ///< bus associated with LVDS display // #define I2C_BUS_LAPTOP (I2C_BUS_EDP|I2C_BUS_LVDS) ///< bus associated with laptop display #define I2C_BUS_LAPTOP (I2C_BUS_LVDS_OR_EDP | I2C_BUS_APPARENT_LAPTOP) #define I2C_BUS_DISPLAYLINK 0x0008 #ifdef OLD #define I2C_BUS_SYSFS_UNRELIABLE 0x---- #endif #define I2C_BUS_SYSFS_KNOWN_RELIABLE 0x0010 #define I2C_BUS_INITIAL_CHECK_DONE 0x0020 #define I2C_BUS_DDC_DISABLED 0x0040 // Flags that can change when monitor connected/disconnected // #define I2C_BUS_ADDR_0X50 0x---- ///< detected I2C bus address 0x50, may or may not have valid EDID #define I2C_BUS_SYSFS_EDID 0x0100 ///< EDID was read from /sys #define I2C_BUS_X50_EDID 0x0200 ///< EDID was read using I2C #define I2C_BUS_HAS_EDID (I2C_BUS_SYSFS_EDID | I2C_BUS_X50_EDID) #define I2C_BUS_ADDR_X37 0x0400 ///< detected I2C bus address 0x37 #define I2C_BUS_ADDR_X30 0x0800 ///< detected write-only addr to specify EDID block number #define I2C_BUS_ACCESSIBLE 0x1000 ///< user could change permissions #define I2C_BUS_DDC_CHECKS_IGNORABLE 0x2000 // affected by display connection/disconnection? #define I2C_BUS_PROBED 0x8000 ///< has bus been checked? typedef enum { DRM_CONNECTOR_NOT_CHECKED = 0, // ??? needed? DRM_CONNECTOR_NOT_FOUND = 1, DRM_CONNECTOR_FOUND_BY_BUSNO = 2, DRM_CONNECTOR_FOUND_BY_EDID = 3 } Drm_Connector_Found_By; const char * drm_connector_found_by_name(Drm_Connector_Found_By found_by); #define I2C_BUS_INFO_MARKER "BINF" /** Information about one I2C bus */ typedef struct { char marker[4]; ///< always "BINF" int busno; ///< I2C device number, i.e. N for /dev/i2c-N unsigned long functionality; ///< i2c bus functionality flags Parsed_Edid * edid; ///< parsed EDID, if slave address x50 active #ifdef ALT_LOCK_REC Display_Lock_Record * lock_record; ///< #endif uint32_t flags; ///< I2C_BUS_* flags char * driver; ///< driver name int open_errno; ///< errno if open fails (!I2C_BUS_ACCESSIBLE) char * drm_connector_name; ///< from /sys Drm_Connector_Found_By drm_connector_found_by; int drm_connector_id; bool last_checked_dpms_asleep; } I2C_Bus_Info; char * i2c_interpret_bus_flags(uint16_t flags); char * i2c_interpret_bus_flags_t(uint16_t flags); // Accessors char * i2c_get_drm_connector_name(I2C_Bus_Info * bus_info); char * i2c_get_drm_connector_attribute(const I2C_Bus_Info * businfo, const char * attribute); #define I2C_GET_DRM_DPMS(_businfo) i2c_get_drm_connector_attribute(_businfo, "dpms") #define I2C_GET_DRM_STATUS(_businfo) i2c_get_drm_connector_attribute(_businfo, "status") #define I2C_GET_DRM_ENABLED(_businfo) i2c_get_drm_connector_attribute(_businfo, "enabled") // Lifecycle I2C_Bus_Info * i2c_new_bus_info(int busno); void i2c_free_bus_info(I2C_Bus_Info * businfo); void i2c_reset_bus_info(I2C_Bus_Info * bus_info); // Generalized Bus_Info retrieval I2C_Bus_Info * i2c_find_bus_info_in_gptrarray_by_busno(GPtrArray * buses, int busno); int i2c_find_bus_info_index_in_gptrarray_by_busno(GPtrArray * buses, int busno); // Reports void i2c_dbgrpt_bus_info(I2C_Bus_Info * businfo, bool include_sysinfo, int depth); // Detected Buses extern GPtrArray * all_i2c_buses; I2C_Bus_Info * i2c_add_bus(int busno); // void i2c_add_bus_info(I2C_Bus_Info * businfo); I2C_Bus_Info * i2c_get_bus_info(int busno, bool* new_info); void i2c_remove_bus_by_businfo(I2C_Bus_Info * businfo); void i2c_discard_buses0(GPtrArray* buses); void i2c_discard_buses(); void i2c_remove_bus_by_busno(int busno); I2C_Bus_Info * i2c_get_bus_info_by_index(guint busndx); I2C_Bus_Info * i2c_find_bus_info_by_busno(int busno); int i2c_dbgrpt_buses(bool report_all, bool include_sysfs_info, int depth); // Reports all detected i2c buses void i2c_dbgrpt_buses_summary(int depth); // Basic I2C bus operations bool i2c_device_exists(int busno); // Simple bus detection, no side effects int i2c_device_count(); // simple /dev/i2c-n count, no side effects Error_Info * i2c_check_device_access(char * dev_name); // Record display X37 status for reconnection typedef enum { X37_Not_Recorded = 0, X37_Not_Detected = 1, X37_Detected = 2 } X37_Detection_State; extern bool use_x37_detection_table; const char * x37_detection_state_name(X37_Detection_State state); void i2c_record_x37_detected(int busno, Byte * edidbytes, X37_Detection_State deteted); X37_Detection_State i2c_query_x37_detected(int busno, Byte * edidbytes); // Initialization and termination void init_i2c_bus_base(); void terminate_i2c_bus_base(); #endif /* I2C_BUS_BASE_H_ */ ddcutil-2.2.0/src/base/monitor_model_key.h0000644000175000001440000000400014754576332014223 /** @file monitor_model_key.h * Uniquely identifies a monitor model using its manufacturer id, * model name, and product code, as listed in the EDID. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef MONITOR_MODEL_KEY_H_ #define MONITOR_MODEL_KEY_H_ #include #include "public/ddcutil_types.h" #include "util/edid.h" #define FIXUP_MODEL_NAME(_name) \ for (int i=0; _name[i] && i < EDID_MODEL_NAME_FIELD_SIZE; i++) { \ if (!isalnum(_name[i])) \ _name[i] = '_'; \ } /** Identifies a monitor model */ typedef struct { char mfg_id[DDCA_EDID_MFG_ID_FIELD_SIZE]; char model_name[DDCA_EDID_MODEL_NAME_FIELD_SIZE]; uint16_t product_code; bool defined; } Monitor_Model_Key; Monitor_Model_Key mmk_value( const char * mfg_id, const char * model_name, uint16_t product_code); Monitor_Model_Key mmk_undefined_value(); Monitor_Model_Key mmk_value_from_edid(Parsed_Edid * edid); Monitor_Model_Key * mmk_new( const char * mfg_id, const char * model_name, uint16_t product_code); Monitor_Model_Key * mmk_new_from_edid( Parsed_Edid * edid); Monitor_Model_Key mmk_value_from_string(const char * sval); Monitor_Model_Key * mmk_new_from_value(Monitor_Model_Key mmk); Monitor_Model_Key * mmk_new_from_string(const char * s); #ifdef UNUSED Monitor_Model_Key * monitor_model_key_undefined_new(); #endif void mmk_free( Monitor_Model_Key * model_id); char * mmk_model_id_string( const char * mfg, const char * model_name, uint16_t product_code); bool monitor_model_key_eq( Monitor_Model_Key mmk1, Monitor_Model_Key mmk2); #ifdef UNUSED bool monitor_model_key_is_defined(Monitor_Model_Key mmk); #endif char * mmk_string( Monitor_Model_Key * model_id); char * mmk_repr(Monitor_Model_Key mmk); void init_monitor_model_key(); #endif /* MONITOR_MODEL_KEY_H_ */ ddcutil-2.2.0/src/base/parms.h0000644000175000001440000001362114754576332011637 /** @file parms.h * * System configuration and tuning */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PARMS_H_ #define PARMS_H_ #include "config.h" // // *** Build options that are not otherwise set // // if defined, DDCA_Display_Ref contains display ref id number instead of Display_Ref * #define NUMERIC_DDCA_DISPLAY_REF // #undef NUMERIC_DDCA_DISPLAY_REF // STATIC_FUNCTIONS_VISIBLE defined in config.h // If defined, remove static function qualifier on many functions to // make them visible to asan, valgrind, backtrace #ifdef STATIC_FUNCTIONS_VISIBLE #define STATIC #else #define STATIC static #endif // // *** Timeout values // // n. the DDC spec lists timeout values in milliseconds #define DDC_TIMEOUT_MILLIS_DEFAULT 50 ///< Normal timeout in DDC spec #define DDC_TIMEOUT_MILLIS_BETWEEN_GETVCP_WRITE_READ 40 ///< Between DDC Get Feature Request and Get Feature Reply #define DDC_TIMEOUT_MILLIS_POST_SETVCP_WRITE 50 ///< Following DDC Set VCP Feature command #define DDC_TIMEOUT_MILLIS_POST_SAVE_SETTINGS 200 ///< Following DDC Save Settings #define DDC_TIMEOUT_MILLIS_BETWEEN_CAP_TABLE_FRAGMENTS 50 #define DDC_TIMEOUT_MILLIS_POST_CAP_TABLE_COMMAND 50 ///< needed? spec ambiguous // Timeouts not part of DDC spec #define DDC_TIMEOUT_NONE 0 ///< No timeout #define DDC_TIMEOUT_MILLIS_NULL_RESPONSE_INCREMENT 50 ///< Used for dynamic tuned sleep in case of DDC Null Message response // // *** Method of low level I2C communication // // One of the following 2 defines must be enabled: #define DEFAULT_I2C_IO_STRATEGY I2C_IO_STRATEGY_IOCTL ///< Use ioctl() calls // #define DEFAULT_I2C_IO_STRATEGY I2C_IO_STRATEGY_FILEIO ///< Use read() and write() #define DEFAULT_DDC_READ_BYTEWISE false ///< Use single byte reads #define EDID_BUFFER_SIZE 256 ///< always 256 #define DEFAULT_EDID_WRITE_BEFORE_READ true #define DEFAULT_EDID_READ_SIZE 0 ///< 128, 256, 0=>dynamic #define DEFAULT_EDID_READ_USES_I2C_LAYER true #define DEFAULT_EDID_READ_BYTEWISE false // Strategy Bytewise read edid uses local i2c call read edid uses i2c layer // FILEIO false ok ok // FILEIO true on P2411h and Acer, reads byes 0. 2, 4 of response EDID ok, getvcp fails // IOCTL false ok All ok // IOCTL true on P2411h and Acer, returns corrupt data EDID ok, getvcp fails // // *** Retry Management *** // // Affects memory allocation in try_stats: #define MAX_MAX_TRIES 15 // All MAX_..._TRIES values must be <= MAX_MAX_TRIES #define INITIAL_MAX_WRITE_ONLY_EXCHANGE_TRIES 4 #define INITIAL_MAX_WRITE_READ_EXCHANGE_TRIES 10 #define INITIAL_MAX_MULTI_EXCHANGE_TRIES 8 // // *** Cache file names // #define DSA_CACHE_FILENAME "dsa" #define CAPABILITIES_CACHE_FILENAME "capabilities" #define DISPLAYS_CACHE_FILENAME "displays" // // *** Option Defaults // #ifdef ENABLE_USB #define DEFAULT_ENABLE_USB false #endif #define DEFAULT_ENABLE_UDF true #define DEFAULT_ENABLE_CACHED_CAPABILITIES true #define DEFAULT_ENABLE_CACHED_DISPLAYS false #define DEFAULT_ENABLE_DSA2 true #define DEFAULT_ENABLE_FLOCK true #define DEFAULT_SETVCP_VERIFY true #define DEFAULT_DDCUTIL_SYSLOG_LEVEL DDCA_SYSLOG_WARNING #define DEFAULT_LIBDDCUTIL_SYSLOG_LEVEL DDCA_SYSLOG_NOTICE #define DEFAULT_WATCH_MODE Watch_Mode_Dynamic // // Asynchronous Initialization // #define CHECK_ASYNC_NEVER 99 /** Parallelize bus checks if at least this number of checkable /dev/i2c devices exist */ #define DEFAULT_BUS_CHECK_ASYNC_THRESHOLD CHECK_ASYNC_NEVER /** Parallelize DDC communication checks if at least this number of /dev/i2c devices have an EDID */ // on workstation banner with 4 displays, async detect: 1.7 sec, non-async 3.4 sec #define DEFAULT_DDC_CHECK_ASYNC_THRESHOLD 3 // // Display detection // // Retry interval for retrying to open display #define DEFAULT_OPEN_MAX_WAIT_MILLISEC 1000 #define DEFAULT_OPEN_WAIT_INTERVAL_MILLISEC 100 // Retry interval and max tries when checking that a display handle // is still valid #define CHECK_OPEN_BUS_ALIVE_RETRY_MILLISEC 1000 #define CHECK_OPEN_BUS_ALIVE_MAX_TRIES 3 // During bus detection, retry interval and max tries for X37 detection #define DETECT_X37_MAX_TRIES 3 #define DETECT_X37_RETRY_MILLISEC 400 // // *** Watching for display changes // /** How frequently libddcutil watches for changes to connected displays */ #define DEFAULT_UDEV_WATCH_LOOP_MILLISEC 500 #define DEFAULT_POLL_WATCH_LOOP_MILLISEC 2000 #define DEFAULT_XEVENT_WATCH_LOOP_MILLISEC 100 // Once an event is received that possibly indicates a display change, // libddcutil repeatedly checks /sys/class/drm until the reported displays // stabilize /** Extra time to wait before first stabilization check */ #define DEFAULT_INITIAL_STABILIZATION_MILLISEC 0 // 500 /** Polling interval between stabilization checks */ #define DEFAULT_STABILIZATION_POLL_MILLISEC 100 // When checking that DDC communication has become enabled, // checks occur at increasing multiples of this value. #define WATCH_RETRY_THREAD_SLEEP_FACTOR_MILLISEC 500 // // *** Miscellaneous // // EDID in /sys can have stale data #define DEFAULT_TRY_GET_EDID_FROM_SYSFS true #define DEFAULT_FLOCK_POLL_MILLISEC 100 #define DEFAULT_FLOCK_MAX_WAIT_MILLISEC 3000 /** Maximum number of i2c buses this code supports */ #define I2C_BUS_MAX 64 /** Maximum number of values on getvcp or vcpinfo */ #define MAX_GETVCP_VALUES 50 /** Maximum number of values on setvcp command */ #define MAX_SETVCP_VALUES 50 /** Maximum command arguments */ // #define MAX_ARGS (MAX_SETVCP_VALUES*2) // causes CMDID_* undefined #define MAX_ARGS 100 // hack #endif /* PARMS_H_ */ ddcutil-2.2.0/src/base/per_thread_data.h0000644000175000001440000000501514754576332013621 /** \file per_thread_data.h * * Maintains per-thread settings and statistics. * * The dependencies between this file and thread_retry_data.c and thread_sleep.data * are not unidirectional. The functionality has been split into 3 files for clarity. */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PER_THREAD_DATA_H_ #define PER_THREAD_DATA_H_ #include #include #include #include #include "base/parms.h" #include "base/displays.h" extern GHashTable * per_thread_data_hash; // key is thread id, value is Per_Thread_Data* void init_per_thread_data(); // module initialization void terminate_per_thread_data(); // release all resources extern int ptd_lock_count; extern int ptd_unlock_count; extern int cross_thread_operation_blocked_count; typedef struct { char * function; int total_calls; uint64_t total_nanosec; } Per_Thread_Function_Stats; // key is function name, value is Per_Thread_Function_Stats * typedef GHashTable Function_Stats_Hash; typedef struct { bool initialized; pid_t thread_id; #ifdef REMOVED char * description; #endif Display_Handle * cur_dh; char * cur_func; uint64_t cur_start; Function_Stats_Hash * function_stats; // double sleep_multiplier; } Per_Thread_Data; bool ptd_cross_thread_operation_start(); void ptd_cross_thread_operation_end(); void ptd_cross_thread_operation_block(); void dbgrpt_per_thread_data_locks(int depth); Per_Thread_Data * ptd_get_per_thread_data(); #ifdef REMOVED void ptd_set_thread_description(const char * description); void ptd_append_thread_description(const char * addl_description); const char * ptd_get_thread_description_t(); #endif // Apply a function to all Per_Thread_Data records typedef void (*Ptd_Func)(Per_Thread_Data * data, void * arg); void ptd_apply_all(Ptd_Func func, void * arg); void ptd_apply_all_sorted(Ptd_Func func, void * arg); void dbgrpt_per_thread_data(Per_Thread_Data * data, int depth); void ptd_list_threads(int depth); // API function performance profiling extern bool ptd_api_profiling_enabled; void ptd_profile_function_start(const char * func); void ptd_profile_function_end(const char * func); void ptd_profile_report_all_threads(int depth); void ptd_profile_report_stats_summary(int depth); void ptd_profile_reset_all_stats(); #endif /* PER_THREAD_DATA_H_ */ ddcutil-2.2.0/src/base/sleep.h0000644000175000001440000000304714754576332011626 /** \file sleep.h * Basic Sleep Services * * Most of **ddcutil's** elapsed time is spent in sleeps mandated by the * DDC protocol. Basic sleep invocation is centralized here to perform sleep * tracing and and maintain sleep statistics. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BASE_SLEEP_H_ #define BASE_SLEEP_H_ #include // Perform sleep void sleep_millis(int milliseconds); void sleep_millis_with_trace( int milliseconds, const char * func, int lineno, const char * filename, const char * message); #define SLEEP_MILLIS_WITH_TRACE(_millis, _msg) \ sleep_millis_with_trace(_millis, __func__, __LINE__, __FILE__, _msg) // Sleep statistics typedef struct { uint64_t actual_sleep_nanos; int requested_sleep_milliseconds; int total_sleep_calls; } Sleep_Stats; void init_sleep_stats(); Sleep_Stats get_sleep_stats(); void report_sleep_stats(int depth); // Perform display watch related sleeps #define DW_SLEEP_MILLIS(_millis, _msg) \ do { \ dw_sleep_millis(DDCA_SYSLOG_NOTICE, __func__, __LINE__, __FILE__, _millis, _msg); \ } while(0) #define DW_SLEEP_MILLIS2(_syslog_level, _millis, _msg) \ do { \ dw_sleep_millis(_syslog_level, __func__, __LINE__, __FILE__, _millis, _msg); \ } while(0) void dw_sleep_millis(DDCA_Syslog_Level level, const char * func, int line, const char * file, uint millis, const char * msg); #endif /* BASE_SLEEP_H_ */ ddcutil-2.2.0/src/base/trace_control.h0000644000175000001440000000335014754576332013351 /** @file trace_control.h * * Manage whether tracing is performed */ // Copyright (C) 2023-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef TRACE_CONTROL_H_ #define TRACE_CONTROL_H_ #include #include "config.h" #include "public/ddcutil_types.h" #include "base/ddcutil_types_internal.h" extern DDCA_Trace_Group trace_levels; bool add_traced_function(const char * funcname); bool is_traced_function( const char * funcname); void dbgrpt_traced_function_table(int depth); bool add_traced_api_call(const char * funcname); bool is_traced_api_call( const char * funcname); bool add_traced_callstack_call(const char * funcname); bool is_traced_callstack_call( const char * funcname); void dbgrpt_traced_callstack_call_table(int depth); void add_traced_file(const char * filename); bool is_traced_file( const char * filename); DDCA_Trace_Group trace_class_name_to_value(const char * name); void set_trace_groups(DDCA_Trace_Group trace_flags); void add_trace_groups(DDCA_Trace_Group trace_flags); // char * get_active_trace_group_names(); // unimplemented void report_tracing(int depth); /** Checks if tracing is currently active for the globally defined TRACE_GROUP value, * current file and function. * * Wrappers call to **is_tracing()**, using the current **TRACE_GROUP** value, * filename, and function as implicit arguments. */ #define IS_TRACING() is_tracing(TRACE_GROUP, __FILE__, __func__) #define IS_TRACING_GROUP(grp) is_tracing((grp), __FILE__, __func__) #define IS_TRACING_BY_FUNC_OR_FILE() is_tracing(DDCA_TRC_NONE, __FILE__, __func__) #define IS_DBGTRC(debug_flag, group) \ ( (debug_flag) || is_tracing((group), __FILE__, __func__) ) #endif /* TRACE_CONTROL_H_ */ ddcutil-2.2.0/src/base/vcp_version.h0000644000175000001440000000461014754576332013050 /** @file vcp_version.h * * VCP (aka MCCS) version specification */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef VCP_VERSION_H_ #define VCP_VERSION_H_ /** \cond */ #include /** \endcond */ #include "public/ddcutil_types.h" #include "util/coredefs.h" extern const char * valid_vcp_versions; ///< for error msgs // Both DDCA_MCCS_Version_Spec and DDCA_MCCS_Version_Id exist for historical reasons. // DDCA_MCCS_Version_Spec is the form in which the version number is returned from a // GETVCP of feature xDF. This form is used throughout much of ddcutil. // DDCA_MCCS_Version_Id reflects the fact that there are a small number of versions // and simplifies program logic that varies among versions. As of 3/2022 it is only // used internally in app_vcpinfo.c. /** @name version_id * Ids for MCCS/VCP versions, reflecting the fact that the set of values * is small. */ ///@{ /** MCCS (VCP) Feature Version IDs */ typedef enum { MCCS_SPEC_VNONE = 0, /**< As response, version unknown */ MCCS_SPEC_V10 = 1, /**< MCCS v1.0 */ MCCS_SPEC_V20 = 2, /**< MCCS v2.0 */ MCCS_SPEC_V21 = 4, /**< MCCS v2.1 */ MCCS_SPEC_V30 = 8, /**< MCCS v3.0 */ MCCS_SPEC_V22 = 16, /**< MCCS v2.2 */ MCCS_SPEC_VANY = 255 /**< On queries, match any VCP version */ } MCCS_SPEC_Version_Id; #define MCCS_SPEC_VUNK MCCS_SPEC_VNONE /**< For use on responses, indicates version unknown */ ///@} bool vcp_version_le(DDCA_MCCS_Version_Spec val, DDCA_MCCS_Version_Spec max); bool vcp_version_lt(DDCA_MCCS_Version_Spec val, DDCA_MCCS_Version_Spec max); bool vcp_version_gt(DDCA_MCCS_Version_Spec val, DDCA_MCCS_Version_Spec min); bool vcp_version_eq(DDCA_MCCS_Version_Spec v1, DDCA_MCCS_Version_Spec v2); bool vcp_version_is_valid(DDCA_MCCS_Version_Spec vspec, bool allow_unknown); char * format_vspec(DDCA_MCCS_Version_Spec vspec); char * format_vspec_verbose(DDCA_MCCS_Version_Spec vspec); DDCA_MCCS_Version_Spec parse_vspec(char * s); #ifdef MCCS_VERSION_ID char * format_vcp_version_id(MCCS_SPEC_Version_Id version_id); char * vcp_version_id_name(MCCS_SPEC_Version_Id version_id); DDCA_MCCS_Version_Spec mccs_version_id_to_spec(MCCS_SPEC_Version_Id id); MCCS_SPEC_Version_Id mccs_version_spec_to_id(DDCA_MCCS_Version_Spec vspec); #endif #endif /* VCP_VERSION_H_ */ ddcutil-2.2.0/src/cmdline/0000775000175000001440000000000014754576332011124 5ddcutil-2.2.0/src/cmdline/Makefile.am0000644000175000001440000000045414441414365013067 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libcmdline.la libcmdline_la_SOURCES = \ cmd_parser_aux.c \ cmd_parser_goption.c \ parsed_cmd.c ddcutil-2.2.0/src/cmdline/Makefile.in0000664000175000001440000005036314754576155013123 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/cmdline ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libcmdline_la_LIBADD = am_libcmdline_la_OBJECTS = cmd_parser_aux.lo cmd_parser_goption.lo \ parsed_cmd.lo libcmdline_la_OBJECTS = $(am_libcmdline_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/cmd_parser_aux.Plo \ ./$(DEPDIR)/cmd_parser_goption.Plo ./$(DEPDIR)/parsed_cmd.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libcmdline_la_SOURCES) DIST_SOURCES = $(libcmdline_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libcmdline.la libcmdline_la_SOURCES = \ cmd_parser_aux.c \ cmd_parser_goption.c \ parsed_cmd.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/cmdline/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/cmdline/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libcmdline.la: $(libcmdline_la_OBJECTS) $(libcmdline_la_DEPENDENCIES) $(EXTRA_libcmdline_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libcmdline_la_OBJECTS) $(libcmdline_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cmd_parser_aux.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cmd_parser_goption.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parsed_cmd.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/cmd_parser_aux.Plo -rm -f ./$(DEPDIR)/cmd_parser_goption.Plo -rm -f ./$(DEPDIR)/parsed_cmd.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/cmd_parser_aux.Plo -rm -f ./$(DEPDIR)/cmd_parser_goption.Plo -rm -f ./$(DEPDIR)/parsed_cmd.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/cmdline/cmd_parser_aux.c0000644000175000001440000005752014754153540014203 /** \file cmd_parser_aux.c * * Functions and strings that are independent of the parser package used. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include /** \cond */ #include #include #include #include #include #include "util/string_util.h" /** \endcond */ #include "base/parms.h" #include "cmdline/cmd_parser_aux.h" // // Command Description data structure // static Cmd_Desc cmdinfo[] = { // cmd_id cmd_name minchars min_arg_ct max_arg_ct supported_options {CMDID_DETECT, "detect", 3, 0, 0, Option_None}, {CMDID_CAPABILITIES, "capabilities", 3, 0, 0, Option_Explicit_Display}, {CMDID_GETVCP, "getvcp", 3, 1, MAX_GETVCP_VALUES, Option_Explicit_Display}, {CMDID_SETVCP, "setvcp", 3, 2, MAX_SETVCP_VALUES*2,Option_Explicit_Display}, {CMDID_LISTVCP, "listvcp", 5, 0, 0, Option_None}, #ifdef INCLUDE_TESTCASES {CMDID_TESTCASE, "testcase", 3, 1, 1, Option_None}, {CMDID_LISTTESTS, "listtests", 5, 0, 0, Option_None}, #endif {CMDID_LOADVCP, "loadvcp", 3, 1, 1, Option_Explicit_Display}, {CMDID_DUMPVCP, "dumpvcp", 3, 0, 1, Option_Explicit_Display}, #ifdef ENABLE_ENVCMDS {CMDID_INTERROGATE, "interrogate", 3, 0, 0, Option_None}, {CMDID_ENVIRONMENT, "environment", 3, 0, 0, Option_None}, {CMDID_USBENV, "usbenvironment", 6, 0, 0, Option_None}, #endif {CMDID_VCPINFO, "vcpinfo", 5, 0, MAX_GETVCP_VALUES, Option_None}, // #ifdef WATCH_COMMAND {CMDID_READCHANGES, "watch", 3, 0, 0, Option_Explicit_Display}, //#endif {CMDID_CHKUSBMON, "chkusbmon", 3, 1, 1, Option_None}, {CMDID_PROBE, "probe", 5, 0, 0, Option_Explicit_Display}, {CMDID_SAVE_SETTINGS,"scs", 3, 0, 0, Option_Explicit_Display}, {CMDID_DISCARD_CACHE,"discard", 4, 1, 2, Option_None}, {CMDID_LIST_RTTI, "traceable-functions", 2, 0, 0, Option_None}, {CMDID_NOOP, "noop", 2, 0, 9, Option_None}, {CMDID_NOOP, "c0", 2, 0, 0, Option_None}, {CMDID_C1, "c1", 2, 0, 9, Option_None}, {CMDID_C2, "c2", 2, 0, 9, Option_None}, {CMDID_C3, "c3", 2, 0, 9, Option_None}, {CMDID_C4, "c4", 2, 0, 9, Option_None}, }; static int cmdct = sizeof(cmdinfo)/sizeof(Cmd_Desc); #ifndef NDEBUG /** Validates the Cmd_Desc data structure. * Called during parser initialization. */ void validate_cmdinfo() { int ndx = 0; for (; ndx < cmdct; ndx++) { assert( cmdinfo[ndx].max_arg_ct <= MAX_ARGS); } } #endif /** Reports the contents of the Cmd_Desc data structure. * For debugging. * * @param cmd_desc pointer to command table */ void show_cmd_desc(Cmd_Desc * cmd_desc) { printf("CmdDesc at %p\n", (void*)cmd_desc); printf(" cmd_id: 0x%04x\n", cmd_desc->cmd_id); printf(" cmd_name: %s\n", cmd_desc->cmd_name); printf(" minchars: %d\n", cmd_desc->minchars); printf(" min_arg_ct: %d\n", cmd_desc->min_arg_ct); printf(" max_arg_ct: %d\n", cmd_desc->max_arg_ct); } /** Looks for a command in the command table, allowing for valid abbreviations. * * @param cmd pointer to command specified by the user, in lower case * @return pointer to #Cmd_Desc struct for the command, NULL if not found */ Cmd_Desc * find_command(char * cmd) { Cmd_Desc * result = NULL; int ndx = 0; for (; ndx < cmdct; ndx++) { Cmd_Desc desc = cmdinfo[ndx]; if (is_abbrev(cmd, desc.cmd_name, desc.minchars)) { result = &cmdinfo[ndx]; } } return result; } /** Looks for a command in the command table by its command id. * @param cmdid id number of command * @return pointer to #Cmd_Desc struct for the command, NULL if not found */ Cmd_Desc * get_command(int cmdid) { bool debug = false; Cmd_Desc * result = NULL; int ndx = 0; for (; ndx < cmdct; ndx++) { Cmd_Desc desc = cmdinfo[ndx]; if (cmdid == desc.cmd_id) { result = &cmdinfo[ndx]; } } if (debug) { DBGMSG("cmdid=0x%04x, returning %p", cmdid, result); show_cmd_desc(result); } return result; } // End of command description data structure // // Parsers for specific argument types // bool all_digits(char * val, int ct) { bool debug = false; DBGMSF(debug, "ct-%d, val -> |%.*s|", ct, ct, val ); bool ok = true; int ndx; for (ndx = 0; ndx < ct; ndx++) { if ( !isdigit(*(val+ndx)) ) { ok = false; break; } } DBGMSF(debug, "Returning: %d ", ok ); return ok; } bool parse_dot_separated_arg(const char * val, int * piAdapterIndex, int * piDisplayIndex) { int rc = sscanf(val, "%d.%d", piAdapterIndex, piDisplayIndex); // DBGMSG("val=|%s| sscanf() returned %d ", val, rc ); bool ok = (rc == 2); return ok; } bool parse_colon_separated_vid_pid(const char * val, uint16_t * pv1, uint16_t * pv2) { Null_Terminated_String_Array parts = strsplit(val, ":"); bool ok = false; if (ntsa_length(parts) == 2 && strlen(parts[0]) == 4 && strlen(parts[1]) == 4) { ok = true; // DBGMSG("parts[0] = |%s|", parts[0]); // DBGMSG("parts[1] = |%s|", parts[1]); ok &= hhs4_to_uint16(parts[0], pv1); ok &= hhs4_to_uint16(parts[1], pv2); } ntsa_free(parts, true); // DBGMSG("Returning %s *pv1=0x%04x, *pv2=0x%04x", sbool(ok), *pv1, *pv2); return ok; } bool parse_colon_separated_arg(const char * val, int* pv1, int* pv2) { int rc = sscanf(val, "%d:%d", pv1, pv2); // DBGMSG("val=|%s| sscanf() returned %d ", val, rc ); bool ok = (rc == 2); return ok; } bool parse_int_arg(char * val, int * pIval) { int ct = sscanf(val, "%d", pIval); return (ct == 1); } // // Feature subset table and functions // typedef struct feature_subset_table_entry_s { VCP_Feature_Subset subset_id; Cmd_Id_Type valid_commands; int min_chars; char * subset_name; char * subset_desc; } Feature_Subset_Table_Entry; // Valid subset identifiers for commands that can take a subset id as an argument const Feature_Subset_Table_Entry subset_table[] = { // special handling {VCP_SUBSET_KNOWN, CMDID_GETVCP|CMDID_VCPINFO, 3, "KNOWN", "All features known to ddcutil that are valid for the display"}, {VCP_SUBSET_KNOWN, CMDID_GETVCP|CMDID_VCPINFO, 3, "ALL", "Same as KNOWN"}, {VCP_SUBSET_KNOWN, CMDID_GETVCP|CMDID_VCPINFO, 3, "MCCS", "Same as KNOWN"}, // {VCP_SUBSET_SUPPORTED, CMDID_GETVCP, 3, "SUPPORTED", "All known features that are valid for the display"}, {VCP_SUBSET_SCAN, CMDID_GETVCP, 3, "SCAN", "All feature codes 00..FF, except those known to be WO"}, {VCP_SUBSET_MFG, CMDID_GETVCP, 3, "MANUFACTURER", "Manufacturer specific codes"}, {VCP_SUBSET_MFG, CMDID_GETVCP, 3, "MFG", "Same as MANUFACTURER"}, {VCP_SUBSET_UDF, CMDID_GETVCP|CMDID_VCPINFO, 3, "UDF", "User defined features"}, {VCP_SUBSET_UDF, CMDID_GETVCP|CMDID_VCPINFO, 3, "USER", "User defined features"}, // ddcutil defined groups {VCP_SUBSET_PROFILE, CMDID_GETVCP|CMDID_VCPINFO, 3, "PROFILE", "Features for color profile management"}, {VCP_SUBSET_COLOR, CMDID_GETVCP|CMDID_VCPINFO, 3, "COLOR", "Color related features"}, {VCP_SUBSET_LUT, CMDID_GETVCP|CMDID_VCPINFO, 3, "LUT", "LUT related features"}, // by MCCS spec group {VCP_SUBSET_CRT, CMDID_GETVCP|CMDID_VCPINFO, 3, "CRT", "CRT related features"}, {VCP_SUBSET_AUDIO, CMDID_GETVCP|CMDID_VCPINFO, 3, "AUDIO", "Audio related features"}, {VCP_SUBSET_WINDOW, CMDID_GETVCP|CMDID_VCPINFO, 3, "WINDOW", "Window related features"}, {VCP_SUBSET_TV, CMDID_GETVCP|CMDID_VCPINFO, 2, "TV", "TV related features"}, {VCP_SUBSET_DPVL, CMDID_GETVCP|CMDID_VCPINFO, 3, "DPVL", "DPVL related features"}, {VCP_SUBSET_PRESET, CMDID_VCPINFO, 3, "PRESET", "Presets"}, // all WO // by feature type {VCP_SUBSET_TABLE, CMDID_GETVCP|CMDID_VCPINFO, 3, "TABLE", "Table type features"}, {VCP_SUBSET_SCONT, CMDID_GETVCP|CMDID_VCPINFO, 3, "SCONT", "Simple Continuous features"}, {VCP_SUBSET_CCONT, CMDID_GETVCP|CMDID_VCPINFO, 3, "CCONT", "Complex Continuous features"}, {VCP_SUBSET_CONT, CMDID_GETVCP|CMDID_VCPINFO, 3, "CONT", "All Continuous features"}, {VCP_SUBSET_SNC, CMDID_GETVCP|CMDID_VCPINFO, 3, "SNC", "Simple NC features"}, {VCP_SUBSET_XNC, CMDID_GETVCP|CMDID_VCPINFO, 3, "XNC", "Extended NC features"}, {VCP_SUBSET_CNC, CMDID_GETVCP|CMDID_VCPINFO, 3, "CNC", "Complex NC features"}, {VCP_SUBSET_NC_WO, CMDID_VCPINFO, 4, "NC_WO", "Write-only NC features"}, {VCP_SUBSET_NC_CONT, CMDID_GETVCP|CMDID_VCPINFO, 4, "NC_CONT", "NC features with continuous subrange"}, {VCP_SUBSET_NC, CMDID_GETVCP|CMDID_VCPINFO, 2, "NC", "All NC features"}, }; const int subset_table_ct = sizeof(subset_table)/sizeof(Feature_Subset_Table_Entry); #ifndef NDEBUG void validate_subset_table() { // quick and dirty check that tables are in sync // +3 for VCP_SUBSET_SINGLE_FEATURE, VCP_SUBSET_MULTI_FEATURE, VCP_SUBSET_NONE // -2 for triple VCP_SUBSET_KNOWN // -1 for double VCP_SUBSET_MFG // -1 for double VCP_SUBSET_DYNAMIC assert(subset_table_ct+(3-4) == vcp_subset_count); } #endif /** Assemble a help message listing valid feature subsets. * @return multi-line help string */ char * assemble_command_argument_help() { GString * buf = g_string_sized_new(1000); g_string_append(buf, "Command Arguments\n" " getvcp, vcpinfo:\n" " can be any of the following:\n" " - the hex feature code for a specific feature, with or without a leading 0x,\n" " e.g. 10 or 0x10\n"); for (int ndx = 0; ndx < subset_table_ct; ndx++) { g_string_append_printf(buf, " - %-10s - %s\n", subset_table[ndx].subset_name, subset_table[ndx].subset_desc); } g_string_append(buf, " Keywords can be abbreviated to the first 3 characters.\n" " Case is ignored. e.g. \"COL\", \"pro\"\n" "\n" " setvcp:\n" " : hexadecimal feature code, with or without a leading 0x,\n" " e.g. 10 or 0x10\n" " [+|-] optionally indicate a relative value change, must be surrounded by blanks\n" " : a decimal number in the range 0..255, or a single byte hex value,\n" " e.g. 0x80\n"); char * result = buf->str; g_string_free(buf, false); // DBGMSG("Returning: |%s|", result); return result; } /** Finds a subset identifier description. * Given a command */ VCP_Feature_Subset find_subset(char * name, int cmd_id) { assert(name && (cmd_id == CMDID_GETVCP || cmd_id == CMDID_VCPINFO)); VCP_Feature_Subset result = VCP_SUBSET_NONE; char * us = strdup_uc(name); int ndx = 0; for (;ndx < subset_table_ct; ndx++) { if ( is_abbrev(us, subset_table[ndx].subset_name, subset_table[ndx].min_chars) ) { if (cmd_id & subset_table[ndx].valid_commands) result = subset_table[ndx].subset_id; break; } } free(us); return result; } #ifdef OLD bool parse_feature_id_or_subset(char * val, int cmd_id, Feature_Set_Ref * fsref) { bool debug = false; bool ok = true; VCP_Feature_Subset subset_id = find_subset(val, cmd_id); if (subset_id != VCP_SUBSET_NONE) fsref->subset = subset_id; else { Byte feature_hexid = 0; // temp ok = any_one_byte_hex_string_to_byte_in_buf(val, &feature_hexid); if (ok) { fsref->subset = VCP_SUBSET_SINGLE_FEATURE; fsref->specific_feature = feature_hexid; bs256_insert(fsref->features, feature_hexid); // for future } } DBGMSF(debug, "Returning: %s", sbool(ok)); if (ok && debug) dbgrpt_feature_set_ref(fsref, 0); return ok; } bool parse_feature_ids(char ** vals, int vals_ct, int cmd_id, Feature_Set_Ref * fsref) { bool debug = false; DBGMSF(debug, "Starting. vals_ct=%d, cmd_id=%d, fsref=%p", vals_ct, cmd_id, fsref); bool ok = true; assert(cmd_id == CMDID_GETVCP || cmd_id == CMDID_VCPINFO); assert(vals_ct > 0); fsref->subset = VCP_SUBSET_NONE; for (int ndx = 0; ndx < vals_ct; ndx++) { Byte feature_hexid = 0; // temp ok = any_one_byte_hex_string_to_byte_in_buf(vals[ndx], &feature_hexid); DBGMSF(debug, "vals[ndx]=%s, ok=%s, feature_hexid=0x%02x", vals[ndx], sbool(ok), feature_hexid); if (ok) { fsref->features = bs256_insert(fsref->features, feature_hexid); } } if (ok) fsref->subset = VCP_SUBSET_MULTI_FEATURES; DBGMSF(debug, "Returning: %s", sbool(ok)); if (ok && debug) dbgrpt_feature_set_ref(fsref, 0); return ok; } #endif Feature_Set_Ref * parse_feature_ids_or_subset(int cmd_id, char **vals, int vals_ct) { bool debug = false; DBGMSF(debug, "cmd_id=%d, vals[0]=%s, vals_ct=%d", cmd_id, vals[0], vals_ct); Feature_Set_Ref * fsref = calloc(1, sizeof(Feature_Set_Ref)); bool ok = false; if (vals_ct <= 1) { char * val = (vals_ct > 0) ? vals[0] : "ALL"; VCP_Feature_Subset subset_id = find_subset(val, cmd_id); if (subset_id != VCP_SUBSET_NONE) { fsref->subset = subset_id; ok = true; } else { Byte feature_hexid = 0; // temp ok = any_one_byte_hex_string_to_byte_in_buf(val, &feature_hexid); if (ok) { fsref->subset = VCP_SUBSET_SINGLE_FEATURE; // fsref->specific_feature = feature_hexid; fsref->features = bs256_insert(fsref->features, feature_hexid); // for future } } } else { // ct > 1 // ok = parse_feature_ids(vals, vals_ct, cmd_id, fsref); assert(cmd_id == CMDID_GETVCP || cmd_id == CMDID_VCPINFO); fsref->subset = VCP_SUBSET_NONE; for (int ndx = 0; ndx < vals_ct; ndx++) { Byte feature_hexid = 0; // temp ok = any_one_byte_hex_string_to_byte_in_buf(vals[ndx], &feature_hexid); DBGMSF(debug, "vals[ndx]=%s, ok=%s, feature_hexid=0x%02x", vals[ndx], sbool(ok), feature_hexid); if (ok) { fsref->features = bs256_insert(fsref->features, feature_hexid); } } if (ok) fsref->subset = VCP_SUBSET_MULTI_FEATURES; } if (!ok) { free(fsref); fsref = NULL; } DBGMSF(debug, "Done. Returning: %p", (void*) fsref); if (ok && debug) dbgrpt_feature_set_ref(fsref, 1); return fsref; } /** Checks that the output level, after parsing, is appropriate for a command. * Writes a message to stdout if not. * * @param parsed_cmd pointer to a #Parsed_Cmd * @return true/false */ bool validate_output_level(Parsed_Cmd* parsed_cmd) { bool ok = true; Byte valid_output_levels; // once upon a time the switch statement really had multiple cases switch(parsed_cmd->cmd_id) { case (CMDID_PROBE): // don't want to deal with how to report errors, handle write-only features // of machine readable output triggered by --terse valid_output_levels = DDCA_OL_NORMAL | DDCA_OL_VERBOSE | DDCA_OL_VV; break; default: valid_output_levels = DDCA_OL_TERSE | DDCA_OL_NORMAL | DDCA_OL_VERBOSE | DDCA_OL_VV; } if (!(parsed_cmd->output_level & valid_output_levels)) { printf("Output level invalid for command %s: %s\n", get_command(parsed_cmd->cmd_id)->cmd_name, output_level_name(parsed_cmd->output_level) ); ok = false; } return ok; } // // Help message fragments // char * commands_list_help = "Commands:\n" " detect Detect monitors\n" " capabilities Query monitor capabilities string\n" // " info\n" // " listvcp\n" " vcpinfo (feature-code-or-group) Show VCP feature characteristics\n" " getvcp Report VCP feature value(s)\n" " setvcp [+|-] Set VCP feature value\n" " dumpvcp (filename) Write color profile related settings to file\n" " loadvcp Load profile related settings from file\n" " scs Store current settings in monitor's nonvolatile storage\n" #ifdef INCLUDE_TESTCASES " testcase \n" " listtests\n" #endif #ifdef ENABLE_ENVCMDS " environment Probe execution environment\n" #ifdef ENABLE_USB " usbenv Probe for USB connected monitors\n" #endif #endif " probe Probe monitor abilities\n" #ifdef ENABLE_ENVCMDS " interrogate Report everything possible\n" #endif #ifdef ENABLE_USB " chkusbmon Check if USB device is monitor (for UDEV)\n" #endif #ifdef DEPRECATED " watch Watch display for reported changes (under development)\n" #endif " discard (all|capabilities|dsa) cache(s) Delete cache files\n" " traceable-functions List traceable functions\n"; #ifdef OLD char * command_argument_help = "Command Arguments\n" " getvcp, vcpinfo:\n" " can be any of the following:\n" " - the hex feature code for a specific feature, with or without a leading 0x,\n" " e.g. 10 or 0x10\n" " - KNOWN - all feature codes known to ddcutil\n" " - ALL - like KNOWN, but implies --show-unsupported\n" " - SCAN - scan all feature codes 0x00..0xff\n" " - COLOR - all color related feature codes\n" " - PROFILE - color related codes for profile management\n" " - LUT - LUT related features\n" " - AUDIO - audio features\n" " - WINDOW - window operations (e.g. PIP)\n" " - TV - TV related settings\n" " - PRESET - MCCS codes classed as PRESET\n" " - MANUFACTURER - manufacturer specific codes\n" " - MFG - same as MANUFACTURER\n" " - TABLE - Table type features\n" " - SCONT - simple Continuous features\n" " - CCONT - complex Continuous features\n" " - CONT - all Continuous features\n" " - SNC - simple Non-Continuous features\n" " - CNC - complex Non-Continuous features, using multiple bytes\n" " - NC_WO - write/only Non-Continuous features\n" " - NC_CONT - features classed as NC having a continuous subrange\n" " - NC - all Non-Continuous features\n" " Keywords can be abbreviated to the first 3 characters.\n" " Case is ignored. e.g. \"COL\", \"pro\"\n" "\n" " setvcp:\n" " : hexadecimal feature code, with or without a leading 0x,\n" " e.g. 10 or 0x10\n" " [+|-] optionally indicate a relative value change, must be surrounded by blanks\n" " : a decimal number in the range 0..255, or a single byte hex value,\n" " e.g. 0x80\n" ; #endif char * monitor_selection_option_help = "Monitor Selection:\n" " The monitor to be communicated with can be specified using the following options:\n" " --display , where ranges from 1 to the number of\n" " displays detected\n" " --bus , /dev/"I2C" bus number\n" #ifdef ENABLE_USB " --usb ., for monitors communicating via USB\n" " --hiddev , for monitors communicationg via USB\n" #endif " --edid , where is a 256 hex character representation of the\n" " 128 byte first block of the EDID\n" " --mfg , where is the 3 character manufacturer id reported by the EDID\n" " --model , where is as reported by the EDID\n" " --sn , where is the string form of the serial number\n" " reported by the EDID\n" " Options --mfg, --model and --sn may be combined.\n" "\n" ; char * tracing_comma_separated_option_help = "Tracing:\n" " The argument to --trace is a comma separated list of trace classes, surrounded by \n" " quotation marks if necessary." " e.g. --trace all, --trace \"I2C,ADL\"\n" " Valid trace classes are: BASE, I2C, ADL, DDC, DDCIO, VCP, TOP, ENV, API, UDF, SLEEP, RETRY, ALL.\n" " Trace class names are not case sensitive.\n" " (Some trace classes are more useful than others.)\n" // "\n" ; char * tracing_multiple_call_option_help = "Trace by trace class:\n" " The argument to --trace is a trace class. Specify the --trace option multiple\n" " times to activate multiple trace classes, e.g. \"--trace "I2C" --trace ddc\"\n" " Valid trace classes are: BASE, I2C, ADL, DDC, DDCIO, VCP, TOP, ENV, API, UDF, SLEEP, RETRY, ALL.\n" " Trace class names are not case sensitive.\n" " (Some trace classes are more useful than others.)\n" // "\n" ; char * trcfunc_multiple_call_option_help = "Trace by function name:\n" " The argument to --trcfunc is a function name. Specify the --trcfunc option multiple\n" " times to trace multiple functions, e.g. \"--trcfunc func1 --trcfunc func2\"\n" ; char * trcfile_multiple_call_option_help = "Trace by file name:\n" " The argument to --trcfile is a simple file name. Specify the --trcfile option multiple\n" " times to trace multiple functions, e.g. \"--trcfile ddc_edid.c --trcfile ddc_output.c\"\n" ; char * stats_multiple_call_option_help = "Stats:\n" " The argument to --stats is a statistics class. Specify the --stats option multiple\n" " times to activate multiple statistics classes, e.g. \"--stats calls --stats errors\"\n" " Valid statistics classes are: TRY, TRIES, ERRS, ERRORS, CALLS, ELAPSED, ALL.\n" " Statistics class names are not case sensitive and can abbreviated to 3 characters.\n" " If no argument is specified, or ALL is specified, then all statistics classes are\n" " output.\n" ; char * maxtries_option_help = "Retries:\n" " The argument to --maxtries is a comma separated list of 3 values:\n" " maximum write-only exchange count\n" " maximum write-read exchange count\n" " maximum multi-part-read exchange count\n" " A value of \"0\" or \".\" leaves the default value unchanged\n" " e.g. --maxtries \".,.,15\" changes only the maximum multi-part-read exchange count" ; // // Initialization // #ifndef NDEBUG void init_cmd_parser_base() { validate_cmdinfo(); validate_subset_table(); } #endif ddcutil-2.2.0/src/cmdline/cmd_parser_goption.c0000644000175000001440000026542414754246527015101 /** @file cmd_parser_goption.c * * Parse the command line using the glib goption functions. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include "util/coredefs.h" #include "util/debug_util.h" #include "util/error_info.h" #include "util/string_util.h" #include "util/report_util.h" #include "base/build_info.h" #include "base/build_timestamp.h" #include "base/core.h" #include "base/displays.h" #include "base/parms.h" #include "base/trace_control.h" #include "cmdline/cmd_parser_aux.h" #include "cmdline/cmd_parser.h" #include "cmdline/parsed_cmd.h" // Variables used by callback functions static char * usbwork = NULL; static DDCA_Output_Level output_level = DDCA_OL_NORMAL; static DDCA_Stats_Type stats_work = DDCA_STATS_NONE; static Cache_Types discarded_caches_work = NO_CACHES; static bool verbose_stats = false; static bool internal_stats = false; static Bit_Set_32 ignored_hiddev_work = 0; // gcc claims not const??? EMPTY_BIT_SET_32; // Callback function for processing --terse, --verbose and synonyms static gboolean output_arg_func(const gchar* option_name, const gchar* value, gpointer data, GError** error) { bool debug = false; DBGMSF(debug, "option_name=|%s|, value|%s|, data=%p", option_name, value, data); bool ok = true; if ( streq(option_name, "-v") || streq(option_name, "--verbose") ) output_level = DDCA_OL_VERBOSE; else if ( streq(option_name, "-t") || streq(option_name, "--terse") || streq(option_name, "--brief") ) output_level = DDCA_OL_TERSE; else if ( streq(option_name, "--vv") || streq(option_name, "--very-verbose") ) output_level = DDCA_OL_VV; else { PROGRAM_LOGIC_ERROR("Unexpected option_name: %s", option_name); g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "PROGRAM LOGIC ERROR: Unexpected option_name: %s", option_name); ok = false; } return ok; } // Callback function for processing --stats, --vstats, --istats static gboolean stats_arg_func(const gchar* option_name, const gchar* value, gpointer data, GError** error) { bool debug = false; DBGMSF(debug,"option_name=|%s|, value|%s|, data=%p", option_name, value, data); if (streq(option_name, "--vstats")) verbose_stats = true; else if (streq(option_name, "--istats")) { verbose_stats = true; internal_stats = true; } bool ok = true; if (value) { char * v2 = strdup_uc(value); if ( streq(v2,"ALL") ) { stats_work |= DDCA_STATS_ALL; } else if (streq(v2,"TRY") || is_abbrev(v2, "TRIES",3)) { stats_work |= DDCA_STATS_TRIES; } else if ( is_abbrev(v2, "CALLS",3)) { stats_work |= DDCA_STATS_CALLS; } else if (streq(v2,"ERRS") || is_abbrev(v2, "ERRORS",3)) { stats_work |= DDCA_STATS_ERRORS; } else if ( is_abbrev(v2,"ELAPSED",3) || is_abbrev(v2, "TIME",3)) { stats_work |= DDCA_STATS_ELAPSED; } else if ( streq(v2,"API") ){ stats_work |= DDCA_STATS_API; } else ok = false; free(v2); } else { stats_work = DDCA_STATS_ALL; } if (!ok) { g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "invalid stats type: %s", value ); } return ok; } // Callback function for processing --discard-cache static gboolean discard_cache_arg_func( const gchar* option_name, const gchar* value, gpointer data, GError** error) { bool debug = false; DBGMSF(debug,"option_name=|%s|, value|%s|, data=%p", option_name, value, data); bool ok = true; if (value) { char * v2 = strdup_uc(value); if ( streq(v2,"ALL") ) { discarded_caches_work |= ALL_CACHES; } else if ( is_abbrev(v2, "CAPABILITIES",3)) { discarded_caches_work |= CAPABILITIES_CACHE; } else if (streq(v2,"DSA") || is_abbrev(v2, "SLEEP",3)) { discarded_caches_work |= DSA2_CACHE; } else ok = false; free(v2); } else { discarded_caches_work = ALL_CACHES; } if (!ok) { g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "invalid cache type: %s", value ); } return ok; } #ifdef ENABLE_USB static gboolean ignored_hiddev_arg_func(const gchar* option_name, const gchar* value, gpointer data, GError** error) { bool debug = false; DBGMSF(debug,"option_name=|%s|, value|%s|, data=%p", option_name, value, data); int ival; bool ok = str_to_int(value, &ival, 10); // DBGMSG("ival=%d", ival); if (!ok || ival < 0 || ival >= BIT_SET_32_MAX) { g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "Invalid hiddev bus number: %s", value); ok = false; } else ignored_hiddev_work = bs32_insert(ignored_hiddev_work, ival); // DBGMSF(debug, "Returning %s", sbool(ok)); return ok; } #endif // #define FUTURE #ifdef FUTURE gboolean debug_pre_parse_func( GOptionContext *context, GOptionGroup *group, gpointer data, GError **error) { DBGMSG("Executing"); return true; } gboolean debug_post_parse_func( GOptionContext *context, GOptionGroup *group, gpointer data, GError **error) { DBGMSG("Executing"); return true; } #endif static void emit_parser_error(GPtrArray* errmsgs, const char * func, const char * msg, ...) { bool debug = false; DBGF(debug, "errmsgs=%p, func=%s, msg=%s", errmsgs, func, msg); va_list(args); va_start(args, msg); char * buffer = g_strdup_vprintf(msg, args); va_end(args); // Hack to clean up msgs still having \n at end if (strlen(buffer) > 1 && buffer[strlen(buffer)-1] == '\n') buffer[strlen(buffer)-1] = '\0'; if (errmsgs) { DBGF(debug,"Adding error msg %s", buffer); g_ptr_array_add(errmsgs, g_strdup(buffer)); } else{ fprintf(stderr, "%s\n", buffer); } free(buffer); } #define EMIT_PARSER_ERROR(errmsgs, msg, ...) \ emit_parser_error(errmsgs, __func__, msg, ##__VA_ARGS__) static bool parse_maxtrywork(char * maxtrywork, Parsed_Cmd * parsed_cmd, GPtrArray* errmsgs) { bool debug = false; DBGMSF(debug, "retrywork, argument = |%s|", maxtrywork ); bool parsing_ok = true; Null_Terminated_String_Array pieces = strsplit(maxtrywork, ","); int ntsal = ntsa_length(pieces); DBGMSF(debug, "ntsal=%d", ntsal ); if (ntsa_length(pieces) != 3) { EMIT_PARSER_ERROR(errmsgs, "Option --maxtries requires 3 values"); parsing_ok = false; } else { int ndx = 0; char trimmed_piece[10]; for (; pieces[ndx] != NULL; ndx++) { char * token = strtrim_r(pieces[ndx], trimmed_piece, 10); if (strlen(token) > 0 && !streq(token,".")) { int ival; int ct = sscanf(token, "%ud", &ival); if (ct != 1) { EMIT_PARSER_ERROR(errmsgs, "Invalid --maxtries value: %s", token); parsing_ok = false; } else if (ival > MAX_MAX_TRIES) { EMIT_PARSER_ERROR(errmsgs, "--maxtries value %d exceeds %d", ival, MAX_MAX_TRIES); parsing_ok = false; } else if (ival < 0) { EMIT_PARSER_ERROR(errmsgs, "negative --maxtries value: %d", ival); parsing_ok = false; } else { parsed_cmd->max_tries[ndx] = ival; } } // split max multipart exchange into read and write // not here, do it in main // parsed_cmd->max_tries[3] = parsed_cmd->max_tries[2]; } assert(ndx == ntsal); } ntsa_free(pieces, /* free_strings */ true); DBGMSF(debug, "maxtries = %d,%d,%d", parsed_cmd->max_tries[0], parsed_cmd->max_tries[1], parsed_cmd->max_tries[2]); DBGMSF(debug, "returning %s", sbool(parsing_ok)); return parsing_ok; } static bool parse_display_identifier( Parsed_Cmd * parsed_cmd, GPtrArray * errmsgs, int dispwork, int buswork, int hidwork, char * usbwork, char * edidwork, char * mfg_id_work, char * modelwork, char * snwork) { bool parsing_ok = true; int explicit_display_spec_ct = 0; if (usbwork) { #ifdef ENABLE_USB bool debug = false; DBGMSF(debug, "usbwork = |%s|", usbwork); int busnum; int devicenum; bool arg_ok = parse_dot_separated_arg(usbwork, &busnum, &devicenum); if (!arg_ok) arg_ok = parse_colon_separated_arg(usbwork, &busnum, &devicenum); if (!arg_ok) { EMIT_PARSER_ERROR(errmsgs, "Invalid USB argument: %s", usbwork ); parsing_ok = false; } else { // avoid memory leak in case parsed_cmd->pdid set in more than 1 way if (parsed_cmd->pdid) { free_display_identifier(parsed_cmd->pdid); } parsed_cmd->pdid = create_usb_display_identifier(busnum, devicenum); } explicit_display_spec_ct++; #else EMIT_PARSER_ERROR(errmsgs, "ddcutil not built with support for USB connected monitors. --usb option invalid."); parsing_ok = false; #endif } if (buswork >= 0) { // avoid memory leak in case parsed_cmd->pdid set in more than 1 way if (parsed_cmd->pdid) free_display_identifier(parsed_cmd->pdid); parsed_cmd->pdid = create_busno_display_identifier(buswork); explicit_display_spec_ct++; } if (hidwork >= 0) { #ifdef ENABLE_USB // avoid memory leak in case parsed_cmd->pdid set in more than 1 way if (parsed_cmd->pdid) free_display_identifier(parsed_cmd->pdid); parsed_cmd->pdid = create_usb_hiddev_display_identifier(hidwork); explicit_display_spec_ct++; #else EMIT_PARSER_ERROR(errmsgs, "ddcutil not built with support for USB connected monitors. --hid option invalid."); parsing_ok = false; #endif } if (dispwork >= 0) { // avoid memory leak in case parsed_cmd->pdid set in more than 1 way if (parsed_cmd->pdid) free_display_identifier(parsed_cmd->pdid); parsed_cmd->pdid = create_dispno_display_identifier(dispwork); explicit_display_spec_ct++; } if (edidwork) { if (strlen(edidwork) != 256) { EMIT_PARSER_ERROR(errmsgs, "EDID hex string not 256 characters"); parsing_ok = false; } else { Byte * pba = NULL; int bytect = hhs_to_byte_array(edidwork, &pba); if (bytect < 0 || bytect != 128) { EMIT_PARSER_ERROR(errmsgs, "Invalid EDID hex string"); parsing_ok = false; } else { // avoid memory leak in case parsed_cmd->pdid set in more than 1 way if (parsed_cmd->pdid) free_display_identifier(parsed_cmd->pdid); parsed_cmd->pdid = create_edid_display_identifier(pba); // new way } if (pba) free(pba); } explicit_display_spec_ct++; } if (mfg_id_work || modelwork || snwork) { // avoid memory leak in case parsed_cmd->pdid set in more than 1 way if (parsed_cmd->pdid) free_display_identifier(parsed_cmd->pdid); parsed_cmd->pdid = create_mfg_model_sn_display_identifier( mfg_id_work, modelwork, snwork); explicit_display_spec_ct++; } if (explicit_display_spec_ct > 1) { EMIT_PARSER_ERROR(errmsgs, "Monitor specified in more than one way"); free_display_identifier(parsed_cmd->pdid); parsed_cmd->pdid = NULL; parsing_ok = false; } return parsing_ok; } static bool parse_mccswork(char * mccswork, Parsed_Cmd * parsed_cmd, GPtrArray * errmsgs) { bool debug = false; bool arg_ok = false; if (mccswork) { DBGMSF(debug, "mccswork = |%s|", mccswork); DDCA_MCCS_Version_Spec vspec = parse_vspec(mccswork); if (!vcp_version_eq(vspec, DDCA_VSPEC_UNKNOWN)) { arg_ok = vcp_version_is_valid(vspec, false); } if (!arg_ok) { EMIT_PARSER_ERROR(errmsgs, "Invalid MCCS spec: %s", mccswork ); EMIT_PARSER_ERROR(errmsgs, "Valid MCCS versions are: %s", valid_vcp_versions); } else { parsed_cmd->mccs_vspec = vspec; // parsed_cmd->mccs_version_id = mccs_version_spec_to_id(vspec); } } return arg_ok; } static bool parse_int_work(char * sval, int * result_loc, GPtrArray * errmsgs) { bool debug = false; bool ok = true; DBGMSF(debug, "sval: %s", sval); if (sval) { ok = str_to_int(sval, result_loc, 0); if (!ok) EMIT_PARSER_ERROR(errmsgs, "Invalid integer or hex number: %s", sval); } DBGMSF(debug, "Done. Returning: %s. result_loc -> %d (0x%08x)", sbool(ok), *result_loc, *result_loc); return ok; } #ifdef UNUSED static bool parse_positive_int(int ival, int * result_loc, GPtrArray * errmsgs) { bool debug = false; bool ok = true; DBGMSF(debug, "ival: %d", ival); ok = (ival > 0); if (ok) *result_loc = ival; else EMIT_PARSER_ERROR(errmsgs, "Must be a positive number: %d", ival); DBGMSF(debug, "Done. Returning: %d. result_loc -> %d", sbool(ok), *result_loc); return ok; } #endif static bool parse_sleep_multiplier( const char* sval, float * result_loc, GPtrArray* errmsgs) { bool debug = false; bool arg_ok = false; if (sval) { DBGMSF(debug, "sval = |%s|", sval); float multiplier = 0.0f; arg_ok = str_to_float(sval, &multiplier); if (arg_ok) { if (multiplier < 0.0f || multiplier >= 100.0) arg_ok = false; } if (arg_ok) { *result_loc = multiplier; } else { EMIT_PARSER_ERROR(errmsgs, "Invalid sleep-multiplier: %s", sval ); } } return arg_ok; } static bool parse_watch_mode( const char * sval, Parsed_Cmd* parsed_cmd, GPtrArray* errmsgs) { bool debug = false; DBGMSF(debug,"sval=|%s|", sval); bool ok = true; if (sval) { char * v2 = strdup_uc(sval); if ( is_abbrev(v2, "POLL", 3)) parsed_cmd->watch_mode = Watch_Mode_Poll; else if (is_abbrev(v2, "XEVENT", 3)) parsed_cmd->watch_mode = Watch_Mode_Xevent; // else if (is_abbrev(v2, "UDEV", 3)) // parsed_cmd->watch_mode = Watch_Mode_Udev; else if (is_abbrev(v2, "DYNAMIC", 3)) parsed_cmd->watch_mode = Watch_Mode_Dynamic; else { EMIT_PARSER_ERROR(errmsgs, "Invalid watch-mode: %s", sval); ok = false; } free(v2); } else { EMIT_PARSER_ERROR(errmsgs, "--watch-mode argument missing"); ok = false; } return ok; } #ifdef OLD static bool parse_sleep_multiplier0( const char* sleep_multiplier_work, Parsed_Cmd* parsed_cmd, GPtrArray* errmsgs) { bool debug = false; bool arg_ok = false; if (sleep_multiplier_work) { DBGMSF(debug, "sleep_multiplier_work = |%s|", sleep_multiplier_work); float multiplier = 0.0f; arg_ok = str_to_float(sleep_multiplier_work, &multiplier); if (arg_ok) { if (multiplier < 0.0f || multiplier >= 100.0) arg_ok = false; // if (parsed_cmd->parser_mode == MODE_DDCUTIL && multiplier == 0.0f) // arg_ok = false; } if (!arg_ok) { EMIT_PARSER_ERROR(errmsgs, "Invalid sleep-multiplier: %s", sleep_multiplier_work ); } else { parsed_cmd->sleep_multiplier = multiplier; parsed_cmd->flags |= CMD_FLAG_EXPLICIT_SLEEP_MULTIPLIER; } } return arg_ok; } #endif static void unhide_options(GOptionEntry * options) { GOptionEntry * cur = options; for (;cur->long_name; cur++) { // DBGMSG("cur=%p, cur->long_name=%p - %s", cur, cur->long_name, cur->long_name); cur->flags = cur->flags & ~G_OPTION_FLAG_HIDDEN; } } static bool parse_trace_classes(gchar** trace_classes, Parsed_Cmd* parsed_cmd, GPtrArray* errmsgs) { #ifdef COMMA_DELIMITED_TRACE if (tracework) { bool saved_debug = debug; debug = false; if (debug) DBGMSG("tracework, argument = |%s|", tracework ); strupper(tracework); DDCA_Trace_Group traceClasses = 0x00; Null_Terminated_String_Array pieces = strsplit(tracework, ','); int ndx = 0; for (; pieces[ndx] != NULL; ndx++) { char * token = pieces[ndx]; // TODO: deal with leading or trailing whitespace DBGMSG("token=|%s|", token); if (streq(token, "ALL") || streq(token, "*")) traceClasses = 0xff; else { // DBGMSG("token: |%s|", token); DDCA_Trace_Group tg = trace_class_name_to_value(token); // DBGMSG("tg=0x%02x", tg); if (tg) { traceClasses |= tg; } else { fprintf(stderr, "Invalid trace group: %s\n", token); parsing_ok = false; } } } DBGMSG("ndx=%d", ndx); DBGMSG("ntsal=%d", ntsa_length(pieces) ); assert(ndx == ntsa_length(pieces)); ntsa_free(pieces); DBGMSG("traceClasses = 0x%02x", traceClasses); parsed_cmd->traced_groups = traceClasses; debug = saved_debug; } #endif bool parsing_ok = true; if (trace_classes) { DDCA_Trace_Group traceClasses = 0x00; int ndx = 0; for (;trace_classes[ndx] != NULL; ndx++) { char * token = trace_classes[ndx]; strupper(token); // DBGMSG("token=|%s|", token); if (streq(token, "ALL") || streq(token, "*")) { traceClasses = DDCA_TRC_ALL; // 0xff } else { // DBGMSG("token: |%s|", token); DDCA_Trace_Group tg = trace_class_name_to_value(token); // DBGMSG("tg=0x%02x", tg); if (tg) { traceClasses |= tg; } else { EMIT_PARSER_ERROR(errmsgs, "Invalid trace group: %s\n", token); parsing_ok = false; } } } // DBGMSG("traceClasses = 0x%02x", traceClasses); parsed_cmd->traced_groups = traceClasses; } return parsing_ok; } bool parse_syslog_level( const char * sval, DDCA_Syslog_Level * result_loc, GPtrArray * errmsgs) { assert(sval); assert(result_loc); bool debug = false; bool parsing_ok = true; DBGF(debug, "sval=|%s|", sval); *result_loc = syslog_level_name_to_value(sval); if (*result_loc == DDCA_SYSLOG_NOT_SET) { parsing_ok = false; EMIT_PARSER_ERROR(errmsgs, "Invalid syslog level: %s", sval ); EMIT_PARSER_ERROR(errmsgs, "Valid values are %s", valid_syslog_levels_string); } if (debug) printf("(%s) Returning %s, *result_loc = %d\n", __func__, sbool(parsing_ok), *result_loc); return parsing_ok; } static bool parse_setvcp_args(Parsed_Cmd * parsed_cmd, GPtrArray* errmsgs) { bool parsing_ok = true; // for (int argpos = 0; argpos < parsed_cmd->argct; argpos+=2) { int argpos = 0; while(argpos < parsed_cmd->argct) { Parsed_Setvcp_Args psv; bool feature_code_ok = any_one_byte_hex_string_to_byte_in_buf( parsed_cmd->args[argpos], &psv.feature_code); if (!feature_code_ok) { EMIT_PARSER_ERROR(errmsgs, "Invalid feature code: %s", parsed_cmd->args[argpos]); parsing_ok = false; break; } argpos++; if (argpos >= parsed_cmd->argct) { EMIT_PARSER_ERROR(errmsgs, "Missing feature value"); parsing_ok = false; break; } psv.feature_value_type = VALUE_TYPE_ABSOLUTE; if ( streq(parsed_cmd->args[argpos], "+") || streq(parsed_cmd->args[argpos], "-") ) { if ( streq(parsed_cmd->args[argpos], "+") ) psv.feature_value_type = VALUE_TYPE_RELATIVE_PLUS; else psv.feature_value_type = VALUE_TYPE_RELATIVE_MINUS; argpos++; if (argpos >= parsed_cmd->argct) { EMIT_PARSER_ERROR(errmsgs, "Missing feature value"); parsing_ok = false; break; } } psv.feature_value = g_strdup(parsed_cmd->args[argpos]); g_array_append_val(parsed_cmd->setvcp_values, psv); argpos++; } return parsing_ok; } static bool parse_discard_args(Parsed_Cmd * parsed_cmd, GPtrArray* errmsgs) { bool parsing_ok = true; assert(parsed_cmd->argct == 1 || parsed_cmd->argct == 2); strupper(parsed_cmd->args[0]); if (parsed_cmd->argct == 2) strupper(parsed_cmd->args[1]); if (parsed_cmd->argct == 1) { if ( is_abbrev(parsed_cmd->args[0], "CACHES", 5) ) parsed_cmd->discarded_cache_types = ALL_CACHES; else parsing_ok = false; } else { if ( !is_abbrev(parsed_cmd->args[1], "CACHES", 5) ) { parsing_ok = false; } else { if (is_abbrev(parsed_cmd->args[0], "CAPABILITIES", 3) ) parsed_cmd->discarded_cache_types = CAPABILITIES_CACHE; #ifdef REMOVED else if (is_abbrev(parsed_cmd->args[0], "DISPLAYS", 3) ) parsed_cmd->cache_types = DISPLAYS_CACHE; #endif else if (is_abbrev(parsed_cmd->args[0], "DSA", 3) ) parsed_cmd->discarded_cache_types = DSA2_CACHE; else if (is_abbrev(parsed_cmd->args[0], "ALL", 3) ) parsed_cmd->discarded_cache_types = ALL_CACHES; else parsing_ok = false; } } if (!parsing_ok) { char * s = g_strdup_printf("%s %s", parsed_cmd->args[0], (parsed_cmd->argct > 1) ? parsed_cmd->args[1] : ""); EMIT_PARSER_ERROR(errmsgs, "Unrecognized DISCARD argument(s): %s", s); g_free(s); } return parsing_ok; } static void report_ddcutil_build_info() { printf("Built %s at %s\n", BUILD_DATE, BUILD_TIME); #ifdef ENABLE_USB printf("Built with support for displays using USB for MCCS communication.\n"); #else printf("Built without support for displays using USB for MCCS communication.\n"); #endif #ifdef ENABLE_FAILSIM printf("Built with function failure simulation.\n"); #else printf("Built without function failure simulation.\n"); #endif #ifdef USE_LIBDRM printf("Built with libdrm services.\n"); #else printf("Built without libdrm services.\n"); #endif puts(""); } #ifdef UNUSED Preparsed_Cmd * preparse_command( int argc, char * argv[], Parser_Mode parser_mode, GPtrArray * errmsgs) { bool debug = false; char * s = getenv("DDCUTIL_DEBUG_PARSE"); if (s && strlen(s) > 0) debug = true; DBGMSF(debug, "Starting. parser_mode = %d", parser_mode ); assert(parser_mode == MODE_DDCUTIL); if (debug) { DBGMSG("argc=%d", argc); int ndx = 0; for (; ndx < argc; ndx++) { DBGMSG("argv[%d] = |%s|", ndx, argv[ndx]); } } Preparsed_Cmd * ppc = calloc(1, sizeof(Preparsed_Cmd)); ppc->severity = DDCA_SYSLOG_NOT_SET; ppc->verbose = false; ppc->noconfig = false; char * syslog_work = NULL; char ** ignored = NULL; GOptionEntry preparser_options[] = { {"verbose", 'v', 0, G_OPTION_ARG_NONE, &ppc->verbose, NULL, NULL}, {"noconfig", '\0', 0, G_OPTION_ARG_NONE, &ppc->noconfig, NULL, NULL}, {"syslog", '\0', 0, G_OPTION_ARG_STRING, &syslog_work, NULL, NULL}, {G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_STRING_ARRAY, &ignored, NULL, NULL}, {NULL}, }; GOptionGroup * all_options = g_option_group_new( "group name", "group description", "help description", NULL, NULL); g_option_group_add_entries(all_options, preparser_options); GError* error = NULL; GOptionContext* context = g_option_context_new("- Preparser"); g_option_context_set_main_group(context, all_options); g_option_context_set_help_enabled(context, false); // Pass a mangleable copy of argv to g_option_context_parse_strv(). Null_Terminated_String_Array temp_argv = ntsa_copy(argv, true); bool parsing_ok = g_option_context_parse_strv(context, &temp_argv, &error); if (ignored) { ntsa_show(ignored); ntsa_free(ignored, true); } if (!parsing_ok) { char * mode_name = (parser_mode == MODE_DDCUTIL) ? "ddcutil" : "libddcutil"; if (error) { // EMIT_PARSER_ERROR(errmsgs, "%s option parsing failed: %s", mode_name, error->message); emit_parser_error(errmsgs, __func__, "%s", error->message); } else emit_parser_error(errmsgs, __func__, "%s option parsing failed", mode_name); } ntsa_free(temp_argv, true); if (syslog_work) { DDCA_Syslog_Level level; bool this_ok = parse_syslog_level(syslog_work, &level, errmsgs); // printf("(%s) this_ok = %s\n", __func__, sbool(this_ok)); if (this_ok) ppc->severity = level; else parsing_ok = false; } if (!parsing_ok) { free(ppc); ppc = NULL; } return ppc; } #endif /* Primary parsing function * * \param argc number of command line arguments * \param argv array of pointers to command line arguments * \param parser_mode indicate whether called for ddcutil or libddcutil * \param errmsgs if non-null collect error messages, do not write to terminal * \return pointer to newly allocated Parsed_Cmd struct if parsing successful * NULL if execution should be terminated */ Parsed_Cmd * parse_command( int argc, char * argv[], Parser_Mode parser_mode, GPtrArray * errmsgs) { bool debug = false; char * s = getenv("DDCUTIL_DEBUG_PARSE"); if (s && strlen(s) > 0) debug = true; DBGF(debug, "Starting. parser_mode = %d", parser_mode ); #ifndef NDEBUG init_cmd_parser_base(); // assertions #endif if (debug) { DBG("argc=%d", argc); int ndx = 0; for (; ndx < argc; ndx++) { DBGMSG("argv[%d] = |%s|", ndx, argv[ndx]); } } Parsed_Cmd * parsed_cmd = new_parsed_cmd(); parsed_cmd->parser_mode = parser_mode; // parsed_cmd->pdid = create_dispno_display_identifier(1); // default monitor // DBGMSG("After new_parsed_cmd(), parsed_cmd->output_level_name = %s", output_level_name(parsed_cmd->output_level)); gchar * original_command = g_strjoinv(" ",argv); DBGF(debug, "original command: %s", original_command); parsed_cmd->raw_command = original_command; // gboolean stats_flag = false; gboolean ddc_flag = false; gboolean force_flag = false; gboolean allow_unrecognized_feature_flag = false; gboolean force_slave_flag = false; gboolean show_unsupported_flag = false; gboolean version_flag = false; gboolean timestamp_trace_flag = false; gboolean wall_timestamp_trace_flag = false; gboolean thread_id_trace_flag = false; gboolean process_id_trace_flag = false; const char * verify_expl = (DEFAULT_SETVCP_VERIFY) ? "Verify value set by setvcp (default)" : "Verify value set by setvcp"; const char * noverify_expl = (DEFAULT_SETVCP_VERIFY) ? "Do not verify value by setvcp" : "Do not verify value set by setvcp (default)"; gboolean verify_flag = DEFAULT_SETVCP_VERIFY; gboolean noverify_flag = false; gboolean async_flag = false; // gboolean async_check_i2c_flag = true; gboolean report_freed_excp_flag = false; gboolean notable_flag = true; gboolean rw_only_flag = false; gboolean ro_only_flag = false; gboolean wo_only_flag = false; gboolean enable_udf_flag = DEFAULT_ENABLE_UDF; const char * enable_udf_expl = (enable_udf_flag) ? "Enable User Defined Features (default)" : "Enable User Defined Features"; const char * disable_udf_expl = (enable_udf_flag) ? "Disable User Defined Features" : "Disable User Defined Features (default)"; #ifdef ENABLE_USB gboolean enable_usb_flag = DEFAULT_ENABLE_USB; const char * enable_usb_expl = (enable_usb_flag) ? "Detect USB devices (default)" : "Detect USB devices"; const char * disable_usb_expl = (enable_usb_flag) ? "Ignore USB devices" : "Ignore USB devices (default)"; gchar** ignored_vid_pid = NULL; #endif gboolean timeout_i2c_io_flag = false; gboolean reduce_sleeps_specified = false; gboolean deferred_sleep_flag = false; gboolean show_settings_flag = false; gboolean i2c_io_fileio_flag = false; gboolean i2c_io_ioctl_flag = false; gboolean debug_parse_flag = false; gboolean parse_only_flag = false; gboolean x52_no_fifo_flag = false; gboolean enable_dsa2_flag = DEFAULT_ENABLE_DSA2; gboolean traced_function_stack_flag = false; gboolean traced_function_stack_errors_fatal_flag = false; // int i2c_bus_check_async_min = DEFAULT_I2C_BUS_CHECK_ASYNC_MIN; // int ddc_check_async_min = DEFAULT_DDC_CHECK_ASYNC_MIN; char i2c_bus_check_async_expl[80]; g_snprintf(i2c_bus_check_async_expl, 80, "Threshold for parallel examination of I2C buses (Experimental). Default=%d.", DEFAULT_BUS_CHECK_ASYNC_THRESHOLD); char ddc_check_async_expl[80]; g_snprintf(ddc_check_async_expl, 80, "Threshold for parallel examination of possible DDC devices. Default=%d.", DEFAULT_DDC_CHECK_ASYNC_THRESHOLD); const char * enable_dsa2_expl = (enable_dsa2_flag) ? "Enable dynamic sleep algorithm (default)" : "Enable dynamic sleep algorithm"; const char * disable_dsa2_expl = (enable_dsa2_flag) ? "Disable dynamic sleep algorithm" : "Disable dynamic sleep algorithm (default)"; gboolean enable_cc_flag = DEFAULT_ENABLE_CACHED_CAPABILITIES; const char * enable_cc_expl = (enable_cc_flag) ? "Enable cached capabilities (default)" : "Enable cached capabilities"; const char * disable_cc_expl = (enable_cc_flag) ? "Disable cached capabilities" : "Disable cached capabilities (default)"; // #ifdef REMOVED gboolean enable_cd_flag = DEFAULT_ENABLE_CACHED_DISPLAYS; const char * enable_cd_expl = (enable_cd_flag) ? "Enable cached displays (default)" : "Enable cached displays"; const char * disable_cd_expl = (enable_cd_flag) ? "Disable cached displays" : "Disable cached displays (default)"; // #endif gboolean enable_flock_flag = DEFAULT_ENABLE_FLOCK; const char * enable_flock_expl = (enable_flock_flag) ? "Enable cross-instance locking (default)" : "Enable cross-instance locking"; const char * disable_flock_expl = (enable_flock_flag) ? "Disable cross-instance locking" : "Disable cross-instance locking (default)"; gboolean quick_flag = false; gboolean mock_data_flag = false; gboolean profile_api_flag = false; gboolean null_msg_for_unsupported_flag = false; gboolean enable_heuristic_unsupported_flag = true; char * mfg_id_work = NULL; char * modelwork = NULL; char * snwork = NULL; char * edidwork = NULL; char * mccswork = NULL; // MCCS version // // char * tracework = NULL; char** cmd_and_args = NULL; gchar** trace_classes = NULL; DDCA_Syslog_Level syslog_level = (parser_mode == MODE_DDCUTIL) ? DEFAULT_DDCUTIL_SYSLOG_LEVEL : DEFAULT_LIBDDCUTIL_SYSLOG_LEVEL; char * syslog_work = NULL; gint buswork = -1; gint hidwork = -1; gint dispwork = -1; char * maxtrywork = NULL; // char * trace_destination = NULL; gboolean trace_to_syslog_only_flag = false; gboolean stats_to_syslog_only_flag = false; gint edid_read_size_work = -1; gboolean disable_api_flag = false; gboolean discard_cached_capabilities_flag = false; gboolean discard_dsa_cache_flag = false; gboolean try_get_edid_from_sysfs = DEFAULT_TRY_GET_EDID_FROM_SYSFS; char * enable_tgefs_expl = NULL; char * disable_tgefs_expl = NULL; if (DEFAULT_TRY_GET_EDID_FROM_SYSFS) { enable_tgefs_expl = "get EDID from /sys when possible (default)"; disable_tgefs_expl = "do not try to get EDID from /sys"; } else { enable_tgefs_expl = "get EDID from /sys when possible"; disable_tgefs_expl = "do not try to get EDID from /sys (default)"; } DDC_Watch_Mode default_watch_mode = DEFAULT_WATCH_MODE; char * default_watch_mode_keyword; switch(default_watch_mode) { case Watch_Mode_Dynamic: default_watch_mode_keyword = "DYNAMIC"; break; case Watch_Mode_Xevent: default_watch_mode_keyword = "XEVENT"; break; case Watch_Mode_Poll: default_watch_mode_keyword = "POLL"; break; case Watch_Mode_Udev: default_watch_mode_keyword = "UDEV"; break; } char watch_mode_expl[80]; g_snprintf(watch_mode_expl, 80, "DYNAMIC|XEVENT|POLL, default: %s", default_watch_mode_keyword); gboolean enable_watch_displays = true; gint xevent_watch_loop_millis_work = DEFAULT_XEVENT_WATCH_LOOP_MILLISEC; gint poll_watch_loop_millis_work = DEFAULT_POLL_WATCH_LOOP_MILLISEC; gboolean f1_flag = false; gboolean f2_flag = false; gboolean f3_flag = false; gboolean f4_flag = false; gboolean f5_flag = false; gboolean f6_flag = false; gboolean f7_flag = false; gboolean f8_flag = false; gboolean f9_flag = false; gboolean f10_flag = false; gboolean f11_flag = false; gboolean f12_flag = false; gboolean f13_flag = false; gboolean f14_flag = false; gboolean f15_flag = false; gboolean f16_flag = false; gboolean f17_flag = false; gboolean f18_flag = false; gboolean f19_flag = false; gboolean f20_flag = false; gboolean f21_flag = false; gboolean f22_flag = false; gboolean f23_flag = false; gboolean f24_flag = false; gboolean f25_flag = false; gboolean f26_flag = false; gboolean f27_flag = false; gboolean f28_flag = false; gboolean f29_flag = false; gboolean f30_flag = false; gboolean f31_flag = false; gboolean f32_flag = false; char * i1_work = NULL; char * i2_work = NULL; char * i3_work = NULL; char * i4_work = NULL; char * i5_work = NULL; char * i6_work = NULL; char * i7_work = NULL; char * i8_work = NULL; char * i9_work = NULL; char * i10_work = NULL; char * i11_work = NULL; char * i12_work = NULL; char * i13_work = NULL; char * i14_work = NULL; char * i15_work = NULL; char * i16_work = NULL; char * fl1_work = NULL; char * fl2_work = NULL; char * failsim_fn_work = NULL; // gboolean enable_failsim_flag = false; char * sleep_multiplier_work = NULL; char * min_dynamic_sleep_work = NULL; char * i2c_source_addr_work = NULL; char * watch_mode_work = NULL; gboolean skip_ddc_checks_flag = false; gboolean hidden_help_flag = false; gboolean disable_config_flag = false; GOptionEntry preparser_options[] = { {"hh", '\0', 0, G_OPTION_ARG_NONE, &hidden_help_flag, "Show hidden options", NULL}, {NULL}, }; #ifdef OLD GOptionEntry libddcutil_only_options[] = { {"disable-api", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &disable_api, "Completely disable API", NULL }, {NULL}, }; #endif GOptionEntry initial_options[] = { // Output control {"verbose", 'v', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, output_arg_func, "Show extended detail", NULL}, {"terse", 't', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, output_arg_func, "Show brief detail", NULL}, {"brief", '\0', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, output_arg_func, "Show brief detail", NULL}, {"vv", '\0', G_OPTION_FLAG_NO_ARG | G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, output_arg_func, "Show extra verbose detail", NULL}, {"very-verbose", '\0', G_OPTION_FLAG_NO_ARG | G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, output_arg_func, "Show extra verbose detail", NULL}, // Program information {"settings",'\0', 0, G_OPTION_ARG_NONE, &show_settings_flag,"Show current settings", NULL}, {"version", 'V', 0, G_OPTION_ARG_NONE, &version_flag, "Show ddcutil version", NULL}, // Miscellaneous // move to preparser_options if also implemented for libddcutil {"noconfig",'\0', 0, G_OPTION_ARG_NONE, &disable_config_flag, "Do not process configuration file", NULL}, {NULL}, }; GOptionEntry ddcutil_only_options[] = { // Monitor selection options {"display", 'd', 0, G_OPTION_ARG_INT, &dispwork, "Display number", "number"}, {"dis", '\0', 0, G_OPTION_ARG_INT, &dispwork, "Display number", "number"}, {"bus", 'b', 0, G_OPTION_ARG_INT, &buswork, "I2C bus number", "busnum" }, {"hiddev", '\0', 0, G_OPTION_ARG_INT, &hidwork, "hiddev device number", "number" }, {"usb", 'u', 0, G_OPTION_ARG_STRING, &usbwork, "USB bus and device numbers", "busnum.devicenum"}, {"mfg", 'g', 0, G_OPTION_ARG_STRING, &mfg_id_work, "Monitor manufacturer code", "mfg_id"}, {"model", 'l', 0, G_OPTION_ARG_STRING, &modelwork, "Monitor model", "model name"}, {"sn", 'n', 0, G_OPTION_ARG_STRING, &snwork, "Monitor serial number", "serial number"}, {"edid", 'e', 0, G_OPTION_ARG_STRING, &edidwork, "Monitor EDID", "256 char hex string" }, // Feature selection filters {"show-unsupported", 'U', 0, G_OPTION_ARG_NONE, &show_unsupported_flag, "Report unsupported features", NULL}, {"notable", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, ¬able_flag, "Exclude table type feature codes", NULL}, {"no-table",'\0', 0, G_OPTION_ARG_NONE, ¬able_flag, "Exclude table type feature codes", NULL}, {"show-table",'\0',G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, ¬able_flag, "Report table type feature codes", NULL}, {"rw", '\0', 0, G_OPTION_ARG_NONE, &rw_only_flag, "Include only RW features", NULL}, {"ro", '\0', 0, G_OPTION_ARG_NONE, &ro_only_flag, "Include only RO features", NULL}, {"wo", '\0', 0, G_OPTION_ARG_NONE, &wo_only_flag, "Include only WO features", NULL}, {NULL}, }; GOptionEntry common_options[] = { // long_name short flags option-type gpointer description arg description // Diagnostic output {"ddc", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &ddc_flag, "Report DDC protocol and data errors (Deprecated, use --ddcdata)", NULL}, {"ddcdata", '\0', 0, G_OPTION_ARG_NONE, &ddc_flag, "Report DDC protocol and data errors", NULL}, {"stats", 's', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, stats_arg_func, "Show performance statistics", "stats type"}, {"vstats", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, stats_arg_func, "Show detailed performance statistics", "stats type"}, {"istats", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, stats_arg_func, "Show detailed and internal performance statistics", "stats type"}, {"profile-api",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &profile_api_flag, "Profile API calls", NULL}, {"syslog", '\0',0, G_OPTION_ARG_STRING, &syslog_work, "system log level", valid_syslog_levels_string}, // Performance {"enable-capabilities-cache", '\0', 0, G_OPTION_ARG_NONE, &enable_cc_flag, enable_cc_expl, NULL}, {"disable-capabilities-cache", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_cc_flag, disable_cc_expl , NULL}, {"enable-displays-cache", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_cd_flag, enable_cd_expl, NULL}, {"disable-displays-cache", '\0', G_OPTION_FLAG_REVERSE|G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_cd_flag, disable_cd_expl , NULL}, {"sleep-multiplier", '\0', 0, G_OPTION_ARG_STRING, &sleep_multiplier_work, "Multiplication factor for DDC sleeps", "number"}, {"enable-dynamic-sleep", '\0', 0, G_OPTION_ARG_NONE, &enable_dsa2_flag, enable_dsa2_expl, NULL}, {"disable-dynamic-sleep", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_dsa2_flag, disable_dsa2_expl, NULL}, {"dynamic-sleep-adjustment",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_dsa2_flag, enable_dsa2_expl, NULL}, {"dsa", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_dsa2_flag, enable_dsa2_expl, NULL}, {"nodsa", '\0', G_OPTION_FLAG_HIDDEN | G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_dsa2_flag, disable_dsa2_expl, NULL}, {"enable-dsa", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_dsa2_flag, enable_dsa2_expl, NULL}, {"disable-dsa", '\0', G_OPTION_FLAG_HIDDEN |G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_dsa2_flag, disable_dsa2_expl, NULL}, {"dsa2", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_dsa2_flag, enable_dsa2_expl, NULL}, {"disable-dsa2", '\0', G_OPTION_FLAG_HIDDEN | G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_dsa2_flag, disable_dsa2_expl, NULL}, {"min-dynamic-multiplier", '\0', 0, G_OPTION_ARG_STRING, &min_dynamic_sleep_work, "Lowest allowed dynamic sleep multiplier", "number"}, {"min-dynamic-sleep-multiplier", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &min_dynamic_sleep_work, "Lowest allowed dynamic sleep multiplier", "number"}, #ifdef OUT {"enable-async-ddc-checks", '\0', 0, G_OPTION_ARG_NONE, &async_flag, "Enable asynchronous display detection", NULL}, {"disable-async-ddc-checks", '\0', 0, G_OPTION_ARG_NONE, &async_flag, "Disable asynchronous display detection", NULL}, {"enable-async-i2c-bus-checks", '\0', 0, G_OPTION_ARG_NONE, &async_check_i2c_flag, "Enable parallel examination of /dev/i2c devices (default)", NULL}, {"disable-async-i2c-bus-checks", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &async_check_i2c_flag, "Disable parallel examination of /dev/i2c devices", NULL}, #endif {"async", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &async_flag, "Enable asynchronous display detection (deprecated)", NULL}, {"i2c-bus-checks-async-min",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_INT, &parsed_cmd->i2c_bus_check_async_min, i2c_bus_check_async_expl, NULL}, {"ddc-checks-async-min", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_INT, &parsed_cmd->ddc_check_async_min, ddc_check_async_expl, NULL}, {"i2c-init-async-min",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_INT, &parsed_cmd->i2c_bus_check_async_min, i2c_bus_check_async_expl, NULL}, {"ddc-init-async-min", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_INT, &parsed_cmd->ddc_check_async_min, ddc_check_async_expl, NULL}, {"skip-ddc-checks",'\0',0,G_OPTION_ARG_NONE, &skip_ddc_checks_flag, "Skip initial DDC checks", NULL}, {"lazy-sleep", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &deferred_sleep_flag, "Delay sleeps if possible", NULL}, // {"defer-sleeps",'\0', 0, G_OPTION_ARG_NONE, &deferred_sleep_flag, "Delay sleeps if possible", NULL}, {"less-sleep" , '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &reduce_sleeps_specified, "Deprecated", NULL}, {"sleep-less" , '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &reduce_sleeps_specified, "Deprecated", NULL}, {"enable-sleep-less" ,'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &reduce_sleeps_specified, "Deprecated", NULL}, {"disable-sleep-less",'\0', G_OPTION_FLAG_HIDDEN|G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &reduce_sleeps_specified, "Deprecated", NULL}, {"discard-caches", '\0', G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, discard_cache_arg_func, "Discard performance caches", "cache type"}, {"discard-cache", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, discard_cache_arg_func, "Discard performance caches", "cache type"}, {"discard-capabilities-cache", '\0', 0, G_OPTION_ARG_NONE, &discard_cached_capabilities_flag, "Discard capabilities cache", NULL}, {"discard-dynamic-sleep-cache", '\0', 0, G_OPTION_ARG_NONE, &discard_dsa_cache_flag, "Discard dynamic sleep cache", NULL}, // {"discard-dsa-cache", // '\0', 0, G_OPTION_ARG_NONE, &discard_dsa_cache_flag, "Discard dynamic sleep cache", NULL}, // Behavior options {"maxtries",'\0', 0, G_OPTION_ARG_STRING, &maxtrywork, "Max try adjustment", "comma separated list" }, {"verify", '\0', 0, G_OPTION_ARG_NONE, &verify_flag, verify_expl, NULL}, {"noverify",'\0', 0, G_OPTION_ARG_NONE, &noverify_flag, noverify_expl, NULL}, {"mccs", '\0', 0, G_OPTION_ARG_STRING, &mccswork, "Tailor feature handling to specific MCCS version", "major.minor" }, {"udf", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_udf_flag, enable_udf_expl, NULL}, {"enable-udf",'\0',0,G_OPTION_ARG_NONE, &enable_udf_flag, enable_udf_expl, NULL}, {"noudf", '\0', G_OPTION_FLAG_HIDDEN | G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_udf_flag, disable_udf_expl, NULL}, {"disable-udf",'\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_udf_flag, disable_udf_expl, NULL}, {"enable-heuristic-unsupported", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_heuristic_unsupported_flag, "Perform heuristic unsupported feature detection", NULL}, {"disable-heuristic-unsupported", '\0', G_OPTION_FLAG_REVERSE|G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &enable_heuristic_unsupported_flag, "Recognize only DDC/CI specified unsupported feature detection", NULL}, {"enable-cross-instance-locks", '\0', 0, G_OPTION_ARG_NONE, &enable_flock_flag, enable_flock_expl, NULL}, {"disable-cross-instance-locks", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_flock_flag, disable_flock_expl , NULL}, {"enable-flock", '\0', 0, G_OPTION_ARG_NONE, &enable_flock_flag, enable_flock_expl, NULL}, {"disable-flock", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_flock_flag, disable_flock_expl , NULL}, {"enable-try-get-edid-from-sysfs", '\0', 0, G_OPTION_ARG_NONE, &try_get_edid_from_sysfs, enable_tgefs_expl, NULL}, {"disable-try-get-edid-from-sysfs", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &try_get_edid_from_sysfs, disable_tgefs_expl, NULL}, // {"enable-watch-displays", '\0', 0, G_OPTION_ARG_NONE, &watch_displays_flag, "Watch for display hotplug events", NULL }, {"disable-watch-displays", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_watch_displays, "Do not watch for display change events", NULL }, {"disable-api", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &disable_api_flag, "Completely disable API", NULL }, {"watch-mode", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &watch_mode_work, "How to watch for display changes", watch_mode_expl}, {"xevent-watch-loop-millisec", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_INT, &xevent_watch_loop_millis_work, "Loop delay for mode XEVENT", "milliseconds"}, {"poll-watch-loop-millisec", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_INT, &poll_watch_loop_millis_work, "Loop delay for mode POLL", "milliseconds"}, #ifdef ENABLE_USB {"enable-usb", '\0', G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, &enable_usb_flag, enable_usb_expl, NULL}, {"disable-usb",'\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_usb_flag, disable_usb_expl, NULL}, {"nousb", '\0', G_OPTION_FLAG_HIDDEN | G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &enable_usb_flag, disable_usb_expl, NULL}, {"ignore-usb-vid-pid", '\0', 0, G_OPTION_ARG_STRING_ARRAY, &ignored_vid_pid, "USB device to ignore","vid:pid" }, {"ignore-hiddev", '\0', 0, G_OPTION_ARG_CALLBACK, ignored_hiddev_arg_func, "USB device to ignore", "hiddev number"}, #endif {"disable-ddc", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING_ARRAY, &parsed_cmd->ddc_disabled, "Disable DDC for monitor","monitor model id" }, {"ignore-mmid", '\0', 0, G_OPTION_ARG_STRING_ARRAY, &parsed_cmd->ddc_disabled, "Disable DDC for monitor","monitor model id" }, #ifdef FUTURE {"force-slave-address", '\0', 0, G_OPTION_ARG_NONE, &force_slave_flag, "Deprecated", NULL}, #endif {"force-slave-address", '\0', 0, G_OPTION_ARG_NONE, &force_slave_flag, "Force I2C slave address", NULL}, {"use-file-io", '\0', 0, G_OPTION_ARG_NONE, &i2c_io_fileio_flag,"Use i2c-dev write()/read() calls by default", NULL}, {"use-ioctl-io", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &i2c_io_ioctl_flag, "Use i2c-dev ioctl() calls by default", NULL}, {"x52-no-fifo",'\0',G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &x52_no_fifo_flag, "Feature x52 does not have a FIFO queue", NULL}, {"edid-read-size", '\0', 0, G_OPTION_ARG_INT, &edid_read_size_work, "Number of EDID bytes to read", "128,256" }, {"i2c-source-addr", '\0', 0, G_OPTION_ARG_STRING, &i2c_source_addr_work, "Alternative I2C source address", "source address"}, {"force", 'f', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &force_flag, "Deprecated", NULL}, {"permit-unknown-feature", '\0', 0, G_OPTION_ARG_NONE, &allow_unrecognized_feature_flag, "setvcp of unrecognized feature ok", NULL}, {"timeout-i2c-io",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &timeout_i2c_io_flag, "Deprecated", NULL}, // {"no-timeout-ddc-io",'\0',G_OPTION_FLAG_REVERSE, // G_OPTION_ARG_NONE, &timeout_i2c_io_flag, "Do not wrap DDC IO in timeout (default)", NULL}, {NULL}, }; GOptionEntry debug_options[] = { // Debugging {"excp", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &report_freed_excp_flag, "Report freed exceptions", NULL}, {"trace", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING_ARRAY, &trace_classes, "Trace classes", "trace class name" }, // {"trace", '\0', 0, G_OPTION_ARG_STRING, &tracework, "Trace classes", "comma separated list" }, {"trcapi", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING_ARRAY, &parsed_cmd->traced_api_calls, "Trace API call", "function name"}, {"trcfunc", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING_ARRAY, &parsed_cmd->traced_functions, "Trace functions","function name" }, {"trcfrom", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING_ARRAY, &parsed_cmd->traced_calls, "Trace call stack from function","function name" }, {"trcfile", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING_ARRAY, &parsed_cmd->traced_files, "Trace files", "file name" }, {"enable-traced-function-stack", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &traced_function_stack_flag, "Enable traced function stack", NULL}, // {"traced-function-stack-errors-fatal", // '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &traced_function_stack_errors_fatal_flag, "Traced function stack errors are fatal", NULL}, {"timestamp", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, ×tamp_trace_flag, "Prepend trace msgs with elapsed time", NULL}, {"ts", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, ×tamp_trace_flag, "Prepend trace msgs with elapsed time", NULL}, {"wall-timestamp", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &wall_timestamp_trace_flag, "Prepend trace msgs with wall time", NULL}, {"wts", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &wall_timestamp_trace_flag, "Prepend trace msgs with wall time", NULL}, {"thread-id", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &thread_id_trace_flag, "Prepend trace msgs with thread id", NULL}, {"tid", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &thread_id_trace_flag, "Prepend trace msgs with thread id", NULL}, {"process-id", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &process_id_trace_flag, "Prepend trace msgs with process id", NULL}, {"pid", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &process_id_trace_flag, "Prepend trace msgs with process id", NULL}, // {"trace-to-file",'\0',0,G_OPTION_ARG_STRING, &parsed_cmd->trace_destination, "Send trace output here instead of terminal", "file name or \"syslog\""}, {"trace-to-syslog-only",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &trace_to_syslog_only_flag, "Direct trace output only to syslog", NULL}, {"libddcutil-trace-file",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &parsed_cmd->trace_destination, "libddcutil trace file", "file name"}, {"stats-to-syslog",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &stats_to_syslog_only_flag, "Direct stats to syslog", NULL}, {"debug-parse",'\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &debug_parse_flag, "Report parsed command", NULL}, {"parse-only", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &parse_only_flag, "Terminate after parsing", NULL}, {"failsim", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_FILENAME, &failsim_fn_work, "Enable simulation", "control file name"}, {"quickenv", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &quick_flag, "Skip long running tests", NULL}, {"enable-mock-data", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &mock_data_flag, "Enable mock feature values", NULL}, {"force-null-msg-for-unsupported", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &null_msg_for_unsupported_flag, "Simulate Null Msg indicates unsupported feature", NULL}, // Generic options to aid development {"i1", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i1_work, "Special integer 1", "decimal or hex number" }, {"i2", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i2_work, "Special integer 2", "decimal or hex number" }, {"i3", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i3_work, "Special integer 3", "decimal or hex number" }, {"i4", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i4_work, "Special integer 4", "decimal or hex number" }, {"i5", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i5_work, "Special integer 5", "decimal or hex number" }, {"i6", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i6_work, "Special integer 6", "decimal or hex number" }, {"i7", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i7_work, "Special integer 7", "decimal or hex number" }, {"i8", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i8_work, "Special integer 8", "decimal or hex number" }, {"i9", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i9_work, "Special integer 9", "decimal or hex number" }, {"i10", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i10_work, "Special integer 10", "decimal or hex number" }, {"i11", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i11_work, "Special integer 11", "decimal or hex number" }, {"i12", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i12_work, "Special integer 12", "decimal or hex number" }, {"i13", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i13_work, "Special integer 13", "decimal or hex number" }, {"i14", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i14_work, "Special integer 14", "decimal or hex number" }, {"i15", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i15_work, "Special integer 15", "decimal or hex number" }, {"i16", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &i16_work, "Special integer 16", "decimal or hex number" }, {"fl1", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &fl1_work, "Special floating point number 1", "floating point number" }, {"fl2", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &fl2_work, "Special floating point number 2", "floating point number" }, {"f1", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f1_flag, "Special flag 1", NULL}, {"f2", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f2_flag, "Special flag 2", NULL}, {"f3", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f3_flag, "Special flag 3", NULL}, {"f4", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f4_flag, "Special flag 4", NULL}, {"f5", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f5_flag, "Special flag 5", NULL}, {"f6", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f6_flag, "Special flag 6", NULL}, {"f7", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f7_flag, "Special flag 7", NULL}, {"f8", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f8_flag, "Special flag 8", NULL}, {"f9", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f9_flag, "Special flag 9", NULL}, {"f10", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f10_flag, "Special flag 10", NULL}, {"f11", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f11_flag, "Special flag 11", NULL}, {"f12", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f12_flag, "Special flag 12", NULL}, {"f13", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f13_flag, "Special flag 13", NULL}, {"f14", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f14_flag, "Special flag 14", NULL}, {"f15", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f15_flag, "Special flag 15", NULL}, {"f16", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f16_flag, "Special flag 16", NULL}, {"f17", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f17_flag, "Special flag 17", NULL}, {"f18", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f18_flag, "Special flag 18", NULL}, {"f19", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f19_flag, "Special flag 19", NULL}, {"f20", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f20_flag, "Special flag 20", NULL}, {"f21", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f21_flag, "Special flag 21", NULL}, {"f22", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f22_flag, "Special flag 22", NULL}, {"f23", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f23_flag, "Special flag 23", NULL}, {"f24", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f24_flag, "Special flag 24", NULL}, {"f25", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f25_flag, "Special flag 25", NULL}, {"f26", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f26_flag, "Special flag 26", NULL}, {"f27", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f27_flag, "Special flag 27", NULL}, {"f28", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f28_flag, "Special flag 28", NULL}, {"f29", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f29_flag, "Special flag 29", NULL}, {"f30", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f30_flag, "Special flag 30", NULL}, {"f31", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f31_flag, "Special flag 31", NULL}, {"f32", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &f32_flag, "Special flag 32", NULL}, {"s1", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &parsed_cmd->s1, "Special string 1", "string"}, {"s2", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &parsed_cmd->s2, "Special string 2", "string"}, {"s3", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &parsed_cmd->s3, "Special string 3", "string"}, {"s4", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &parsed_cmd->s4, "Special string 4", "string"}, {NULL}, }; GOptionEntry final_options[] = { {G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_STRING_ARRAY, &cmd_and_args, "ARGUMENTS description", "command [arguments...]"}, { NULL } }; // DBG("Looking for --hh..."); Null_Terminated_String_Array temp_argv = ntsa_copy(argv, true); int hh_ndx = ntsa_find(temp_argv, "--hh"); if (hh_ndx >= 0) { DBGF(debug, "--hh found"); hidden_help_flag = true; free(temp_argv[hh_ndx]); temp_argv[hh_ndx] = g_strdup("-h"); } if (hidden_help_flag) { unhide_options(initial_options); unhide_options(ddcutil_only_options); unhide_options(common_options); unhide_options(debug_options); } bool preparse_verbose = ntsa_find(temp_argv, "--verbose") >= 0 || ntsa_find(temp_argv, "-v") >= 0; bool preparse_terse = ntsa_find(temp_argv, "--terse") >= 0 || ntsa_find(temp_argv, "-t") >= 0 || ntsa_find(temp_argv, "--brief") >= 0; GOptionGroup * all_options = g_option_group_new( "group name", "group description", "help description", NULL, NULL); g_option_group_add_entries(all_options, initial_options); if (parser_mode == MODE_DDCUTIL) { g_option_group_add_entries(all_options, ddcutil_only_options); } g_option_group_add_entries(all_options, common_options); g_option_group_add_entries(all_options, preparser_options); #ifdef OLD if (parser_mode == MODE_LIBDDCUTIL) { g_option_group_add_entries(all_options, libddcutil_only_options); } #endif #ifndef FUTURE g_option_group_add_entries(all_options, debug_options); #endif g_option_group_add_entries(all_options, final_options); #ifdef FUTURE GOptionGroup * debug_option_group = g_option_group_new("debug","Debug Options", "(debug options description)", NULL, // user data NULL); // function to free user data g_option_group_add_entries(debug_option_group, debug_options); g_option_group_set_parse_hooks(debug_option_group, debug_pre_parse_func, debug_post_parse_func); #endif #ifdef WORKS // Preparser GError* preparser_error = NULL; GOptionContext* preparser_context = g_option_context_new("- Preparser"); g_option_context_add_main_entries(preparser_context, preparser_options, NULL); // on --help, comes after usage line, before option detail g_option_context_set_summary(preparser_context, "Preparser help_summary"); // on --help, comes at end after option detail g_option_context_set_description(preparser_context, "Preparser help description"); g_option_context_set_help_enabled(preparser_context, false); Null_Terminated_String_Array temp_argv = ntsa_copy(argv, true); bool preparser_parsing_ok = g_option_context_parse_strv(preparser_context, &temp_argv, &preparser_error); if (!preparser_parsing_ok) { if (preparser_error) printf("%s\n" , preparser_error->message); else printf("Preparser option parsing failed"); } ntsa_free(temp_argv, true); printf("(%s) hidden_help_flag: %s\n", __func__, sbool(hidden_help_flag)); if (hidden_help_flag) { } #endif // Main Parser GError* error = NULL; // DBG("Allocating context..."); GOptionContext* context = g_option_context_new("- DDC query and manipulation"); // g_option_context_add_main_entries(context, option_entries, NULL); g_option_context_set_main_group(context, all_options); #ifdef FUTURE g_option_context_add_group(context, debug_option_group); #endif // comma delimited list of trace identifiers: // char * trace_group_string = strjoin(trace_group_names, trace_group_ct, ", "); // DBGMSG("traceGroupString = %s", traceGroupString); // const char * pieces[] = {tracing_option_help, " Recognized trace classes: ", trace_group_string, "\n\n"}; // tracing_option_help = strjoin(pieces, 4, NULL); // const char * pieces2[] = {command_argument_help, " Recognized trace classes: ", trace_group_string, "\n\n"}; // command_argument_help = strjoin(pieces, 4, NULL); // const char * pieces3[] = {commands_list_help, command_argument_help}; // char * help_summary = strjoin(pieces3, 2, NULL); char * help_summary = NULL; if (preparse_verbose) { char * cmd_args_help = assemble_command_argument_help(); const char * pieces[] = {commands_list_help, "\n", cmd_args_help}; help_summary = strjoin(pieces, 3, NULL); free(cmd_args_help); } else { // const char * pieces[] = {commands_list_help, "\n"}; // help_summary = strjoin(pieces, 2, NULL); help_summary = g_strdup(commands_list_help); } char * help_description = NULL; if (preparse_verbose) { const char * pieces[] = {monitor_selection_option_help, tracing_multiple_call_option_help, "\n", trcfunc_multiple_call_option_help, "\n", trcfile_multiple_call_option_help, "\n", stats_multiple_call_option_help, "\n", maxtries_option_help, NULL}; help_description = strjoin(pieces, -1, NULL); } else if (preparse_terse) { help_description = NULL; } else { // const char * help_pieces[] = {monitor_selection_option_help}; // help_description = strjoin(help_pieces, 1, NULL); // help_description = g_strdup(monitor_selection_option_help); help_description = g_strdup("For detailed help, use option \"--verbose\"" "\nTo see all options, use option \"--hh\""); } // on --help, comes after usage line, before option detail g_option_context_set_summary(context, help_summary); free(help_summary); // on --help, comes at end after option detail g_option_context_set_description(context, help_description); free(help_description); g_option_context_set_help_enabled(context, true); /* From g_option_parse_documentation(): If the parsing is successful, any parsed arguments are removed from the array and argc and argv are updated accordingly. From g_option_parse_strv() documentation: This function is similar to g_option_context_parse() except that it respects the normal memory rules when dealing with a strv instead of assuming that the passed-in array is the argv of the main function. In particular, strings that are removed from the arguments list will be freed using g_free(). Pass a mangleable copy of argv to g_option_context_parse_strv(). */ // Null_Terminated_String_Array temp_argv = ntsa_copy(argv, true); // DBG("Before g_option_context_parse_strv()"); bool parsing_ok = g_option_context_parse_strv(context, &temp_argv, &error); DBGF(debug, "g_option_contenxt_parser_strv() returned %s, error=%p", sbool(parsing_ok), error); if (!parsing_ok) { char * mode_name = (parser_mode == MODE_DDCUTIL) ? "ddcutil" : "libddcutil"; if (error) { // EMIT_PARSER_ERROR(errmsgs, "%s option parsing failed: %s", mode_name, error->message); EMIT_PARSER_ERROR(errmsgs, "%s", error->message); free(error->message); free(error); } else EMIT_PARSER_ERROR(errmsgs, "%s option parsing failed", mode_name); } ntsa_free(temp_argv, true); int rwo_flag_ct = 0; if (rw_only_flag) rwo_flag_ct++; if (ro_only_flag) rwo_flag_ct++; if (wo_only_flag) rwo_flag_ct++; if (rwo_flag_ct > 1) { EMIT_PARSER_ERROR(errmsgs, "Options -rw-only, --ro-only, --wo-only are mutually exclusive"); parsing_ok = false; } if (reduce_sleeps_specified) EMIT_PARSER_ERROR(errmsgs, "Deprecated option ignored: --enable-sleep-less, --disable-sleep-less, etc."); if (timeout_i2c_io_flag) EMIT_PARSER_ERROR(errmsgs, "Deprecated option ignored: --timeout-i2c-io"); if (force_flag) { EMIT_PARSER_ERROR(errmsgs,"Deprecated option --force: Use --permit-unknown-feature"); allow_unrecognized_feature_flag = force_flag; } if (enable_cd_flag) { EMIT_PARSER_ERROR(errmsgs, "Warning: Experimental display information caching enabled"); } if (async_flag) { EMIT_PARSER_ERROR(errmsgs, "Deprecated option ignored: --async."); EMIT_PARSER_ERROR(errmsgs, "Use --i2c-bus-checks-async-min (experimental) or --ddc-checks-async-min"); } if (verify_flag && noverify_flag) { EMIT_PARSER_ERROR(errmsgs, "Both --verify and --noverify specified"); } #define LIBDDCUTIL_ONLY_OPTION(_name,_val) \ do \ if (_val) { \ EMIT_PARSER_ERROR(errmsgs, "libddcutil only option: %s", _name); \ parsing_ok = false; \ } \ while (0) if (parser_mode != MODE_LIBDDCUTIL) { LIBDDCUTIL_ONLY_OPTION("--trcapi", parsed_cmd->traced_api_calls); LIBDDCUTIL_ONLY_OPTION("--profile-api", profile_api_flag); LIBDDCUTIL_ONLY_OPTION("--libddcutil-trace-file", parsed_cmd->trace_destination); LIBDDCUTIL_ONLY_OPTION("--disable-watch-displays", !enable_watch_displays); LIBDDCUTIL_ONLY_OPTION("--disable-api", disable_api_flag); } #undef LIBDDCUTIL_ONLY_OPTION #define SET_CMDFLAG(_bit, _flag) \ do { \ if (_flag) \ parsed_cmd->flags |= _bit; \ } while(0) #define SET_CMDFLAG2(_bit, _flag) \ do { \ if (_flag) \ parsed_cmd->flags2 |= _bit; \ } while(0) #define SET_CLR_CMDFLAG(_bit, _flag) \ do { \ if (_flag) \ parsed_cmd->flags |= _bit; \ else \ parsed_cmd->flags &= ~_bit; \ } while(0) #define SET_CLR_CMDFLAG2(_bit, _flag) \ do { \ if (_flag) \ parsed_cmd->flags2 |= _bit; \ else \ parsed_cmd->flags2 &= ~_bit; \ } while(0) parsed_cmd->output_level = output_level; parsed_cmd->stats_types = stats_work; parsed_cmd->ignored_hiddevs = ignored_hiddev_work; SET_CMDFLAG(CMD_FLAG_VERBOSE_STATS, verbose_stats); SET_CMDFLAG(CMD_FLAG_INTERNAL_STATS, internal_stats); SET_CMDFLAG(CMD_FLAG_DDCDATA, ddc_flag); SET_CMDFLAG(CMD_FLAG_FORCE_SLAVE_ADDR, force_slave_flag); SET_CMDFLAG(CMD_FLAG_TIMESTAMP_TRACE, timestamp_trace_flag); SET_CMDFLAG(CMD_FLAG_WALLTIME_TRACE, wall_timestamp_trace_flag); SET_CMDFLAG(CMD_FLAG_THREAD_ID_TRACE, thread_id_trace_flag); SET_CMDFLAG(CMD_FLAG_PROCESS_ID_TRACE, process_id_trace_flag); SET_CMDFLAG(CMD_FLAG_VERIFY, verify_flag || !noverify_flag); // if (verify_flag || !noverify_flag) // parsed_cmd->flags |= CMD_FLAG_VERIFY; #ifdef OLD SET_CMDFLAG(CMD_FLAG_NODETECT, nodetect_flag); SET_CMDFLAG(CMD_FLAG_ASYNC_I2C_CHECK, async_check_i2c_flag); #endif SET_CMDFLAG(CMD_FLAG_REPORT_FREED_EXCP, report_freed_excp_flag); SET_CMDFLAG(CMD_FLAG_NOTABLE, notable_flag); SET_CMDFLAG(CMD_FLAG_SHOW_UNSUPPORTED, show_unsupported_flag); SET_CMDFLAG(CMD_FLAG_RW_ONLY, rw_only_flag); SET_CMDFLAG(CMD_FLAG_RO_ONLY, ro_only_flag); SET_CMDFLAG(CMD_FLAG_WO_ONLY, wo_only_flag); SET_CMDFLAG(CMD_FLAG_FORCE_UNRECOGNIZED_VCP_CODE, allow_unrecognized_feature_flag); SET_CLR_CMDFLAG(CMD_FLAG_ENABLE_UDF, enable_udf_flag); #ifdef ENABLE_USB SET_CMDFLAG(CMD_FLAG_ENABLE_USB, enable_usb_flag); #endif #ifdef OLD SET_CMDFLAG(CMD_FLAG_TIMEOUT_I2C_IO, timeout_i2c_io_flag); SET_CMDFLAG(CMD_FLAG_REDUCE_SLEEPS, reduce_sleeps_flag); #endif SET_CMDFLAG(CMD_FLAG_DSA2, enable_dsa2_flag); SET_CMDFLAG(CMD_FLAG_DEFER_SLEEPS, deferred_sleep_flag); SET_CMDFLAG(CMD_FLAG_WATCH_DISPLAY_EVENTS, enable_watch_displays); SET_CMDFLAG(CMD_FLAG_DISABLE_API, disable_api_flag); SET_CMDFLAG(CMD_FLAG_X52_NO_FIFO, x52_no_fifo_flag); SET_CMDFLAG(CMD_FLAG_SHOW_SETTINGS, show_settings_flag); SET_CMDFLAG(CMD_FLAG_I2C_IO_FILEIO, i2c_io_fileio_flag); SET_CMDFLAG(CMD_FLAG_I2C_IO_IOCTL, i2c_io_ioctl_flag); SET_CMDFLAG(CMD_FLAG_QUICK, quick_flag); SET_CMDFLAG(CMD_FLAG_MOCK, mock_data_flag); SET_CMDFLAG(CMD_FLAG_PROFILE_API, profile_api_flag); SET_CMDFLAG(CMD_FLAG_TRACE_TO_SYSLOG_ONLY, trace_to_syslog_only_flag); SET_CMDFLAG(CMD_FLAG_STATS_TO_SYSLOG, stats_to_syslog_only_flag); SET_CMDFLAG(CMD_FLAG_NULL_MSG_INDICATES_UNSUPPORTED_FEATURE, null_msg_for_unsupported_flag); SET_CMDFLAG(CMD_FLAG_HEURISTIC_UNSUPPORTED_FEATURES, enable_heuristic_unsupported_flag); SET_CMDFLAG(CMD_FLAG_SKIP_DDC_CHECKS, skip_ddc_checks_flag); SET_CMDFLAG(CMD_FLAG_FLOCK, enable_flock_flag); SET_CMDFLAG(CMD_FLAG_ENABLE_TRACED_FUNCTION_STACK, traced_function_stack_flag); SET_CMDFLAG(CMD_FLAG_TRACED_FUNCTION_STACK_ERRORS_FATAL, traced_function_stack_errors_fatal_flag); SET_CLR_CMDFLAG(CMD_FLAG_TRY_GET_EDID_FROM_SYSFS, try_get_edid_from_sysfs); SET_CLR_CMDFLAG(CMD_FLAG_ENABLE_CACHED_CAPABILITIES, enable_cc_flag); // #ifdef REMOVED SET_CLR_CMDFLAG(CMD_FLAG_ENABLE_CACHED_DISPLAYS, enable_cd_flag); // #endif SET_CMDFLAG2(CMD_FLAG2_F1, f1_flag); SET_CMDFLAG2(CMD_FLAG2_F2, f2_flag); SET_CMDFLAG2(CMD_FLAG2_F3, f3_flag); SET_CMDFLAG2(CMD_FLAG2_F4, f4_flag); SET_CMDFLAG2(CMD_FLAG2_F5, f5_flag); SET_CMDFLAG2(CMD_FLAG2_F6, f6_flag); SET_CMDFLAG2(CMD_FLAG2_F7, f7_flag); SET_CMDFLAG2(CMD_FLAG2_F8, f8_flag); SET_CMDFLAG2(CMD_FLAG2_F9, f9_flag); SET_CMDFLAG2(CMD_FLAG2_F10, f10_flag); SET_CMDFLAG2(CMD_FLAG2_F11, f11_flag); SET_CMDFLAG2(CMD_FLAG2_F12, f12_flag); SET_CMDFLAG2(CMD_FLAG2_F13, f13_flag); SET_CMDFLAG2(CMD_FLAG2_F14, f14_flag); SET_CMDFLAG2(CMD_FLAG2_F15, f15_flag); SET_CMDFLAG2(CMD_FLAG2_F16, f16_flag); SET_CMDFLAG2(CMD_FLAG2_F17, f17_flag); SET_CMDFLAG2(CMD_FLAG2_F18, f18_flag); SET_CMDFLAG2(CMD_FLAG2_F19, f19_flag); SET_CMDFLAG2(CMD_FLAG2_F20, f20_flag); SET_CMDFLAG2(CMD_FLAG2_F21, f21_flag); SET_CMDFLAG2(CMD_FLAG2_F22, f22_flag); SET_CMDFLAG2(CMD_FLAG2_F23, f23_flag); SET_CMDFLAG2(CMD_FLAG2_F24, f24_flag); SET_CMDFLAG2(CMD_FLAG2_F25, f25_flag); SET_CMDFLAG2(CMD_FLAG2_F26, f26_flag); SET_CMDFLAG2(CMD_FLAG2_F27, f27_flag); SET_CMDFLAG2(CMD_FLAG2_F28, f28_flag); SET_CMDFLAG2(CMD_FLAG2_F29, f29_flag); SET_CMDFLAG2(CMD_FLAG2_F30, f30_flag); SET_CMDFLAG2(CMD_FLAG2_F31, f31_flag); SET_CMDFLAG2(CMD_FLAG2_F32, f32_flag); if (discarded_caches_work) { parsed_cmd->discarded_cache_types = discarded_caches_work; SET_CMDFLAG(CMD_FLAG_DISCARD_CACHES, true); } if (discard_cached_capabilities_flag) { parsed_cmd->discarded_cache_types |= CAPABILITIES_CACHE;; SET_CMDFLAG(CMD_FLAG_DISCARD_CACHES, true); } if (discard_dsa_cache_flag) { parsed_cmd->discarded_cache_types |= DSA2_CACHE;; SET_CMDFLAG(CMD_FLAG_DISCARD_CACHES, true); } if (failsim_fn_work) { #ifdef ENABLE_FAILSIM // parsed_cmd->enable_failure_simulation = true; parsed_cmd->flags |= CMD_FLAG_ENABLE_FAILSIM; parsed_cmd->failsim_control_fn = failsim_fn_work; #else EMIT_PARSER_ERROR(errmsgs, "ddcutil not built with failure simulation support. --failsim option invalid."); parsing_ok = false; #endif } #undef SET_CMDFLAG #undef SET_CMDFLAG2 #undef SET_CLR_CMDFLAG // Create display identifier // // n. at this point parsed_cmd->pdid == NULL parsing_ok &= parse_display_identifier( parsed_cmd, errmsgs, dispwork, buswork, hidwork, usbwork, edidwork, mfg_id_work, modelwork, snwork); FREE(usbwork); FREE(edidwork); FREE(mfg_id_work); FREE(modelwork); FREE(snwork); if (maxtrywork) { parsing_ok &= parse_maxtrywork(maxtrywork, parsed_cmd, errmsgs); free(maxtrywork); maxtrywork = NULL; } if (mccswork) { parsing_ok &= parse_mccswork(mccswork, parsed_cmd, errmsgs); FREE(mccswork); } if (syslog_work) { DDCA_Syslog_Level level; bool this_ok = parse_syslog_level(syslog_work, &level, errmsgs); // printf("(%s) this_ok = %s\n", __func__, sbool(this_ok)); if (this_ok) syslog_level = level; else parsing_ok = false; FREE(syslog_work); } parsed_cmd->syslog_level = syslog_level; if (i2c_source_addr_work) { int ival; bool ok = parse_int_work(i2c_source_addr_work, &ival, errmsgs); if (ival < 0 || ival > 255) { EMIT_PARSER_ERROR(errmsgs, "Source address must be a single byte value"); ok = false; } if (ok) { parsed_cmd->flags = parsed_cmd->flags | CMD_FLAG_EXPLICIT_I2C_SOURCE_ADDR; parsed_cmd->explicit_i2c_source_addr = (uint8_t) ival; } parsing_ok &= ok; FREE(i2c_source_addr_work); } #ifdef OLD if (i1_work) { bool ok = parse_int_work(i1_work, &parsed_cmd->i1, errmsgs); if (ok) parsed_cmd->flags2 = parsed_cmd->flags2 | CMD_FLAG2_I1_SET; parsing_ok &= ok; FREE(i1_work); } if (i2_work) { bool ok = parse_int_work(i2_work, &parsed_cmd->i2, errmsgs); if (ok) parsed_cmd->flags2 = parsed_cmd->flags2 | CMD_FLAG2_I2_SET; parsing_ok &= ok; FREE(i2_work); } if (i3_work) { bool ok = parse_int_work(i3_work, &parsed_cmd->i3, errmsgs); if (ok) parsed_cmd->flags2 = parsed_cmd->flags2 | CMD_FLAG2_I3_SET; parsing_ok &= ok; FREE(i2_work); } #endif #define SET_CMDFLAG_I(_n) \ do { \ if (i ## _n ## _work) { \ bool ok = parse_int_work(i ## _n ## _work, &parsed_cmd->i##_n, errmsgs); \ if (ok) \ parsed_cmd->flags2 = parsed_cmd->flags2 | CMD_FLAG2_I##_n##_SET; \ parsing_ok &= ok; \ free (i ## _n ## _work); \ i ## _n ## _work = NULL; \ } \ } while (0) SET_CMDFLAG_I(1); SET_CMDFLAG_I(2); SET_CMDFLAG_I(3); SET_CMDFLAG_I(4); SET_CMDFLAG_I(5); SET_CMDFLAG_I(6); SET_CMDFLAG_I(7); SET_CMDFLAG_I(8); SET_CMDFLAG_I(9); SET_CMDFLAG_I(10); SET_CMDFLAG_I(11); SET_CMDFLAG_I(12); SET_CMDFLAG_I(13); SET_CMDFLAG_I(14); SET_CMDFLAG_I(15); SET_CMDFLAG_I(16); #undef SET_CMDFLAG_I if (fl1_work) { bool ok = str_to_float(fl1_work, &parsed_cmd->fl1); if (!ok) EMIT_PARSER_ERROR(errmsgs, "Invalid floating point number: %s", fl1_work); else parsed_cmd->flags = parsed_cmd->flags2 | CMD_FLAG2_FL1_SET; parsing_ok &= ok; FREE(fl1_work); } if (fl2_work) { bool ok = str_to_float(fl2_work, &parsed_cmd->fl2); if (!ok) EMIT_PARSER_ERROR(errmsgs, "Invalid floating point number: %s", fl2_work); else parsed_cmd->flags = parsed_cmd->flags2 | CMD_FLAG2_FL2_SET; parsing_ok &= ok; FREE(fl2_work); } #ifdef ENABLE_USB if (ignored_vid_pid) { int ndx = 0; for (char * cur = ignored_vid_pid[ndx]; cur && ndx < 10; cur=ignored_vid_pid[++ndx]) { // DBGMSG("cur[%d]=%p -> %s", ndx, cur, cur); uint16_t vid; uint16_t pid; bool ok = parse_colon_separated_vid_pid(cur, &vid, &pid); if (!ok) { EMIT_PARSER_ERROR(errmsgs, "Invalid vid:pid value: %s", cur); parsing_ok = false; } else { // DBGMSG("vid = 0x%04x, pid=0x%04x", vid, pid); uint32_t ignored_vid_pid = vid << 16 | pid; // DBGMSG("ignored_vid_pid = 0x%08x", ignored_vid_pid); if (parsed_cmd->ignored_usb_vid_pid_ct < IGNORED_VID_PID_MAX) parsed_cmd->ignored_usb_vid_pids[parsed_cmd->ignored_usb_vid_pid_ct++] = ignored_vid_pid; else { EMIT_PARSER_ERROR(errmsgs, "Too many ignore-usb-vid-pid values"); parsing_ok = false; } } } ntsa_free(ignored_vid_pid,true); ignored_vid_pid = NULL; } #endif if (sleep_multiplier_work) { float multiplier = 0.0f; if (parse_sleep_multiplier(sleep_multiplier_work, &multiplier, errmsgs) ) { parsed_cmd->sleep_multiplier = multiplier; parsed_cmd->flags |= CMD_FLAG_EXPLICIT_SLEEP_MULTIPLIER; } else { parsing_ok = false; } FREE(sleep_multiplier_work); } if (min_dynamic_sleep_work) { parsing_ok &= parse_sleep_multiplier(min_dynamic_sleep_work, &parsed_cmd->min_dynamic_multiplier, errmsgs); FREE(min_dynamic_sleep_work); } if (watch_mode_work) { parsing_ok &= parse_watch_mode(watch_mode_work, parsed_cmd, errmsgs); FREE(watch_mode_work); } else parsed_cmd->watch_mode = DEFAULT_WATCH_MODE; DBGMSF(debug, "edid_read_size_work = %d", edid_read_size_work); if (edid_read_size_work != -1 && edid_read_size_work != 128 && edid_read_size_work != 0 && edid_read_size_work != 256) { EMIT_PARSER_ERROR(errmsgs, "Invalid EDID read size: %d", edid_read_size_work); parsing_ok = false; } else parsed_cmd->edid_read_size = edid_read_size_work; if (trace_classes) { parsing_ok &= parse_trace_classes(trace_classes, parsed_cmd, errmsgs); ntsa_free(trace_classes, true); } int rest_ct = 0; // don't pull debug into the if clause, need rest_ct to be set if (cmd_and_args) { for (; cmd_and_args[rest_ct] != NULL; rest_ct++) { DBGMSF(debug, "cmd_and_args[%d]: %s", rest_ct, cmd_and_args[rest_ct]); } } if (version_flag) { const char * version = get_full_ddcutil_version(); const char * prefix = (output_level > DDCA_OL_TERSE) ? "ddcutil " : ""; printf("%s%s\n", prefix, version); if (output_level >= DDCA_OL_VERBOSE) report_ddcutil_build_info(); // if no command specified, include license in version information and terminate if (rest_ct == 0) { if (output_level > DDCA_OL_TERSE) { puts("Copyright (C) 2015-2025 Sanford Rockowitz"); puts("License GPLv2: GNU GPL version 2 or later "); puts("This is free software: you are free to change and redistribute it."); puts("There is NO WARRANTY, to the extent permitted by law."); } exit(0); } } if (xevent_watch_loop_millis_work <= 0) { EMIT_PARSER_ERROR(errmsgs, "--xevent-watch-loop-millisec not a positive number: %d", xevent_watch_loop_millis_work); parsing_ok = false; } else parsed_cmd->xevent_watch_loop_millisec = (uint16_t) xevent_watch_loop_millis_work; if (poll_watch_loop_millis_work <= 0) { EMIT_PARSER_ERROR(errmsgs, "--poll-watch-loop-millisec not a positive number: %d", poll_watch_loop_millis_work); parsing_ok = false; } else parsed_cmd->poll_watch_loop_millisec = (uint16_t) poll_watch_loop_millis_work; // All options processed. Check for consistency, set defaults if (parser_mode == MODE_LIBDDCUTIL && rest_ct > 0) { EMIT_PARSER_ERROR(errmsgs, "Unrecognized: %s", cmd_and_args[0]); parsing_ok = false; } else if (parsing_ok && parser_mode == MODE_DDCUTIL && rest_ct == 0) { EMIT_PARSER_ERROR(errmsgs, "No command specified"); parsing_ok = false; } if (parsing_ok && parser_mode == MODE_DDCUTIL) { char * cmd = cmd_and_args[0]; if (debug) printf("cmd=|%s|\n", cmd); Cmd_Desc * cmdInfo = find_command(cmd); if (cmdInfo == NULL) { EMIT_PARSER_ERROR(errmsgs, "Unrecognized ddcutil command: %s", cmd); parsing_ok = false; } else { if (debug) show_cmd_desc(cmdInfo); // process command args parsed_cmd->cmd_id = cmdInfo->cmd_id; // parsedCmd->argCt = cmdInfo->argct; int min_arg_ct = cmdInfo->min_arg_ct; int max_arg_ct = cmdInfo->max_arg_ct; int argctr = 1; while ( cmd_and_args[argctr] != NULL) { if (argctr > max_arg_ct) { EMIT_PARSER_ERROR(errmsgs, "Too many arguments"); parsing_ok = false; break; } parsed_cmd->args[argctr-1] = g_strdup(cmd_and_args[argctr]); argctr++; } parsed_cmd->argct = argctr-1; ntsa_free(cmd_and_args, true); // no more arguments specified if (argctr <= min_arg_ct) { EMIT_PARSER_ERROR(errmsgs, "Missing argument(s)"); parsing_ok = false; } if ( parsing_ok && (parsed_cmd->cmd_id == CMDID_VCPINFO || parsed_cmd->cmd_id == CMDID_GETVCP) ) { parsed_cmd->fref = parse_feature_ids_or_subset( parsed_cmd->cmd_id, parsed_cmd->args, parsed_cmd->argct); if (!parsed_cmd->fref) { parsing_ok = false; char * s = strjoin((const char **)parsed_cmd->args, parsed_cmd->argct, " "); EMIT_PARSER_ERROR(errmsgs, "Invalid feature code(s) or subset: %s", s); free(s); } } // Ignore option --notable for vcpinfo if ( parsing_ok && parsed_cmd->cmd_id == CMDID_VCPINFO) { parsed_cmd->flags &= ~CMD_FLAG_NOTABLE; } if (parsing_ok && parsed_cmd->cmd_id == CMDID_DISCARD_CACHE) parsing_ok &= parse_discard_args(parsed_cmd, errmsgs); if (parsing_ok && parsed_cmd->cmd_id == CMDID_GETVCP && (parsed_cmd->flags & CMD_FLAG_WO_ONLY) ) { fprintf(stdout, "Ignoring option --wo-only\n"); parsed_cmd->flags &= ~CMD_FLAG_WO_ONLY; } if (parsing_ok && parsed_cmd->cmd_id == CMDID_SETVCP) parsing_ok &= parse_setvcp_args(parsed_cmd,errmsgs); if (parsing_ok && parsed_cmd->pdid) { if (!cmdInfo->supported_options & Option_Explicit_Display) { EMIT_PARSER_ERROR(errmsgs, "%s does not support explicit display option\n", cmdInfo->cmd_name); parsing_ok = false; } } #ifdef OUT if (parsing_ok && !(parsed_cmd->cmd_id == CMDID_GETVCP || parsed_cmd->cmd_id == CMDID_SETVCP)) { if (skip_ddc_checks_flag) { EMIT_PARSER_ERROR(errmsgs, "Option --skip-ddc-checks valid only for getvcp or setvcp"); parsing_ok = false; } } if (parsing_ok && skip_ddc_checks_flag && buswork < 0) { EMIT_PARSER_ERROR(errmsgs, "Option --skip-ddc-checks valid only with option --bus"); parsing_ok = false; } #endif } // recognized command } parsing_ok &= validate_output_level(parsed_cmd); DBGMSF(debug, "Calling g_option_context_free(), context=%p...", context); g_option_context_free(context); if (debug || debug_parse_flag) { DBGMSG("parsing_ok=%s", sbool(parsing_ok)); dbgrpt_parsed_cmd(parsed_cmd, 0); } if (!parsing_ok) { free_parsed_cmd(parsed_cmd); parsed_cmd = NULL; } if (debug) { DBGMSG("Before return: argc=%d", argc); int ndx = 0; for (; ndx < argc; ndx++) { DBGMSG("argv[%d] = |%s|", ndx, argv[ndx]); } } if (parse_only_flag && parsing_ok) { free_parsed_cmd(parsed_cmd); parsed_cmd = NULL; } DBGMSF(debug, "Returning: %p", parsed_cmd); return parsed_cmd; } ddcutil-2.2.0/src/cmdline/parsed_cmd.c0000644000175000001440000005703214754153540013306 /** @file parsed_cmd.c */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/glib_string_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "usb/usb_base.h" #include "base/core.h" #include "base/parms.h" #include "cmdline/parsed_cmd.h" // // Parsed_Cmd data structure // const char * parser_mode_name(Parser_Mode mode) { // use switch to force compilation error if a mode is added but not named char * name = NULL; switch(mode) { case MODE_DDCUTIL: name = "ddcutil"; break; case MODE_LIBDDCUTIL: name = "libddcutil"; break; } return name; } // Must be kept in sync with Cmd_Id_Type Value_Name_Table cmd_id_table = { VNT(CMDID_NONE , "none"), VNT(CMDID_DETECT , "detect"), VNT(CMDID_CAPABILITIES , "capabilities"), VNT(CMDID_GETVCP , "getvcp"), VNT(CMDID_SETVCP , "setvcp"), VNT(CMDID_LISTVCP , "listvcp"), VNT(CMDID_TESTCASE , "testcase"), VNT(CMDID_LISTTESTS , "listtests"), VNT(CMDID_LOADVCP , "loadvcp"), VNT(CMDID_DUMPVCP , "dumpvcp"), #ifdef ENABLE_ENVCMDS VNT(CMDID_INTERROGATE , "interrogate"), VNT(CMDID_ENVIRONMENT , "environment"), VNT(CMDID_USBENV , "usbenvironment"), #endif VNT(CMDID_VCPINFO , "vcpinfo"), VNT(CMDID_READCHANGES , "watch"), VNT(CMDID_CHKUSBMON , "chkusbmon"), VNT(CMDID_PROBE , "probe"), VNT(CMDID_SAVE_SETTINGS , "save settings"), VNT(CMDID_DISCARD_CACHE , "discard cache"), VNT(CMDID_LIST_RTTI , "traceable functions"), VNT(CMDID_C1 , "c1"), VNT(CMDID_C2 , "c2"), VNT(CMDID_C3 , "c3"), VNT(CMDID_C4 , "c4"), VNT_END }; /** Returns the symbolic name for a Cmd_Id_Type value */ const char * cmdid_name(Cmd_Id_Type id) { return vnt_name(cmd_id_table, id); } #ifdef FUTURE Value_Name_Table cmd_flag_table = { VNT(CMD_FLAG_DDCDATA, "report DDC errors"), VNT(CMD_FLAG_FORCE_UNRECOGNIZED_VCP_CODE, "ignore certain errors"), VNT(CMD_FLAG_FORCE_SLAVE_ADDR, "force slave address setting"), VNT(CMD_FLAG_TIMESTAMP_TRACE, "include timestamp on trace messages"), VNT(CMD_FLAG_SHOW_UNSUPPORTED, "show unsupported VCP features"), VNT(CMD_FLAG_ENABLE_FAILSIM, "enable failure simulation"), VNT(CMD_FLAG_VERIFY, "read VCP features after setting them"), // etc }; #endif /** Returns the symbolic name for a Setvcp_Value_Type value */ const char * setvcp_value_type_name(Setvcp_Value_Type value_type) { char * names[] = {"VALUE_TYPE_ABSOLUTE", "VALUE_TYPE_RELAIIVE_PLUS", "VALUE_TYPE_RELATIVE_MINUS"}; return names[value_type]; } /** Called by g_array_free() * Conforms to GDestroyNotify(): * * \param data pointer to Parsed_Setup_Value to clear */ static void destroy_parsed_setvcp_value(gpointer data) { Parsed_Setvcp_Args * psv = (Parsed_Setvcp_Args *) data; free(psv->feature_value); memset(psv, 0, sizeof(Parsed_Setvcp_Args)); } /** Allocates and initializes a #Parsed_Cmd data structure * * \return pointer to initialized #Parsed_Cmd */ Parsed_Cmd * new_parsed_cmd() { // DBGMSG("Starting. file=%s", __FILE__); Parsed_Cmd * parsed_cmd = calloc(1, sizeof(Parsed_Cmd)); memcpy(parsed_cmd->marker, PARSED_CMD_MARKER, 4); // n. all flags are false, byte values 0, integers 0, pointers NULL because of calloc // parsed_cmd->output_level = OL_DEFAULT; parsed_cmd->output_level = DDCA_OL_NORMAL; parsed_cmd->edid_read_size = -1; // if set, values are >= 0 parsed_cmd->sleep_multiplier = 1.0; parsed_cmd->min_dynamic_multiplier = -1.0; parsed_cmd->i2c_bus_check_async_min = -1; parsed_cmd->ddc_check_async_min = -1; parsed_cmd->i1 = -1; // if set, values are >= 0 #ifdef OLD parsed_cmd->flags |= CMD_FLAG_NODETECT; #endif parsed_cmd->setvcp_values = g_array_new(false, // not null-terminated true, // clear to 0's sizeof(Parsed_Setvcp_Args)); g_array_set_clear_func(parsed_cmd->setvcp_values, destroy_parsed_setvcp_value); if (DEFAULT_ENABLE_UDF) parsed_cmd->flags |= CMD_FLAG_ENABLE_UDF; #ifdef ENABLE_USB if (DEFAULT_ENABLE_USB) parsed_cmd->flags |= CMD_FLAG_ENABLE_USB; #endif if (DEFAULT_ENABLE_CACHED_CAPABILITIES) parsed_cmd->flags |= CMD_FLAG_ENABLE_CACHED_CAPABILITIES; // parsed_cmd->watch_mode = Watch_Mode_Dynamic; parsed_cmd->xevent_watch_loop_millisec = DEFAULT_XEVENT_WATCH_LOOP_MILLISEC; parsed_cmd->poll_watch_loop_millisec = DEFAULT_POLL_WATCH_LOOP_MILLISEC; return parsed_cmd; } /** Frees a #Parsed_Cmd data structure * \param parsed_cmd pointer to instance to free */ void free_parsed_cmd(Parsed_Cmd * parsed_cmd) { bool debug = false; DBGMSF(debug, "Starting. parsed_cmd=%p", parsed_cmd); if (parsed_cmd) { assert ( memcmp(parsed_cmd->marker,PARSED_CMD_MARKER,4) == 0); int ndx = 0; for (; ndx < parsed_cmd->argct; ndx++) free(parsed_cmd->args[ndx]); if (parsed_cmd->pdid) free_display_identifier(parsed_cmd->pdid); free(parsed_cmd->raw_command); free(parsed_cmd->failsim_control_fn); free(parsed_cmd->fref); free(parsed_cmd->trace_destination); ntsa_free(parsed_cmd->traced_files, true); ntsa_free(parsed_cmd->traced_functions, true); ntsa_free(parsed_cmd->traced_calls, true); ntsa_free(parsed_cmd->traced_api_calls, true); g_array_free(parsed_cmd->setvcp_values, true); free(parsed_cmd->s1); free(parsed_cmd->s2); free(parsed_cmd->s3); free(parsed_cmd->s4); parsed_cmd->marker[3] = 'x'; free(parsed_cmd); } DBGMSF(debug, "Done"); } static void dbgrpt_ntsa(int depth, char * title, gchar** values) { if (values) { char * joined = g_strjoinv(", ", values); rpt_str(title, NULL, joined, depth); free(joined); } else rpt_str(title, NULL, "none", depth); } #define RPT_CMDFLAG(_desc, _flag, _depth) \ rpt_vstring(_depth, "%-50s : %s", _desc, SBOOL(parsed_cmd->flags & _flag)); #ifdef OLD #define RPT_CMDFLAG(_desc, _flag, _depth) \ rpt_str(_desc, NULL, SBOOL(parsed_cmd->flags & _flag), _depth) #endif #define RPT_CMDFLAG2(_desc, _flag, _depth) \ rpt_str(_desc, NULL, SBOOL(parsed_cmd->flags2 & _flag), _depth) /** Dumps the #Parsed_Command data structure * \param parsed_cmd pointer to instance * \param depth logical indentation depth */ void dbgrpt_parsed_cmd(Parsed_Cmd * parsed_cmd, int depth) { int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("Parsed_Cmd", parsed_cmd, depth); if (parsed_cmd) { rpt_nl(); rpt_label(depth, "General"); rpt_str("raw_command", NULL, parsed_cmd->raw_command, d1); rpt_str("parser mode", NULL, parser_mode_name(parsed_cmd->parser_mode), d1); rpt_int_as_hex( "cmd_id", NULL, parsed_cmd->cmd_id, d1); rpt_int( "argct", NULL, parsed_cmd->argct, d1); int ndx = 0; for (ndx = 0; ndx < parsed_cmd->argct; ndx++) { printf(" argument %d: %s\n", ndx, parsed_cmd->args[ndx]); } rpt_str( "output_level", NULL, output_level_name(parsed_cmd->output_level), d1); rpt_str ("MCCS version spec", NULL, format_vspec(parsed_cmd->mccs_vspec), d1); // rpt_str ("MCCS version id", NULL, vcp_version_id_name(parsed_cmd->mccs_version_id), d1); rpt_nl(); rpt_label(depth, "Commands"); rpt_int("setvcp value count:",NULL, parsed_cmd->setvcp_values->len, d1); for (int ndx = 0; ndx < parsed_cmd->setvcp_values->len; ndx++) { Parsed_Setvcp_Args * elem = &g_array_index(parsed_cmd->setvcp_values, Parsed_Setvcp_Args, ndx); rpt_vstring(d2, "feature_code: 0x%02x, relative: %s, value: %s", elem->feature_code, setvcp_value_type_name(elem->feature_value_type), elem->feature_value); } rpt_nl(); rpt_label(depth, "Behavior modification"); RPT_CMDFLAG("i2c source addr set", CMD_FLAG_EXPLICIT_I2C_SOURCE_ADDR, d1); if (parsed_cmd->flags & CMD_FLAG_EXPLICIT_I2C_SOURCE_ADDR) rpt_vstring(d2, "explicit_i2c_source_addr: 0x%02x", parsed_cmd->explicit_i2c_source_addr); rpt_int( "edid_read_size", NULL, parsed_cmd->edid_read_size, d1); rpt_bool("force_slave_addr", NULL, parsed_cmd->flags & CMD_FLAG_FORCE_SLAVE_ADDR, d1); rpt_bool("verify_setvcp", NULL, parsed_cmd->flags & CMD_FLAG_VERIFY, d1); // rpt_bool("async", NULL, parsed_cmd->flags & CMD_FLAG_ASYNC, d1); rpt_bool("force", NULL, parsed_cmd->flags & CMD_FLAG_FORCE_UNRECOGNIZED_VCP_CODE, d1); rpt_bool("enable udf", NULL, parsed_cmd->flags & CMD_FLAG_ENABLE_UDF, d1); rpt_bool("x52 not fifo:", NULL, parsed_cmd->flags & CMD_FLAG_X52_NO_FIFO, d1); rpt_bool("i2c_io_fileio", NULL, parsed_cmd->flags & CMD_FLAG_I2C_IO_FILEIO,d1); rpt_bool("i2c_io_ioctl", NULL, parsed_cmd->flags & CMD_FLAG_I2C_IO_IOCTL, d1); rpt_bool("enable traced function stack", NULL, parsed_cmd->flags & CMD_FLAG_ENABLE_TRACED_FUNCTION_STACK, d1); //RPT_CMDFLAG("heuristically detect unsupported features", CMD_FLAG_HEURISTIC_UNSUPPORTED_FEATURES, d1); rpt_vstring(d1, "%s: %s", "heuristically detect unsupported features ", SBOOL(parsed_cmd->flags& CMD_FLAG_HEURISTIC_UNSUPPORTED_FEATURES)); rpt_bool("quick", NULL, parsed_cmd->flags & CMD_FLAG_QUICK, d1); RPT_CMDFLAG("watch hotplug events", CMD_FLAG_WATCH_DISPLAY_EVENTS, d1); rpt_vstring(d1, "watch_mode : %s", watch_mode_name(parsed_cmd->watch_mode)); rpt_int( "xevent_watch_loop_millisec", NULL, parsed_cmd->xevent_watch_loop_millisec, d1); rpt_int( "poll_watch_loop_millisec", NULL, parsed_cmd->poll_watch_loop_millisec, d1); RPT_CMDFLAG("disable API", CMD_FLAG_DISABLE_API, d1); rpt_nl(); rpt_label(depth, "Display Selection"); #ifdef ENABLE_USB rpt_bool("enable usb", NULL, parsed_cmd->flags & CMD_FLAG_ENABLE_USB, d1); #endif rpt_structure_loc("pdid", parsed_cmd->pdid, d1); if (parsed_cmd->pdid) dbgrpt_display_identifier(parsed_cmd->pdid, d2); char buf2[BIT_SET_32_MAX+1]; bs32_to_bitstring(parsed_cmd->ignored_hiddevs, buf2, BIT_SET_32_MAX+1); rpt_vstring(d1, "ignored_hiddevs : 0x%08x = |%s|", parsed_cmd->ignored_hiddevs, buf2); rpt_int( "ignored_vid_pid_ct", NULL, parsed_cmd->ignored_usb_vid_pid_ct, d1); for (int ndx = 0; ndx < parsed_cmd->ignored_usb_vid_pid_ct; ndx++) { Vid_Pid_Value v = parsed_cmd->ignored_usb_vid_pids[ndx]; rpt_vstring(d1, "ignored_vid_pids[%d] : %04x:%04x", ndx, VID_PID_VALUE_TO_VID(v), VID_PID_VALUE_TO_PID(v) ); } rpt_nl(); rpt_label(depth, "Feature Selection"); rpt_structure_loc("fref", parsed_cmd->fref, d1); if (parsed_cmd->fref) dbgrpt_feature_set_ref(parsed_cmd->fref, d2); rpt_bool("notable", NULL, parsed_cmd->flags & CMD_FLAG_NOTABLE, d1); rpt_bool("rw only", NULL, parsed_cmd->flags & CMD_FLAG_RW_ONLY, d1); rpt_bool("ro only", NULL, parsed_cmd->flags & CMD_FLAG_RO_ONLY, d1); rpt_bool("wo only", NULL, parsed_cmd->flags & CMD_FLAG_WO_ONLY, d1); rpt_bool("show unsupported", NULL, parsed_cmd->flags & CMD_FLAG_SHOW_UNSUPPORTED, d1); #ifdef REF // Tracing and logging DDCA_Trace_Group traced_groups; gchar ** traced_files; gchar ** traced_functions; gchar ** traced_calls; gchar ** traced_api_calls; char * trace_destination; DDCA_Syslog_Level syslog_level; // Other Development char * failsim_control_fn; #endif rpt_nl(); rpt_label(depth, "Performance and Tuning"); rpt_bool("enable cached capabilities", NULL, parsed_cmd->flags & CMD_FLAG_ENABLE_CACHED_CAPABILITIES, d1); rpt_bool("enable cached displays", NULL, parsed_cmd->flags & CMD_FLAG_ENABLE_CACHED_DISPLAYS, d1); rpt_vstring(d1, "cache types: 0x%02x", parsed_cmd->cache_types); RPT_CMDFLAG("discard caches", CMD_FLAG_DISCARD_CACHES, d1); rpt_vstring(d1, "discarded cache types: 0x%02x", parsed_cmd->discarded_cache_types); // rpt_bool("clear persistent cache:", // NULL, parsed_cmd->flags & CMD_FLAG_CLEAR_PERSISTENT_CACHE, d1); rpt_vstring(d1, "sleep multiplier : %.3f", parsed_cmd->sleep_multiplier); rpt_vstring(d1, "min dynamic sleep multiplier : %.3f", parsed_cmd->min_dynamic_multiplier); rpt_bool("explicit sleep multiplier", NULL, parsed_cmd->flags & CMD_FLAG_EXPLICIT_SLEEP_MULTIPLIER, d1); #ifdef OLD rpt_bool("timeout I2C IO:", NULL, parsed_cmd->flags & CMD_FLAG_TIMEOUT_I2C_IO, d1); rpt_bool("reduce sleeps:", NULL, parsed_cmd->flags & CMD_FLAG_REDUCE_SLEEPS, d1); #endif rpt_bool("defer sleeps", NULL, parsed_cmd->flags & CMD_FLAG_DEFER_SLEEPS, d1); rpt_bool("dsa2 enabled", NULL, parsed_cmd->flags & CMD_FLAG_DSA2, d1); rpt_int("i2c_bus_check_async_min", NULL, parsed_cmd->i2c_bus_check_async_min, d1); rpt_int("ddc_check_async_min", NULL, parsed_cmd->ddc_check_async_min, d1); dbgrpt_ntsa(d1, "ddc_disabled", parsed_cmd->ddc_disabled); rpt_bool("verbose stats:", NULL, parsed_cmd->flags & CMD_FLAG_VERBOSE_STATS, d1); RPT_CMDFLAG("internal stats", CMD_FLAG_INTERNAL_STATS, d1); rpt_int_as_hex( "stats", NULL, parsed_cmd->stats_types, d1); rpt_bool("stats to syslog only", NULL, parsed_cmd->flags & CMD_FLAG_STATS_TO_SYSLOG, d1); char buf[30]; g_snprintf(buf,30, "%d,%d,%d", parsed_cmd->max_tries[0], parsed_cmd->max_tries[1], parsed_cmd->max_tries[2] ); rpt_str("max_retries", NULL, buf, d1); rpt_bool("profile API", NULL, parsed_cmd->flags & CMD_FLAG_PROFILE_API, d1); rpt_nl(); rpt_label(depth, "Tracing and Logging"); rpt_bool("timestamp_trace", NULL, parsed_cmd->flags & CMD_FLAG_TIMESTAMP_TRACE, d1); rpt_int_as_hex( "traced_groups", NULL, parsed_cmd->traced_groups, d1); dbgrpt_ntsa(d1, "traced_functions", parsed_cmd->traced_functions); dbgrpt_ntsa(d1, "traced_files", parsed_cmd->traced_files); dbgrpt_ntsa(d1, "traced_api_calls", parsed_cmd->traced_api_calls); dbgrpt_ntsa(d1, "traced_calls", parsed_cmd->traced_calls); rpt_str ("library trace file", NULL, parsed_cmd->trace_destination, d1); rpt_bool("trace to syslog only", NULL, parsed_cmd->flags & CMD_FLAG_TRACE_TO_SYSLOG_ONLY, d1); rpt_str("syslog_level", NULL, syslog_level_name(parsed_cmd->syslog_level), d1); RPT_CMDFLAG("timestamp prefix", CMD_FLAG_TIMESTAMP_TRACE, d1); RPT_CMDFLAG("walltime prefix", CMD_FLAG_WALLTIME_TRACE, d1); RPT_CMDFLAG("thread id prefix", CMD_FLAG_THREAD_ID_TRACE, d1); RPT_CMDFLAG("process id prefix", CMD_FLAG_PROCESS_ID_TRACE, d1); RPT_CMDFLAG("process id prefix", CMD_FLAG_PROCESS_ID_TRACE, d1); RPT_CMDFLAG("enable traced function stack", CMD_FLAG_ENABLE_TRACED_FUNCTION_STACK, d1); RPT_CMDFLAG("traced function stack errors fatal", CMD_FLAG_TRACED_FUNCTION_STACK_ERRORS_FATAL, d1); rpt_nl(); rpt_label(depth, "Other Development"); rpt_bool("enable_failure_simulation", NULL, parsed_cmd->flags & CMD_FLAG_ENABLE_FAILSIM, d1); rpt_str("failsim_control_fn", NULL, parsed_cmd->failsim_control_fn, d1); rpt_bool("mock data", NULL, parsed_cmd->flags & CMD_FLAG_MOCK, d1); RPT_CMDFLAG("simulate Null Msg indicates unsupported", CMD_FLAG_NULL_MSG_INDICATES_UNSUPPORTED_FEATURE, d1); // rpt_vstring(d1, "%s: %s", "simulate Null Msg indicates unsupported ", // SBOOL(parsed_cmd->flags& CMD_FLAG_NULL_MSG_INDICATES_UNSUPPORTED_FEATURE)); RPT_CMDFLAG("skip ddc checks", CMD_FLAG_SKIP_DDC_CHECKS, d1); RPT_CMDFLAG("async I2C bus checks", CMD_FLAG_ASYNC_I2C_CHECK, d1); RPT_CMDFLAG("enable_flock", CMD_FLAG_FLOCK, d1); RPT_CMDFLAG("try get edid from sysfs", CMD_FLAG_TRY_GET_EDID_FROM_SYSFS, d1); rpt_nl(); rpt_label(depth, "Unsorted"); rpt_bool("ddcdata", NULL, parsed_cmd->flags & CMD_FLAG_DDCDATA, d1); #ifdef OLD rpt_bool("nodetect", NULL, parsed_cmd->flags & CMD_FLAG_NODETECT, d1); #endif rpt_bool("report_freed_exceptions", NULL, parsed_cmd->flags & CMD_FLAG_REPORT_FREED_EXCP, d1); rpt_bool("show settings", NULL, parsed_cmd->flags & CMD_FLAG_SHOW_SETTINGS, d1); #ifdef FUTURE char * interpreted_flags = vnt_interpret_flags(parsed_cmd->flags, cmd_flag_table, false, ", "); rpt_str("flags", NULL, interpreted_flags, d1); free(interpreted_flags); #endif rpt_nl(); rpt_label(depth, "Temporary Utility Variables"); #define RPT_IVAL(_n, _depth) \ do { \ rpt_bool("i"#_n" set", NULL, parsed_cmd->flags2 & CMD_FLAG2_I ## _n ## _SET, _depth); \ if (parsed_cmd->flags2 & CMD_FLAG2_I ## _n ##_SET) { \ rpt_int("i"#_n, NULL, parsed_cmd->i ## _n, _depth); \ rpt_int_as_hex("i" #_n " as hex", NULL, parsed_cmd->i ## _n, _depth); \ } \ } \ while(0) #ifdef OLD rpt_nl(); rpt_label(depth, "Temporary Utility Variables"); rpt_bool("i1 set", NULL, parsed_cmd->flags2 & CMD_FLAG2_I1_SET, d1); if (parsed_cmd->flags2 & CMD_FLAG2_I1_SET) { rpt_int( "i1", NULL, parsed_cmd->i1, d1); rpt_int_as_hex( "i1 as hex", NULL, parsed_cmd->i1, d1); } rpt_bool("i2 set", NULL, parsed_cmd->flags2 & CMD_FLAG2_I2_SET, d1); if (parsed_cmd->flags2 & CMD_FLAG2_I2_SET) { rpt_int( "i2", NULL, parsed_cmd->i2, d1); rpt_int_as_hex( "i2 as hex", NULL, parsed_cmd->i2, d1); } rpt_bool("i3 set", NULL, parsed_cmd->flags2 & CMD_FLAG2_I3_SET, d1); if (parsed_cmd->flags2 & CMD_FLAG2_I3_SET) { rpt_int( "i3", NULL, parsed_cmd->i3, d1); rpt_int_as_hex( "i3 as hex", NULL, parsed_cmd->i3, d1); } #endif RPT_IVAL(1,d1); RPT_IVAL(2,d1); RPT_IVAL(3,d1); RPT_IVAL(4,d1); RPT_IVAL(5,d1); RPT_IVAL(6,d1); RPT_IVAL(7,d1); RPT_IVAL(8,d1); RPT_IVAL(9,d1); RPT_IVAL(11,d1); RPT_IVAL(12,d1); RPT_IVAL(13,d1); RPT_IVAL(14,d1); RPT_IVAL(15,d1); RPT_IVAL(16,d1); #undef RPT_IVAL #define RPT_FVAL(_flagno, _depth) \ rpt_str("f"#_flagno, NULL, SBOOL(parsed_cmd->flags2 & CMD_FLAG2_F##_flagno), _depth) rpt_bool("fl1 set", NULL, parsed_cmd->flags2 & CMD_FLAG2_FL1_SET, d1); if (parsed_cmd->flags2 & CMD_FLAG2_FL1_SET) rpt_vstring(d1, "fl1 : %.2f", parsed_cmd->fl1); rpt_bool("fl2 set", NULL, parsed_cmd->flags2 & CMD_FLAG2_FL2_SET, d1); if (parsed_cmd->flags & CMD_FLAG2_FL2_SET) rpt_vstring(d1, "fl2 : %.2f", parsed_cmd->fl2); rpt_bool("f1", NULL, parsed_cmd->flags2 & CMD_FLAG2_F1, d1); rpt_bool("f2", NULL, parsed_cmd->flags2 & CMD_FLAG2_F2, d1); rpt_bool("f3", NULL, parsed_cmd->flags2 & CMD_FLAG2_F3, d1); rpt_bool("f4", NULL, parsed_cmd->flags2 & CMD_FLAG2_F4, d1); rpt_bool("f5", NULL, parsed_cmd->flags2 & CMD_FLAG2_F5, d1); rpt_bool("f6", NULL, parsed_cmd->flags2 & CMD_FLAG2_F6, d1); rpt_bool("f7", NULL, parsed_cmd->flags2 & CMD_FLAG2_F7, d1); rpt_bool("f8", NULL, parsed_cmd->flags2 & CMD_FLAG2_F8, d1); rpt_bool("f9", NULL, parsed_cmd->flags2 & CMD_FLAG2_F9, d1); RPT_CMDFLAG2("f9", CMD_FLAG2_F9, d1); RPT_CMDFLAG2("f10", CMD_FLAG2_F10, d1); RPT_CMDFLAG2("f11", CMD_FLAG2_F11, d1); RPT_CMDFLAG2("f12", CMD_FLAG2_F12, d1); RPT_CMDFLAG2("f13", CMD_FLAG2_F13, d1); RPT_CMDFLAG2("f14", CMD_FLAG2_F14, d1); RPT_CMDFLAG2("f15", CMD_FLAG2_F15, d1); RPT_CMDFLAG2("f16", CMD_FLAG2_F16, d1); RPT_FVAL(17, d1); RPT_FVAL(18, d1); RPT_FVAL(19, d1); RPT_FVAL(20, d1); RPT_FVAL(21, d1); RPT_FVAL(22, d1); RPT_FVAL(23, d1); RPT_FVAL(24, d1); RPT_FVAL(25, d1); RPT_FVAL(26, d1); RPT_FVAL(27, d1); RPT_FVAL(28, d1); RPT_FVAL(29, d1); RPT_FVAL(30, d1); RPT_FVAL(31, d1); RPT_FVAL(32, d1); #undef RPT_FVAL rpt_str( "s1", NULL, parsed_cmd->s1, d1); rpt_str( "s2", NULL, parsed_cmd->s2, d1); rpt_str( "s3", NULL, parsed_cmd->s3, d1); rpt_str( "s4", NULL, parsed_cmd->s4, d1); } } #ifdef UNUSED void dbgrpt_preparsed_cmd(Preparsed_Cmd * ppc, int depth) { int d1 = depth+1; rpt_structure_loc("Preparsed_Cmd", ppc, depth); if (ppc) { rpt_bool("verbose", NULL, ppc->verbose, d1); rpt_bool("noconfig", NULL, ppc->noconfig, d1); rpt_str("syslog severity", NULL, syslog_level_name(ppc->severity), d1); } } #endif ddcutil-2.2.0/src/cmdline/cmd_parser.h0000644000175000001440000000127214754576332013334 /** @file cmd_parser.h */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later // // This simple interface facilitated switching command parsers during // development. Candidate for removal. // #ifndef CMD_PARSER_H_ #define CMD_PARSER_H_ #include #include "public/ddcutil_types.h" #include "cmdline/parsed_cmd.h" bool parse_syslog_level( const char * sval, DDCA_Syslog_Level * result_loc, GPtrArray * errmsgs); Parsed_Cmd * parse_command( int argc, char * argv[], Parser_Mode parser_mode, GPtrArray * errmsgs); #endif /* CMD_PARSER_H_ */ ddcutil-2.2.0/src/cmdline/cmd_parser_aux.h0000644000175000001440000000360214754576332014210 /** \file cmd_parser_aux.c * * Functions and strings that are independent of the parser package used. */ // Copyright (C) 20014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef CMD_PARSER_AUX_H_ #define CMD_PARSER_AUX_H_ #include #include "cmdline/parsed_cmd.h" void init_cmd_parser_base(); typedef enum { Option_None = 0, Option_Explicit_Display = 1 } Cmd_Supported_Options; typedef struct { int cmd_id; const char * cmd_name; int minchars; int min_arg_ct; int max_arg_ct; Cmd_Supported_Options supported_options; } Cmd_Desc; Cmd_Desc * find_command(char * cmd); Cmd_Desc * get_command(int cmdid); void show_cmd_desc(Cmd_Desc * cmd_desc); // debugging function bool all_digits(char * val, int ct); bool parse_dot_separated_arg( const char * val, int * pv1, int * pv2); bool parse_colon_separated_arg(const char * val, int * pv1, int * pv2); bool parse_colon_separated_vid_pid(const char * val, uint16_t * pv1, uint16_t * pv2); bool parse_int_arg(char * val, int * pIval); bool parse_feature_id_or_subset(char * val, int cmd_id, Feature_Set_Ref * fsref); bool parse_feature_ids(char ** vals, int vals_ct, int cmd_id, Feature_Set_Ref * fsref); Feature_Set_Ref * parse_feature_ids_or_subset(int cmd_id, char **vals, int vals_ct); bool validate_output_level(Parsed_Cmd* parsed_cmd); char * assemble_command_argument_help(); extern char * commands_list_help; extern char * command_argument_help; extern char * monitor_selection_option_help; extern char * tracing_comma_separated_option_help; extern char * tracing_multiple_call_option_help; extern char * trcfunc_multiple_call_option_help; extern char * trcfile_multiple_call_option_help; extern char * stats_multiple_call_option_help; extern char * maxtries_option_help; #endif /* CMD_PARSER_AUX_H_ */ ddcutil-2.2.0/src/cmdline/parsed_cmd.h0000644000175000001440000002615714754576332013327 /** @file parsed_cmd.h */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PARSED_CMD_H_ #define PARSED_CMD_H_ /** \cond */ #include #include /** \endcond */ #include "base/core.h" #include "base/displays.h" #include "base/parms.h" typedef enum { MODE_DDCUTIL, MODE_LIBDDCUTIL } Parser_Mode; typedef enum { CMDID_NONE = 0x0000, CMDID_DETECT = 0x0001, CMDID_CAPABILITIES = 0x0002, CMDID_GETVCP = 0x0004, CMDID_SETVCP = 0x0008, CMDID_LISTVCP = 0x0010, CMDID_TESTCASE = 0x0020, CMDID_LISTTESTS = 0x0040, CMDID_LOADVCP = 0x0080, CMDID_DUMPVCP = 0x0100, #ifdef ENABLE_ENVCMDS CMDID_INTERROGATE = 0x0200, CMDID_ENVIRONMENT = 0x0400, CMDID_USBENV = 0x0800, #endif CMDID_VCPINFO = 0x1000, CMDID_READCHANGES = 0x2000, CMDID_CHKUSBMON = 0x4000, CMDID_PROBE = 0x8000, CMDID_SAVE_SETTINGS = 0x010000, CMDID_DISCARD_CACHE = 0x020000, CMDID_LIST_RTTI = 0x040000, CMDID_NOOP = 0x080000, CMDID_C1 = 0x100000, // utility command id, for tests CMDID_C2 = 0x200000, CMDID_C3 = 0x400000, CMDID_C4 = 0x800000, } Cmd_Id_Type; typedef enum { CMD_FLAG_DDCDATA = 0x0001, CMD_FLAG_FORCE_UNRECOGNIZED_VCP_CODE = 0x0002, CMD_FLAG_FORCE_SLAVE_ADDR = 0x0004, CMD_FLAG_TIMESTAMP_TRACE = 0x0008, // prepend trace and debug msgs with elapsed time CMD_FLAG_SHOW_UNSUPPORTED = 0x0010, CMD_FLAG_ENABLE_FAILSIM = 0x0020, CMD_FLAG_VERIFY = 0x0040, CMD_FLAG_SKIP_DDC_CHECKS = 0x0080, CMD_FLAG_UNUSED1 = 0x0100, CMD_FLAG_REPORT_FREED_EXCP = 0x0200, CMD_FLAG_NOTABLE = 0x0400, CMD_FLAG_THREAD_ID_TRACE = 0x0800, CMD_FLAG_NULL_MSG_INDICATES_UNSUPPORTED_FEATURE = 0x1000, CMD_FLAG_HEURISTIC_UNSUPPORTED_FEATURES = 0x2000, CMD_FLAG_DISCARD_CACHES = 0x4000, CMD_FLAG_PROCESS_ID_TRACE = 0x8000, CMD_FLAG_RW_ONLY = 0x010000, CMD_FLAG_RO_ONLY = 0x020000, CMD_FLAG_WO_ONLY = 0x040000, CMD_FLAG_ASYNC_I2C_CHECK = 0x080000, CMD_FLAG_ENABLE_UDF = 0x100000, CMD_FLAG_ENABLE_USB = 0x200000, CMD_FLAG_TRY_GET_EDID_FROM_SYSFS = 0x10000000, CMD_FLAG_FLOCK = 0x20000000, CMD_FLAG_DEFER_SLEEPS = 0x40000000, CMD_FLAG_X52_NO_FIFO = 0x0100000000, CMD_FLAG_VERBOSE_STATS = 0x0200000000, CMD_FLAG_SHOW_SETTINGS = 0x0400000000, CMD_FLAG_ENABLE_CACHED_CAPABILITIES = 0x0800000000, // CMD_FLAG_CLEAR_PERSISTENT_CACHE // = 0x1000000000, CMD_FLAG_WALLTIME_TRACE = 0x2000000000, CMD_FLAG_I2C_IO_FILEIO = 0x010000000000, CMD_FLAG_I2C_IO_IOCTL = 0x020000000000, CMD_FLAG_EXPLICIT_SLEEP_MULTIPLIER = 0x100000000000, CMD_FLAG_DSA2 = 0x200000000000, CMD_FLAG_QUICK = 0x400000000000, CMD_FLAG_MOCK = 0x01000000000000, CMD_FLAG_PROFILE_API = 0x02000000000000, CMD_FLAG_ENABLE_CACHED_DISPLAYS = 0x10000000000000, CMD_FLAG_TRACE_TO_SYSLOG_ONLY = 0x20000000000000, CMD_FLAG_STATS_TO_SYSLOG = 0x0100000000000000, CMD_FLAG_INTERNAL_STATS = 0x0200000000000000, CMD_FLAG_EXPLICIT_I2C_SOURCE_ADDR = 0x0400000000000000, CMD_FLAG_ENABLE_TRACED_FUNCTION_STACK = 0x1000000000000000, CMD_FLAG_TRACED_FUNCTION_STACK_ERRORS_FATAL = 0x2000000000000000, CMD_FLAG_DISABLE_API = 0x4000000000000000, CMD_FLAG_WATCH_DISPLAY_EVENTS = 0x8000000000000000, #ifdef OLD CMD_FLAG_TIMEOUT_I2C_IO = 0x400000, // UNUSED --timeout-i2c-io CMD_FLAG_REDUCE_SLEEPS = 0x800000, // --sleep-less, etc CMD_FLAG_NODETECT = 0x0080, // UNUSED #endif } Parsed_Cmd_Flags; typedef enum { CMD_FLAG2_F1 = 0x00000001, CMD_FLAG2_F2 = 0x00000002, CMD_FLAG2_F3 = 0x00000004, CMD_FLAG2_F4 = 0x00000008, CMD_FLAG2_F5 = 0x00000010, CMD_FLAG2_F6 = 0x00000020, CMD_FLAG2_F7 = 0x00000040, CMD_FLAG2_F8 = 0x00000080, CMD_FLAG2_F9 = 0x00000100, CMD_FLAG2_F10 = 0x00000200, CMD_FLAG2_F11 = 0x00000400, CMD_FLAG2_F12 = 0x00000800, CMD_FLAG2_F13 = 0x00001000, CMD_FLAG2_F14 = 0x00002000, CMD_FLAG2_F15 = 0x00004000, CMD_FLAG2_F16 = 0x00008000, CMD_FLAG2_F17 = 0x00010000, CMD_FLAG2_F18 = 0x00020000, CMD_FLAG2_F19 = 0x00040000, CMD_FLAG2_F20 = 0x00080000, CMD_FLAG2_F21 = 0x00100000, CMD_FLAG2_F22 = 0x00200000, CMD_FLAG2_F23 = 0x00400000, CMD_FLAG2_F24 = 0x00800000, CMD_FLAG2_F25 = 0x01000000, CMD_FLAG2_F26 = 0x02000000, CMD_FLAG2_F27 = 0x04000000, CMD_FLAG2_F28 = 0x08000000, CMD_FLAG2_F29 = 0x10000000, CMD_FLAG2_F30 = 0x20000000, CMD_FLAG2_F31 = 0x40000000, CMD_FLAG2_F32 = 0x80000000, CMD_FLAG2_I1_SET = 0x010000000000, CMD_FLAG2_I2_SET = 0x020000000000, CMD_FLAG2_I3_SET = 0x040000000000, CMD_FLAG2_I4_SET = 0x080000000000, CMD_FLAG2_I5_SET = 0x100000000000, CMD_FLAG2_I6_SET = 0x200000000000, CMD_FLAG2_I7_SET = 0x400000000000, CMD_FLAG2_I8_SET = 0x800000000000, CMD_FLAG2_I9_SET = 0x01000000000000, CMD_FLAG2_I10_SET = 0x02000000000000, CMD_FLAG2_I11_SET = 0x04000000000000, CMD_FLAG2_I12_SET = 0x08000000000000, CMD_FLAG2_I13_SET = 0x10000000000000, CMD_FLAG2_I14_SET = 0x20000000000000, CMD_FLAG2_I15_SET = 0x40000000000000, CMD_FLAG2_I16_SET = 0x80000000000000, CMD_FLAG2_FL1_SET = 0x1000000000000000, CMD_FLAG2_FL2_SET = 0x2000000000000000, } Parsed_Cmd_Flags2; #define IGNORED_VID_PID_MAX 4 typedef enum {VALUE_TYPE_ABSOLUTE, VALUE_TYPE_RELATIVE_PLUS, VALUE_TYPE_RELATIVE_MINUS } Setvcp_Value_Type; typedef struct { Byte feature_code; Setvcp_Value_Type feature_value_type; char * feature_value; } Parsed_Setvcp_Args; typedef enum {NO_CACHES = 0, CAPABILITIES_CACHE = 1, DISPLAYS_CACHE = 2, DSA2_CACHE = 4, ALL_CACHES = 255 } Cache_Types; /** Parsed arguments to **ddcutil** command */ #define PARSED_CMD_MARKER "PCMD" typedef struct { char marker[4]; // always PCMD // General char * raw_command; Parser_Mode parser_mode; int argct; char * args[MAX_ARGS]; uint64_t flags; // Parsed_Cmd_Flags uint64_t flags2; // Parsed_Cmd_Flags2 DDCA_Output_Level output_level; DDCA_MCCS_Version_Spec mccs_vspec; // DDCA_MCCS_Version_Id mccs_version_id; // Commands Cmd_Id_Type cmd_id; GArray * setvcp_values; // Behavior Modification uint8_t explicit_i2c_source_addr; int edid_read_size; gchar ** ddc_disabled; // Display Selection Display_Identifier* pdid; // Display_Selector* display_selector; // for future use Bit_Set_32 ignored_hiddevs; uint8_t ignored_usb_vid_pid_ct; uint32_t ignored_usb_vid_pids[IGNORED_VID_PID_MAX]; // Feature Selection Feature_Set_Ref* fref; // Performance and Tuning Cache_Types cache_types; Cache_Types discarded_cache_types; uint16_t max_tries[3]; float sleep_multiplier; float min_dynamic_multiplier; DDCA_Stats_Type stats_types; int16_t i2c_bus_check_async_min; int16_t ddc_check_async_min; DDC_Watch_Mode watch_mode; uint16_t xevent_watch_loop_millisec; uint16_t poll_watch_loop_millisec; // Tracing and logging DDCA_Trace_Group traced_groups; gchar ** traced_files; gchar ** traced_functions; gchar ** traced_calls; gchar ** traced_api_calls; char * trace_destination; DDCA_Syslog_Level syslog_level; // Other Development char * failsim_control_fn; // Options for temporary use int i1; // for temporary use int i2; // for temporary use int i3; // for temporary use int i4; // for temporary use int i5; // for temporary use int i6; // for temporary use int i7; // for temporary use int i8; // for temporary use int i9; // for temporary use int i10; // for temporary use int i11; // for temporary use int i12; // for temporary use int i13; // for temporary use int i14; // for temporary use int i15; // for temporary use int i16; // for temporary use char * s1; // for temporary use char * s2; // for temporary use char * s3; // for temporary use char * s4; // for temporary use float fl1; // for temporary use float fl2; // for temporary use } Parsed_Cmd; #ifdef UNUSED /** Preparsed arguments to **ddcutil** command */ typedef struct { DDCA_Syslog_Level severity; bool verbose; bool noconfig; } Preparsed_Cmd; #endif const char * parser_mode_name(Parser_Mode mode); const char * cmdid_name(Cmd_Id_Type id); const char * setvcp_value_type_name(Setvcp_Value_Type value_type); Parsed_Cmd * new_parsed_cmd(); void free_parsed_cmd(Parsed_Cmd * parsed_cmd); void dbgrpt_parsed_cmd(Parsed_Cmd * parsed_cmd, int depth); #endif /* PARSED_CMD_H_ */ ddcutil-2.2.0/src/ddc/0000775000175000001440000000000014754576332010243 5ddcutil-2.2.0/src/ddc/Makefile.am0000644000175000001440000000265414754153540012214 # src/ddc/Makefile.am AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) \ $(JANSSON_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libddc.la libddc_la_SOURCES = \ ddc_common_init.c \ ddc_displays.c \ ddc_display_ref_reports.c \ ddc_display_selection.c \ ddc_dumpload.c \ ddc_initial_checks.c \ ddc_multi_part_io.c \ ddc_output.c \ ddc_packet_io.c \ ddc_phantom_displays.c \ ddc_read_capabilities.c \ ddc_save_current_settings.c \ ddc_serialize.c \ ddc_services.c \ ddc_strategy.c \ ddc_vcp.c \ ddc_vcp_version.c \ ddc_try_data.c # Rename to "all=local" for development all-local-disabled: @echo "" @echo "(src/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" ddcutil-2.2.0/src/ddc/Makefile.in0000664000175000001440000006146114754576155012243 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # src/ddc/Makefile.am VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/ddc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libddc_la_LIBADD = am_libddc_la_OBJECTS = ddc_common_init.lo ddc_displays.lo \ ddc_display_ref_reports.lo ddc_display_selection.lo \ ddc_dumpload.lo ddc_initial_checks.lo ddc_multi_part_io.lo \ ddc_output.lo ddc_packet_io.lo ddc_phantom_displays.lo \ ddc_read_capabilities.lo ddc_save_current_settings.lo \ ddc_serialize.lo ddc_services.lo ddc_strategy.lo ddc_vcp.lo \ ddc_vcp_version.lo ddc_try_data.lo libddc_la_OBJECTS = $(am_libddc_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/ddc_common_init.Plo \ ./$(DEPDIR)/ddc_display_ref_reports.Plo \ ./$(DEPDIR)/ddc_display_selection.Plo \ ./$(DEPDIR)/ddc_displays.Plo ./$(DEPDIR)/ddc_dumpload.Plo \ ./$(DEPDIR)/ddc_initial_checks.Plo \ ./$(DEPDIR)/ddc_multi_part_io.Plo ./$(DEPDIR)/ddc_output.Plo \ ./$(DEPDIR)/ddc_packet_io.Plo \ ./$(DEPDIR)/ddc_phantom_displays.Plo \ ./$(DEPDIR)/ddc_read_capabilities.Plo \ ./$(DEPDIR)/ddc_save_current_settings.Plo \ ./$(DEPDIR)/ddc_serialize.Plo ./$(DEPDIR)/ddc_services.Plo \ ./$(DEPDIR)/ddc_strategy.Plo ./$(DEPDIR)/ddc_try_data.Plo \ ./$(DEPDIR)/ddc_vcp.Plo ./$(DEPDIR)/ddc_vcp_version.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libddc_la_SOURCES) DIST_SOURCES = $(libddc_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) \ $(JANSSON_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libddc.la libddc_la_SOURCES = \ ddc_common_init.c \ ddc_displays.c \ ddc_display_ref_reports.c \ ddc_display_selection.c \ ddc_dumpload.c \ ddc_initial_checks.c \ ddc_multi_part_io.c \ ddc_output.c \ ddc_packet_io.c \ ddc_phantom_displays.c \ ddc_read_capabilities.c \ ddc_save_current_settings.c \ ddc_serialize.c \ ddc_services.c \ ddc_strategy.c \ ddc_vcp.c \ ddc_vcp_version.c \ ddc_try_data.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/ddc/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/ddc/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libddc.la: $(libddc_la_OBJECTS) $(libddc_la_DEPENDENCIES) $(EXTRA_libddc_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libddc_la_OBJECTS) $(libddc_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_common_init.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_display_ref_reports.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_display_selection.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_displays.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_dumpload.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_initial_checks.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_multi_part_io.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_output.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_packet_io.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_phantom_displays.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_read_capabilities.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_save_current_settings.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_serialize.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_strategy.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_try_data.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_vcp.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddc_vcp_version.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/ddc_common_init.Plo -rm -f ./$(DEPDIR)/ddc_display_ref_reports.Plo -rm -f ./$(DEPDIR)/ddc_display_selection.Plo -rm -f ./$(DEPDIR)/ddc_displays.Plo -rm -f ./$(DEPDIR)/ddc_dumpload.Plo -rm -f ./$(DEPDIR)/ddc_initial_checks.Plo -rm -f ./$(DEPDIR)/ddc_multi_part_io.Plo -rm -f ./$(DEPDIR)/ddc_output.Plo -rm -f ./$(DEPDIR)/ddc_packet_io.Plo -rm -f ./$(DEPDIR)/ddc_phantom_displays.Plo -rm -f ./$(DEPDIR)/ddc_read_capabilities.Plo -rm -f ./$(DEPDIR)/ddc_save_current_settings.Plo -rm -f ./$(DEPDIR)/ddc_serialize.Plo -rm -f ./$(DEPDIR)/ddc_services.Plo -rm -f ./$(DEPDIR)/ddc_strategy.Plo -rm -f ./$(DEPDIR)/ddc_try_data.Plo -rm -f ./$(DEPDIR)/ddc_vcp.Plo -rm -f ./$(DEPDIR)/ddc_vcp_version.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/ddc_common_init.Plo -rm -f ./$(DEPDIR)/ddc_display_ref_reports.Plo -rm -f ./$(DEPDIR)/ddc_display_selection.Plo -rm -f ./$(DEPDIR)/ddc_displays.Plo -rm -f ./$(DEPDIR)/ddc_dumpload.Plo -rm -f ./$(DEPDIR)/ddc_initial_checks.Plo -rm -f ./$(DEPDIR)/ddc_multi_part_io.Plo -rm -f ./$(DEPDIR)/ddc_output.Plo -rm -f ./$(DEPDIR)/ddc_packet_io.Plo -rm -f ./$(DEPDIR)/ddc_phantom_displays.Plo -rm -f ./$(DEPDIR)/ddc_read_capabilities.Plo -rm -f ./$(DEPDIR)/ddc_save_current_settings.Plo -rm -f ./$(DEPDIR)/ddc_serialize.Plo -rm -f ./$(DEPDIR)/ddc_services.Plo -rm -f ./$(DEPDIR)/ddc_strategy.Plo -rm -f ./$(DEPDIR)/ddc_try_data.Plo -rm -f ./$(DEPDIR)/ddc_vcp.Plo -rm -f ./$(DEPDIR)/ddc_vcp_version.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Rename to "all=local" for development all-local-disabled: @echo "" @echo "(src/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/ddc/ddc_common_init.c0000644000175000001440000005413514754153540013452 /** @file ddc_common_init.c * Initialization that must be performed very early by both ddcutil and libddcutil */ // Copyright (C) 2021-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later // Contains initialization functions extracted from main.c so they can // be shared with libmain/api.base.c #include #include #include #include #include "config.h" #include "util/debug_util.h" #ifdef ENABLE_FAILSIM #include "util/failsim.h" #endif #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_i2c_util.h" #include "util/timestamp.h" #include "util/traced_function_stack.h" #ifdef USE_LIBDRM #include "util/drm_common.h" #include "util/libdrm_util.h" #endif #include "base/core.h" #include "base/display_retry_data.h" #include "base/dsa2.h" #include "base/drm_connector_state.h" #include "base/flock.h" #include "base/i2c_bus_base.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/per_thread_data.h" #include "base/rtti.h" #include "base/stats.h" #include "base/tuned_sleep.h" #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "vcp/persistent_capabilities.h" #include "dynvcp/dyn_feature_files.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_edid.h" #include "i2c/i2c_execute.h" #include "i2c/i2c_strategy_dispatcher.h" #include "ddc_displays.h" #include "ddc/ddc_initial_checks.h" #include "ddc_multi_part_io.h" #include "ddc/ddc_phantom_displays.h" #include "ddc_serialize.h" #include "ddc_services.h" #include "ddc_try_data.h" #include "ddc_vcp.h" #include "dw/dw_common.h" #include "dw/dw_main.h" #include "dw/dw_poll.h" #include "dw/dw_udev.h" #include "ddc_common_init.h" /** Assembles a #Error_Info struct and appends it to an array. * * @param errinfo_accumulator array of #Error_Info * @param func function generating the error * @param errcode status code * @param format msg template * @param ... substitution arguments */ STATIC void emit_init_tracing_error( GPtrArray* errinfo_accumulator, const char * func, DDCA_Status errcode, const char * format, ...) { assert(errinfo_accumulator); va_list(args); va_start(args, format); char buffer[200]; vsnprintf(buffer, 200, format, args); va_end(args); va_end(args); g_ptr_array_add(errinfo_accumulator, errinfo_new(errcode, func, buffer)); } void i2c_discard_caches(Cache_Types caches) { bool debug = false; if (caches & CAPABILITIES_CACHE) { DBGMSF(debug, "Erasing capabilities cache"); delete_capabilities_file(); } if (caches & DISPLAYS_CACHE) { DBGMSF(debug, "Erasing displays cache"); ddc_erase_displays_cache(); } if (caches & DSA2_CACHE) { DBGMSF(debug, "Erasing dynamic sleep cache"); dsa2_erase_persistent_stats(); } } Error_Info * init_tracing(Parsed_Cmd * parsed_cmd) { bool debug = false; Error_Info * result = NULL; GPtrArray* errinfo_accumulator = g_ptr_array_new_with_free_func((GDestroyNotify) errinfo_free); DBGF(debug, "Starting."); if (parsed_cmd->flags & CMD_FLAG_TIMESTAMP_TRACE) // timestamps on debug and trace messages? dbgtrc_show_time = true; // extern in core.h if (parsed_cmd->flags & CMD_FLAG_WALLTIME_TRACE) // wall timestamps on debug and trace messages? dbgtrc_show_wall_time = true; // extern in core.h if (parsed_cmd->flags & CMD_FLAG_THREAD_ID_TRACE) // thread id on debug and trace messages? dbgtrc_show_thread_id = true; // extern in core.h if (parsed_cmd->flags & CMD_FLAG_PROCESS_ID_TRACE) // process id on debug and trace messages? dbgtrc_show_process_id = true; // extern in core.h if (parsed_cmd->flags & CMD_FLAG_TRACE_TO_SYSLOG_ONLY) dbgtrc_trace_to_syslog_only = true; // extern in core.h report_freed_exceptions = parsed_cmd->flags & CMD_FLAG_REPORT_FREED_EXCP; // extern in core.h add_trace_groups(parsed_cmd->traced_groups); // if (parsed_cmd->s1) // set_trace_destination(parsed_cmd->s1, parser_mode_name(parsed_cmd->parser_mode)); if (parsed_cmd->traced_functions) { for (int ndx = 0; ndx < ntsa_length(parsed_cmd->traced_functions); ndx++) { DBGF(debug, "Adding traced function: %s", parsed_cmd->traced_functions[ndx]); char * curfunc = parsed_cmd->traced_functions[ndx]; bool found = add_traced_function(curfunc); if (!found) { emit_init_tracing_error(errinfo_accumulator, __func__, -EINVAL, "Traced function not found: %s", curfunc); } } } if (parsed_cmd->traced_api_calls) { for (int ndx = 0; ndx < ntsa_length(parsed_cmd->traced_api_calls); ndx++) { char * curfunc = parsed_cmd->traced_api_calls[ndx]; DBGF(debug, "Adding traced api_call: %s", curfunc); bool found = add_traced_api_call(curfunc); if (!found) { emit_init_tracing_error(errinfo_accumulator, __func__, -EINVAL, "Traced API call not found: %s", curfunc); } } } if (parsed_cmd->traced_calls) { for (int ndx = 0; ndx < ntsa_length(parsed_cmd->traced_calls); ndx++) { char * curfunc = parsed_cmd->traced_calls[ndx]; DBGF(debug, "Adding traced call stack function: %s", curfunc); bool found = add_traced_callstack_call(curfunc); if (!found) { emit_init_tracing_error(errinfo_accumulator, __func__, -EINVAL, "Traced call stack function not found: %s", curfunc); } } } if (parsed_cmd->traced_files) { for (int ndx = 0; ndx < ntsa_length(parsed_cmd->traced_files); ndx++) { DBGF(debug, "Adding traced file: %s", parsed_cmd->traced_files[ndx]); add_traced_file(parsed_cmd->traced_files[ndx]); } } ptd_api_profiling_enabled = parsed_cmd->flags & CMD_FLAG_PROFILE_API; // dbgrpt_traced_function_table(2); if (errinfo_accumulator->len > 0) result = errinfo_new_with_causes_gptr( DDCRC_CONFIG_ERROR, errinfo_accumulator, __func__, "Invalid trace option(s):"); g_ptr_array_set_free_func(errinfo_accumulator, (GDestroyNotify) errinfo_free); g_ptr_array_free(errinfo_accumulator, true); traced_function_stack_enabled = parsed_cmd->flags & CMD_FLAG_ENABLE_TRACED_FUNCTION_STACK; traced_function_stack_errors_fatal = parsed_cmd->flags & CMD_FLAG_TRACED_FUNCTION_STACK_ERRORS_FATAL; if (parsed_cmd->flags2 & CMD_FLAG2_F26) traced_function_stack_errors_fatal = true; tracing_initialized = true; return result; } STATIC Error_Info * init_disabled_displays(Parsed_Cmd * parsed_cmd) { bool debug = false; Error_Info * errinfo = NULL; GPtrArray* errinfo_accumulator = g_ptr_array_new_with_free_func((GDestroyNotify) errinfo_free); if (parsed_cmd->ddc_disabled) { for (int ndx = 0; ndx < ntsa_length(parsed_cmd->ddc_disabled); ndx++) { // DBGF(debug, "Adding disabled_mmid: %s", parsed_cmd->ddc_disabled[ndx]); char * cur_mmid = parsed_cmd->ddc_disabled[ndx]; bool found = add_disabled_mmk_by_string(cur_mmid); if (!found) { Error_Info * err = errinfo_new(DDCRC_CONFIG_ERROR, "Invalid mmid: %s", cur_mmid); g_ptr_array_add(errinfo_accumulator, err); } } } if (debug) dbgrpt_ddc_disabled_table(2); if (errinfo_accumulator->len > 0) errinfo = errinfo_new_with_causes_gptr( DDCRC_CONFIG_ERROR, errinfo_accumulator, __func__, "Invalid mmid(s):"); g_ptr_array_free(errinfo_accumulator, true); return errinfo; } STATIC Error_Info * init_failsim(Parsed_Cmd * parsed_cmd) { Error_Info * result = NULL; #ifdef ENABLE_FAILSIM fsim_set_name_to_number_funcs( status_name_to_modulated_number, status_name_to_unmodulated_number); if (parsed_cmd->failsim_control_fn) { bool loaded = fsim_load_control_file(parsed_cmd->failsim_control_fn); if (loaded) { printf("Loaded failure simulation control file %s\n", parsed_cmd->failsim_control_fn); fsim_report_failure_simulation_table(2); } else { // fprintf(stderr, "Error loading failure simulation control file %s.\n", // parsed_cmd->failsim_control_fn); result = ERRINFO_NEW(DDCRC_CONFIG_ERROR, "Error loading failure simulation control file %s", parsed_cmd->failsim_control_fn); } } #endif return result; } STATIC void init_max_tries(Parsed_Cmd * parsed_cmd) { // n. MAX_MAX_TRIES checked during command line parsing if (parsed_cmd->max_tries[0] > 0) { // resets highest, lowest: try_data_init_retry_type(WRITE_ONLY_TRIES_OP, parsed_cmd->max_tries[0]); // redundant drd_set_default_max_tries(0, parsed_cmd->max_tries[0]); // drd_set_initial_display_max_tries(0, parsed_cmd->max_tries[0]); } if (parsed_cmd->max_tries[1] > 0) { try_data_init_retry_type(WRITE_READ_TRIES_OP, parsed_cmd->max_tries[1]); drd_set_default_max_tries(1, parsed_cmd->max_tries[1]); // drd_set_initial_display_max_tries(1, parsed_cmd->max_tries[1]); } if (parsed_cmd->max_tries[2] > 0) { try_data_init_retry_type(MULTI_PART_READ_OP, parsed_cmd->max_tries[2]); try_data_init_retry_type(MULTI_PART_WRITE_OP, parsed_cmd->max_tries[2]); drd_set_default_max_tries(MULTI_PART_READ_OP, parsed_cmd->max_tries[2]); // drd_set_initial_display_max_tries(2, parsed_cmd->max_tries[2]); // impedance match drd_set_default_max_tries(MULTI_PART_WRITE_OP, parsed_cmd->max_tries[2]); // drd_set_initial_display_max_tries(3, parsed_cmd->max_tries[2]); } } STATIC void init_performance_options(Parsed_Cmd * parsed_cmd) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "deferred sleeps: %s, sleep_multiplier: %5.2f", SBOOL(parsed_cmd->flags & CMD_FLAG_DEFER_SLEEPS), parsed_cmd->sleep_multiplier); enable_deferred_sleep( parsed_cmd->flags & CMD_FLAG_DEFER_SLEEPS); #ifdef OLD int threshold = DISPLAY_CHECK_ASYNC_NEVER; if (parsed_cmd->flags & CMD_FLAG_ASYNC) { threshold = DEFAULT_DDC_CHECK_ASYNC_MIN; ddc_set_async_threshold(threshold); } if (parsed_cmd->flags & CMD_FLAG_I3_SET) { ddc_set_async_threshold(parsed_cmd->i3); } if (parsed_cmd->flags & CMD_FLAG_ASYNC_I2C_CHECK) i2c_businfo_async_threshold = I2C_BUS_CHECK_ASYNC_MIN; else i2c_businfo_async_threshold = 999; #endif int threshold = DEFAULT_BUS_CHECK_ASYNC_THRESHOLD; if (parsed_cmd->i2c_bus_check_async_min >= 0) { threshold = parsed_cmd->i2c_bus_check_async_min; } i2c_businfo_async_threshold = threshold; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "set i2c_businfo_async_threshold = %d", threshold); threshold = DEFAULT_DDC_CHECK_ASYNC_THRESHOLD; if (parsed_cmd->ddc_check_async_min >= 0) { threshold= parsed_cmd->ddc_check_async_min; } ddc_set_async_threshold(threshold); // DBGMSG("called ddc_set_async_threshold(%d)", threshold); if (parsed_cmd->sleep_multiplier >= 0) { User_Multiplier_Source source = (parsed_cmd->flags & CMD_FLAG_EXPLICIT_SLEEP_MULTIPLIER) ? Explicit : Default; pdd_set_default_sleep_multiplier_factor(parsed_cmd->sleep_multiplier, source); } bool dsa2_enabled = parsed_cmd->flags & CMD_FLAG_DSA2; dsa2_enable(dsa2_enabled); if (dsa2_enabled) { if (parsed_cmd->flags & CMD_FLAG_EXPLICIT_SLEEP_MULTIPLIER) { dsa2_reset_multiplier(parsed_cmd->sleep_multiplier); dsa2_erase_persistent_stats(); } else { Error_Info * stats_errs = dsa2_restore_persistent_stats(); if (stats_errs) { // for now, just dump to terminal rpt_vstring(0, stats_errs->detail); for (int ndx = 0; ndx < stats_errs->cause_ct; ndx++) { rpt_vstring(1, stats_errs->causes[ndx]->detail); } errinfo_free(stats_errs); } } if (parsed_cmd->min_dynamic_multiplier >= 0.0f) { dsa2_step_floor = dsa2_multiplier_to_step(parsed_cmd->min_dynamic_multiplier); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "min_dynamic_multiplier = %3.1f, setting dsa2_step_floor = %d", parsed_cmd->min_dynamic_multiplier, dsa2_step_floor); } } else { // dsa2_erase_persistent_stats(); // do i want to do this ? } if (display_caching_enabled) ddc_restore_displays_cache(); // else // ddc_erase_displays_cache(); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } STATIC void init_display_watch_options(Parsed_Cmd* parsed_cmd) { watch_displays_mode = parsed_cmd->watch_mode; enable_watch_displays = parsed_cmd->flags & CMD_FLAG_WATCH_DISPLAY_EVENTS; poll_watch_loop_millisec = parsed_cmd->poll_watch_loop_millisec; xevent_watch_loop_millisec = parsed_cmd->xevent_watch_loop_millisec; if (parsed_cmd->i8 >= 0 && (parsed_cmd->flags2 & CMD_FLAG2_I8_SET)) udev_watch_loop_millisec = parsed_cmd->i8; if (parsed_cmd->flags2 & CMD_FLAG2_F18) report_udev_events = true; if (parsed_cmd->flags2 & CMD_FLAG2_I1_SET) initial_stabilization_millisec = parsed_cmd->i1; if (parsed_cmd->i7 >= 0 && (parsed_cmd->flags2 & CMD_FLAG2_I7_SET)) stabilization_poll_millisec = parsed_cmd->i7; } STATIC void init_algorithm_options(Parsed_Cmd * parsed_cmd) { try_get_edid_from_sysfs_first = parsed_cmd->flags & CMD_FLAG_TRY_GET_EDID_FROM_SYSFS; if (parsed_cmd->flags2 & CMD_FLAG2_F17) use_sysfs_connector_id = false; force_sysfs_unreliable = parsed_cmd->flags2 & CMD_FLAG2_F21; force_sysfs_reliable = parsed_cmd->flags2 & CMD_FLAG2_F22; use_x37_detection_table = !(parsed_cmd->flags2 & CMD_FLAG2_F20); } STATIC void init_experimental_options(Parsed_Cmd* parsed_cmd) { suppress_se_post_read = parsed_cmd->flags2 & CMD_FLAG2_F1; ddc_never_uses_null_response_for_unsupported = parsed_cmd->flags2 & CMD_FLAG2_F3; // ddc_always_uses_null_response_for_unsupported = parsed_cmd->flags2 & CMD_FLAG2_F8; if (parsed_cmd->flags2 & CMD_FLAG2_F5) EDID_Read_Uses_I2C_Layer = !EDID_Read_Uses_I2C_Layer; if (parsed_cmd->flags2 & CMD_FLAG2_F6) use_drm_connector_states = true; if (parsed_cmd->flags2 & CMD_FLAG2_F7) detect_phantom_displays = false; if (parsed_cmd->flags2 & CMD_FLAG2_F9) msg_to_syslog_only = true; ddc_enable_displays_cache(parsed_cmd->flags & (CMD_FLAG_ENABLE_CACHED_DISPLAYS)); // was CMD_FLAG_ENABLE_CACHED_DISPLAYS if (parsed_cmd->flags2 & CMD_FLAG2_F10) null_msg_adjustment_enabled = true; if (parsed_cmd->flags2 & CMD_FLAG2_F11) monitor_state_tests = true; if (parsed_cmd->flags2 & CMD_FLAG2_F14) debug_flock = true; if (parsed_cmd->flags2 & CMD_FLAG2_F16) tag_output = true; #ifdef TEST_EDID_SMBUS if (parsed_cmd->flags & CMD_FLAG_F13) EDID_Read_Uses_Smbus = true; #endif #ifdef GET_EDID_USING_SYSFS if (parsed_cmd->flags2 & CMD_FLAG2_F15) verify_sysfs_edid = true; #endif if (parsed_cmd->flags2 & CMD_FLAG2_F19) stabilize_added_buses_w_edid = true; if (parsed_cmd->flags2 & CMD_FLAG2_F23) primitive_sysfs = true; if (parsed_cmd->flags2 & CMD_FLAG2_F24) enable_write_detect_to_status = true; if (parsed_cmd->flags2 & CMD_FLAG2_I2_SET) multi_part_null_adjustment_millis = parsed_cmd->i2; if (parsed_cmd->flags2 & CMD_FLAG2_I3_SET) flock_poll_millisec = parsed_cmd->i3; if (parsed_cmd->flags2 & CMD_FLAG2_I4_SET) flock_max_wait_millisec = parsed_cmd->i4; // if (parsed_cmd->flags & CMD_FLAG_FL1_SET) // dsa2_step_floor = dsa2_multiplier_to_step(parsed_cmd->fl1); if (parsed_cmd->flags2 & CMD_FLAG2_I5_SET) { if (parsed_cmd->i5 >= 1) max_setvcp_verify_tries = parsed_cmd->i5; else rpt_label(0, "--i5 value must be greater than 1"); } } /** Initialization code common to the standalone program ddcutil and * the shared library libddcutil. Called from both main.c and api.base.c. * * @param parsed_cmd parsed command * @return ok if initialization succeeded, false if not */ Error_Info * submaster_initializer(Parsed_Cmd * parsed_cmd) { assert(tracing_initialized); // Full tracing services now available bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDC, "parsed_cmd = %p", parsed_cmd); Error_Info * final_result = NULL; redirect_reports_to_syslog = parsed_cmd->flags2 & CMD_FLAG2_F8; final_result = init_failsim(parsed_cmd); if (final_result) goto bye; // main_rc == EXIT_FAILURE final_result = init_disabled_displays(parsed_cmd); if (parsed_cmd->flags & CMD_FLAG_NULL_MSG_INDICATES_UNSUPPORTED_FEATURE) { DBGMSF(debug, "setting simulate_null_msg_means_unspported = true"); simulate_null_msg_means_unsupported = true; } // global variable in dyn_dynamic_features: enable_dynamic_features = parsed_cmd->flags & CMD_FLAG_ENABLE_UDF; if (parsed_cmd->edid_read_size >= 0) EDID_Read_Size = parsed_cmd->edid_read_size; if (parsed_cmd->flags & CMD_FLAG_I2C_IO_FILEIO) i2c_set_io_strategy_by_id(I2C_IO_STRATEGY_FILEIO); if (parsed_cmd->flags & CMD_FLAG_I2C_IO_IOCTL) i2c_set_io_strategy_by_id(I2C_IO_STRATEGY_IOCTL); i2c_enable_cross_instance_locks(parsed_cmd->flags & CMD_FLAG_FLOCK); setvcp_verify_default = parsed_cmd->flags & CMD_FLAG_VERIFY; // for new threads ddc_set_verify_setvcp(setvcp_verify_default); // set current thread set_output_level(parsed_cmd->output_level); // current thread set_default_thread_output_level(parsed_cmd->output_level); // for future threads enable_report_ddc_errors( parsed_cmd->flags & CMD_FLAG_DDCDATA ); // TMI: // if (show_recoverable_errors) // parsed_cmd->stats = true; char * expected_architectures[] = {"x86_64", "i386", "i686", "armv7l", "aarch64", "ppc64", NULL}; char * architecture = execute_shell_cmd_one_line_result("uname -m"); // char * distributor_id = execute_shell_cmd_one_line_result("lsb_release -s -i"); // e.g. Ubuntu, Raspbian if (ntsa_find(expected_architectures, architecture) >= 0) { DBGTRC_NOPREFIX(debug, DDCA_TRC_DDC, "Found a known architecture: %s", architecture); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_DDC, "Unexpected architecture %s. Please report.", architecture); SYSLOG2(DDCA_SYSLOG_ERROR, "Unexpected architecture %s.", architecture); } // bool is_raspbian = distributor_id && streq(distributor_id, "Raspbian"); bool is_arm = architecture && ( str_starts_with(architecture, "arm") || str_starts_with(architecture, "aarch") ); free(architecture); // free(distributor_id); if (is_arm) primitive_sysfs = true; uint64_t t0; uint64_t t1; all_video_adapters_implement_drm = false; #ifdef USE_LIBDRM // For each video adapter node in sysfs, check that subdirectories drm/cardN/cardN-xxx exist t0 = cur_realtime_nanosec(); all_video_adapters_implement_drm = check_all_video_adapters_implement_drm(); // in i2c_sysfs.c t1 = cur_realtime_nanosec(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "check_all_video_adapters_implement_drm() returned %s in %"PRIu64" microsec", sbool(all_video_adapters_implement_drm), NANOS2MICROS(t1-t0)); #ifdef OUT // Fails if nvidia driver, adapter path not filled in // Gets a list of video adapter paths from the Sys_I2C_Info array and checks if each // supports DRM by checking that subdirectories drm/cardN/cardNxxx exist. bool result3 = all_sysfs_i2c_info_drm(/*rescan=*/false); // in i2c_sysfs.c DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "all_sysfs_i2c_info_drm() returned %s", sbool(result3)); #endif if (parsed_cmd->flags2 & CMD_FLAG2_F12) all_video_adapters_implement_drm = false; #endif subinit_i2c_bus_core(); // rpt_nl(); // get_sys_drm_connectors(false); // initializes global sys_drm_connectors if (use_drm_connector_states) redetect_drm_connector_states(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "use_drm_connector_states=%s, drm_enabled = %s", sbool(use_drm_connector_states), sbool(all_video_adapters_implement_drm)); #ifdef NOT_HERE // adding or removing MST device can change whether all drm connectors have connector_id all_drm_connectors_have_connector_id = all_sys_drm_connectors_have_connector_id(false); bool all2 = all_sys_drm_connectors_have_connector_id_direct(); assert(all2 == all_drm_connectors_have_connector_id); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "all_drm_connectors_have_connector_id = %s", SBOOL(all_drm_connectors_have_connector_id)); // all_drm_connectors_have_connector_id = all_drm_connectors_have_connector_id && (parsed_cmd->flags2 & CMD_FLAG2_F17); #endif init_max_tries(parsed_cmd); enable_mock_data = parsed_cmd->flags & CMD_FLAG_MOCK; (void) ddc_enable_usb_display_detection( parsed_cmd->flags & CMD_FLAG_ENABLE_USB ); if (parsed_cmd->flags & CMD_FLAG_DISCARD_CACHES) { i2c_discard_caches(parsed_cmd->discarded_cache_types); } // if (parsed_cmd->flags & CMD_FLAG2_F16) // dbgrpt_sysfs_basic_connector_attributes(1); init_performance_options(parsed_cmd); enable_capabilities_cache(parsed_cmd->flags & CMD_FLAG_ENABLE_CACHED_CAPABILITIES); skip_ddc_checks = parsed_cmd->flags & CMD_FLAG_SKIP_DDC_CHECKS; #ifdef BUILD_SHARED_LIB library_disabled = parsed_cmd->flags & CMD_FLAG_DISABLE_API; #endif rpt_set_default_ornamentation_enabled(true); // applies to all new threads rpt_set_ornamentation_enabled(true); // current thread init_display_watch_options(parsed_cmd); init_algorithm_options(parsed_cmd); init_experimental_options(parsed_cmd); bye: DBGTRC_RET_ERRINFO(debug, DDCA_TRC_DDC, final_result, ""); return final_result; } void init_ddc_common_init() { RTTI_ADD_FUNC(submaster_initializer); RTTI_ADD_FUNC(init_performance_options); } ddcutil-2.2.0/src/ddc/ddc_displays.c0000644000175000001440000007673514754153540013001 /** @file ddc_displays.c * * Access displays, whether DDC or USB * * This file and ddc_display_ref_reports.c cross-reference each other. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #ifdef USE_X11 #include #endif #include "config.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/drm_common.h" #include "util/edid.h" #include "util/error_info.h" #include "util/failsim.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/traced_function_stack.h" #ifdef ENABLE_UDEV #include "util/udev_usb_util.h" #include "util/udev_util.h" #endif #ifdef USE_X11 #include "util/x11_util.h" #endif /** \endcond */ #include "public/ddcutil_types.h" #include "base/core.h" #include "base/ddc_packets.h" #include "base/drm_connector_state.h" #include "base/dsa2.h" #include "base/feature_metadata.h" #include "base/linux_errno.h" #include "base/monitor_model_key.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/rtti.h" #include "vcp/vcp_feature_codes.h" #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "sysfs/sysfs_base.h" // for is_sysfs_unreliable() #include "i2c/i2c_bus_core.h" #include "i2c/i2c_strategy_dispatcher.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #endif #include "dynvcp/dyn_feature_files.h" #include "ddc/ddc_display_ref_reports.h" #include "ddc/ddc_initial_checks.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_phantom_displays.h" #include "ddc/ddc_serialize.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" // #include "ddc/ddc_dw_main.h" #include "ddc/ddc_displays.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; GPtrArray * display_open_errors = NULL; // array of Bus_Open_Error static int ddc_detect_async_threshold = DEFAULT_DDC_CHECK_ASYNC_THRESHOLD; #ifdef ENABLE_USB static bool detect_usb_displays = true; #else static bool detect_usb_displays = false; #endif #ifdef DONT_CHECK_EDID static bool allow_asleep = true; #endif // Externally visible globals: int dispno_max = 0; // highest assigned display number bool publish_all_display_refs = false; // hack for command C1 /** Performs initial checks in a thread * * @param data display reference */ STATIC void * threaded_initial_checks_by_dref(gpointer data) { bool debug = false; Display_Ref * dref = data; TRACED_ASSERT(memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0 ); DBGTRC_STARTING(debug, TRACE_GROUP, "dref = %s", dref_repr_t(dref) ); Error_Info * erec = ddc_initial_checks_by_dref(dref, false); // g_thread_exit(NULL); ERRINFO_FREE_WITH_REPORT(erec, debug); DBGTRC_DONE(debug, TRACE_GROUP, "Returning NULL. dref = %s,", dref_repr_t(dref) ); free_current_traced_function_stack(); return NULL; } /** Spawns threads to perform initial checks and waits for them all to complete. * * @param all_displays #GPtrArray of pointers to #Display_Ref */ STATIC void ddc_async_scan(GPtrArray * all_displays) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "all_displays=%p, display_count=%d", all_displays, all_displays->len); GPtrArray * threads = g_ptr_array_new(); for (int ndx = 0; ndx < all_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); TRACED_ASSERT( memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0 ); GThread * th = g_thread_new( dref_repr_t(dref), // thread name threaded_initial_checks_by_dref, dref); // pass pointer to display ref as data g_ptr_array_add(threads, th); } DBGMSF(debug, "Started %d threads", threads->len); for (int ndx = 0; ndx < threads->len; ndx++) { GThread * thread = g_ptr_array_index(threads, ndx); g_thread_join(thread); // implicitly unrefs the GThread } DBGMSF(debug, "Threads joined"); g_ptr_array_free(threads, true); DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Loops through a list of display refs, performing initial checks on each. * * @param all_displays #GPtrArray of pointers to #Display_Ref */ STATIC void ddc_non_async_scan(GPtrArray * all_displays) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "checking %d displays", all_displays->len); for (int ndx = 0; ndx < all_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); TRACED_ASSERT( memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0 ); Error_Info * err = ddc_initial_checks_by_dref(dref, false); free(err); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Functions to get display information // /** Gets a list of all detected displays, whether they support DDC or not. * * Detection must already have occurred. * * @return **GPtrArray of #Display_Ref instances */ GPtrArray * ddc_get_all_display_refs() { // ddc_ensure_displays_detected(); TRACED_ASSERT(all_display_refs); return all_display_refs; } /** Gets a list of all detected displays, optionally excluding those * that are invalid. * * @param include_invalid_displays i.e. displays having EDID but not DDC * @param include_removed_drefs * @return **GPtrArray of #Display_Ref instances */ GPtrArray * ddc_get_filtered_display_refs(bool include_invalid_displays, bool include_removed_drefs) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "include_invalid_displays=%s, include_removed_drefs=%s", sbool(include_invalid_displays), sbool(include_removed_drefs)); TRACED_ASSERT(all_display_refs); GPtrArray * result = g_ptr_array_sized_new(all_display_refs->len); for (int ndx = 0; ndx < all_display_refs->len; ndx++) { Display_Ref * cur = g_ptr_array_index(all_display_refs, ndx); if ((include_invalid_displays || cur->dispno > 0) && (!(cur->flags&DREF_REMOVED) || include_removed_drefs) ) { g_ptr_array_add(result, cur); } } DBGTRC_DONE(debug, TRACE_GROUP, "Returning array of size %d", result->len); if (debug || IS_TRACING()) { ddc_dbgrpt_drefs("Display_Refs:", result, 2); } return result; } #ifdef UNUSED void ddc_dbgrpt_display_refs(bool include_invalid_displays, bool report_businfo, int depth) { GPtrArray * drefs = ddc_get_filtered_display_refs(include_invalid_displays, true); rpt_vstring(depth, "Reporting %d display refs", drefs->len); for (int ndx = 0; ndx < drefs->len; ndx++) { dbgrpt_display_ref(g_ptr_array_index(drefs, ndx), false, depth+1); } g_ptr_array_free(drefs,true); } #endif void ddc_dbgrpt_display_refs_summary(bool include_invalid_displays, bool report_businfo, int depth) { GPtrArray * drefs = ddc_get_filtered_display_refs(include_invalid_displays, /* include removed */ true); // rpt_vstring(depth, "Reporting %d display refs", drefs->len); for (int ndx = 0; ndx < drefs->len; ndx++) { dbgrpt_display_ref_summary(g_ptr_array_index(drefs, ndx), report_businfo, depth); } g_ptr_array_free(drefs,true); } void ddc_dbgrpt_display_refs_terse(bool include_invalid_displays, int depth) { GPtrArray * drefs = ddc_get_filtered_display_refs(include_invalid_displays, /* include removed */ true); // rpt_vstring(depth, "Reporting %d display refs", drefs->len); for (int ndx = 0; ndx < drefs->len; ndx++) { rpt_vstring(depth, "%s", dref_reprx_t(g_ptr_array_index(drefs, ndx))); } g_ptr_array_free(drefs,true); } /** Returns the number of detected displays. * * @param include_invalid_displays * @return number of displays, 0 if display detection has not yet occurred. */ int ddc_get_display_count(bool include_invalid_displays) { int display_ct = -1; if (all_display_refs) { display_ct = 0; for (int ndx=0; ndxlen; ndx++) { Display_Ref * dref = g_ptr_array_index(all_display_refs, ndx); TRACED_ASSERT(memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); if (dref->dispno > 0 || include_invalid_displays) { display_ct++; } } } return display_ct; } /** Returns list of all open() errors encountered during display detection. * * @return **GPtrArray of #Bus_Open_Error. */ GPtrArray * ddc_get_bus_open_errors() { return display_open_errors; } /** Emits a debug report of a list of #Bus_Open_Error. * * @param open_errors array of #Bus_Open_Error * @param depth logical indentation depth */ void dbgrpt_bus_open_errors(GPtrArray * open_errors, int depth) { int d1 = depth+1; if (!open_errors || open_errors->len == 0) { rpt_vstring(depth, "Bus open errors: None"); } else { rpt_vstring(depth, "Bus open errors:"); for (int ndx = 0; ndx < open_errors->len; ndx++) { Bus_Open_Error * cur = g_ptr_array_index(open_errors, ndx); rpt_vstring(d1, "%s bus: %-2d, error: %d, detail: %s", (cur->io_mode == DDCA_IO_I2C) ? "I2C" : "hiddev", cur->devno, cur->error, cur->detail); } } } // // Display Detection // /** Sets the threshold for async display examination. * If the number of /dev/i2c devices for which DDC communication is to be * checked is greater than or equal to the threshold value, examine each * device in a separate thread. * * @param threshold threshold value */ void ddc_set_async_threshold(int threshold) { // DBGMSG("threshold = %d", threshold); ddc_detect_async_threshold = threshold; } static bool all_displays_asleep = true; #ifdef UNUSED Display_Ref * get_display_ref_by_businfo(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno = %d", businfo->busno); Display_Ref * dref = NULL; DBGTRC_DONE(debug, TRACE_GROUP, "dref=%s", dref_repr_t(dref)); return dref; } Display_Ref * detect_display_by_businfo(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno = %d", businfo->busno); Display_Ref * dref = NULL; if ( (businfo->flags & I2C_BUS_ADDR_0X50) && businfo->edid ) { dref = create_bus_display_ref(businfo->busno); dref->dispno = DISPNO_INVALID; // -1, guilty until proven innocent if (businfo->drm_connector_name) { dref->drm_connector = g_strdup(businfo->drm_connector_name); } dref->pedid = copy_parsed_edid(businfo->edid); // needed? dref->mmid = mmk_new(dref->pedid->mfg_id, dref->pedid->model_name, dref->pedid->product_code); dref->detail = businfo; dref->flags |= DREF_DDC_IS_MONITOR_CHECKED; dref->flags |= DREF_DDC_IS_MONITOR; bool asleep = dpms_check_drm_asleep(businfo); if (asleep) { dref->flags |= DREF_DPMS_SUSPEND_STANDBY_OFF; } else { all_displays_asleep = false; } } DBGTRC_DONE(debug, TRACE_GROUP, "dref=%s", dref_repr_t(dref)); return dref; } #endif /** Detects all connected displays by querying the I2C and USB subsystems. * * @param open_errors_loc where to return address of #GPtrArray of #Bus_Open_Error * @return array of #Display_Ref */ GPtrArray * ddc_detect_all_displays(GPtrArray ** i2c_open_errors_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "display_caching_enabled=%s, detect_usb_displays=%s", sbool(display_caching_enabled), sbool(detect_usb_displays)); dispno_max = 0; GPtrArray * bus_open_errors = g_ptr_array_new(); g_ptr_array_set_free_func(bus_open_errors, (GDestroyNotify) free_bus_open_error); GPtrArray * display_list = g_ptr_array_new(); g_ptr_array_set_free_func(display_list, (GDestroyNotify) free_display_ref); int busct = i2c_detect_buses(); DBGTRC(debug, DDCA_TRC_NONE, "i2c_detect_buses() returned: %d", busct); guint busndx = 0; for (busndx=0; busndx < busct; busndx++) { DBGMSF(debug, "busndx = %d", busndx); I2C_Bus_Info * businfo = i2c_get_bus_info_by_index(busndx); // if (IS_DBGTRC(debug, DDCA_TRC_NONE)) // i2c_dbgrpt_bus_info(businfo, 2); if ( businfo->edid ) { Display_Ref * dref = NULL; // Do not restore serialized display ref if slave address x37 inactive // Prevents creating a display ref with stale contents if (display_caching_enabled && (businfo->flags&I2C_BUS_ADDR_X37) ) { dref = copy_display_ref( ddc_find_deserialized_display(businfo->busno, businfo->edid->bytes)); if (dref) dref->detail = businfo; } if (!dref) { dref = create_bus_display_ref(businfo->busno); dref->dispno = DISPNO_INVALID; // -1, guilty until proven innocent if (businfo->drm_connector_name) { dref->drm_connector = g_strdup(businfo->drm_connector_name); } dref->drm_connector_id = businfo->drm_connector_id; dref->pedid = copy_parsed_edid(businfo->edid); dref->mmid = mmk_new(dref->pedid->mfg_id, dref->pedid->model_name, dref->pedid->product_code); dref->detail = businfo; dref->flags |= DREF_DDC_IS_MONITOR_CHECKED; dref->flags |= DREF_DDC_IS_MONITOR; } #ifdef USE_X11 bool asleep = dpms_state&DPMS_STATE_X11_ASLEEP; if (!asleep & !(dpms_state&DPMS_STATE_X11_CHECKED)) { if (dpms_check_drm_asleep_by_dref(dref)) { dpms_state |= DPMS_SOME_DRM_ASLEEP; asleep = true; } else { all_displays_asleep = false; } } #else if (dpms_check_drm_asleep_by_dref(dref)) { dpms_state |= DPMS_SOME_DRM_ASLEEP; dref->flags |= DREF_DPMS_SUSPEND_STANDBY_OFF; } else { all_displays_asleep = false; } #endif // dbgrpt_display_ref(dref,5); g_ptr_array_add(display_list, dref); } else if ( !(businfo->flags & I2C_BUS_ACCESSIBLE) ) { Bus_Open_Error * boe = calloc(1, sizeof(Bus_Open_Error)); boe->io_mode = DDCA_IO_I2C; boe->devno = businfo->busno; boe->error = businfo->open_errno; g_ptr_array_add(bus_open_errors, boe); } } #ifdef ENABLE_USB if (detect_usb_displays) { GPtrArray * usb_monitors = get_usb_monitor_list(); // array of USB_Monitor_Info // DBGMSF(debug, "Found %d USB displays", usb_monitors->len); for (int ndx=0; ndxlen; ndx++) { Usb_Monitor_Info * curmon = g_ptr_array_index(usb_monitors,ndx); TRACED_ASSERT(memcmp(curmon->marker, USB_MONITOR_INFO_MARKER, 4) == 0); Display_Ref * dref = create_usb_display_ref( curmon->hiddev_devinfo->busnum, curmon->hiddev_devinfo->devnum, curmon->hiddev_device_name); dref->dispno = DISPNO_INVALID; // -1 dref->pedid = copy_parsed_edid(curmon->edid); if (dref->pedid) dref->mmid = mmk_new( dref->pedid->mfg_id, dref->pedid->model_name, dref->pedid->product_code); else dref->mmid = mmk_new("UNK", "UNK", 0); // drec->detail.usb_detail = curmon; dref->detail = curmon; dref->flags |= DREF_DDC_IS_MONITOR_CHECKED; dref->flags |= DREF_DDC_IS_MONITOR; #ifdef OUT bool asleep = dpms_state&DPMS_STATE_X11_ASLEEP; if (!asleep & !(dpms_state&DPMS_STATE_X11_CHECKED)) { if (dpms_check_drm_asleep_by_dref(dref)) { dpms_state |= DPMS_SOME_DRM_ASLEEP; asleep = true; } else { all_displays_asleep = false; } } if (asleep) { dref->flags |= DREF_DPMS_SUSPEND_STANDBY_OFF; } #endif #ifdef USE_X11 bool asleep = dpms_state&DPMS_STATE_X11_ASLEEP; if (!asleep & !(dpms_state&DPMS_STATE_X11_CHECKED)) { if (dpms_check_drm_asleep_by_dref(dref)) { dpms_state |= DPMS_SOME_DRM_ASLEEP; asleep = true; } else { all_displays_asleep = false; } } #else if (dpms_check_drm_asleep_by_dref(dref)) { dpms_state |= DPMS_SOME_DRM_ASLEEP; dref->flags |= DREF_DPMS_SUSPEND_STANDBY_OFF; } else { all_displays_asleep = false; } #endif g_ptr_array_add(display_list, dref); } GPtrArray * usb_open_errors = get_usb_open_errors(); if (usb_open_errors && usb_open_errors->len > 0) { for (int ndx = 0; ndx < usb_open_errors->len; ndx++) { Bus_Open_Error * usb_boe = (Bus_Open_Error *) g_ptr_array_index(usb_open_errors, ndx); Bus_Open_Error * boe_copy = calloc(1, sizeof(Bus_Open_Error)); boe_copy->io_mode = DDCA_IO_USB; boe_copy->devno = usb_boe->devno; boe_copy->error = usb_boe->error; boe_copy->detail = usb_boe->detail; g_ptr_array_add(bus_open_errors, boe_copy); } } } #endif if (all_displays_asleep) dpms_state |= DPMS_ALL_DRM_ASLEEP; else dpms_state &= ~DPMS_ALL_DRM_ASLEEP; // verbose output is distracting within scans // saved and reset here so that async threads are not adjusting output level DDCA_Output_Level olev = get_output_level(); if (olev == DDCA_OL_VERBOSE) set_output_level(DDCA_OL_NORMAL); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "display_list->len=%d, ddc_detect_async_threshold=%d", display_list->len, ddc_detect_async_threshold); if (display_list->len >= ddc_detect_async_threshold) ddc_async_scan(display_list); else ddc_non_async_scan(display_list); if (olev == DDCA_OL_VERBOSE) set_output_level(olev); // assign display numbers for (int ndx = 0; ndx < display_list->len; ndx++) { Display_Ref * dref = g_ptr_array_index(display_list, ndx); TRACED_ASSERT( memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0 ); // DBGMSG("dref->flags: %s", interpret_dref_flags_t(dref->flags)); if (!(dref->flags & DREF_DDC_COMMUNICATION_WORKING)) DBGTRC(debug, DDCA_TRC_NONE,"dref=%s, DREF_DDC_COMMUNICATON_WORKING not set", dref_repr_t(dref)); // if (dref->flags & DREF_DPMS_SUSPEND_STANDBY_OFF) // dref->dispno = DISPNO_INVALID; // does this need to be different? if (dref->flags & DREF_DDC_DISABLED) dref->dispno = DISPNO_DDC_DISABLED; else if (dref->flags & DREF_DDC_BUSY) dref->dispno = DISPNO_BUSY; else if (dref->flags & DREF_DDC_COMMUNICATION_WORKING) dref->dispno = ++dispno_max; else { dref->dispno = DISPNO_INVALID; // -1; } } bool phantom_displays_found = filter_phantom_displays(display_list); if (phantom_displays_found) { // in case a display other than the last was marked phantom int next_valid_display = 1; for (int ndx = 0; ndx < display_list->len; ndx++) { Display_Ref * dref = g_ptr_array_index(display_list, ndx); if (dref->dispno > 0) dref->dispno = next_valid_display++; } } if (bus_open_errors->len > 0) { *i2c_open_errors_loc = bus_open_errors; } else { g_ptr_array_free(bus_open_errors, false); *i2c_open_errors_loc = NULL; } if (debug) { DBGMSG("Displays detected:"); ddc_dbgrpt_drefs("display_list:", display_list, 1); dbgrpt_bus_open_errors(*i2c_open_errors_loc, 1); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p, Detected %d valid displays", display_list, dispno_max); return display_list; } /** Initializes the master display list in global variable #all_display_refs * and records open errors in global variable #display_open_errors. * * Does nothing if the list has already been initialized. */ void ddc_ensure_displays_detected() { bool debug = false || debug_locks; DBGTRC_STARTING(debug, TRACE_GROUP, ""); g_mutex_lock(&all_display_refs_mutex); if (!all_display_refs) { // i2c_detect_buses(); // called in ddc_detect_all_displays() all_display_refs = ddc_detect_all_displays(&display_open_errors); if (publish_all_display_refs) { for (int ndx = 0; ndx < all_display_refs->len; ndx++) add_published_dref_id_by_dref(g_ptr_array_index(all_display_refs, ndx)); } } g_mutex_unlock(&all_display_refs_mutex); DBGTRC_DONE(debug, TRACE_GROUP, "all_displays=%p, all_displays has %d displays", all_display_refs, all_display_refs->len); } /** Discards all detected displays. * * - All open displays are closed * - The list of open displays in #all_display_refs is discarded * - The list of errors in #display_open_errors is discarded * - The list of detected I2C buses is discarded * - The USB monitor list is discarded */ void ddc_discard_detected_displays() { bool debug = false || debug_locks; DBGTRC_STARTING(debug, TRACE_GROUP, ""); // grab locks to prevent any opens? ddc_close_all_displays(); #ifdef ENABLE_USB discard_usb_monitor_list(); #endif reset_published_dref_hash(); if (all_display_refs) { for (int ndx = 0; ndx < all_display_refs->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_display_refs, ndx); dref->flags |= DREF_TRANSIENT; // hack to allow all Display References to be freed #ifdef OUT #ifndef NDEBUG DDCA_Status ddcrc = free_display_ref(dref); TRACED_ASSERT(ddcrc==0); #else free_display_ref(dref); #endif #endif } g_mutex_lock(&all_display_refs_mutex); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "calling g_ptr_array_free(all_display_refs, true)..."); g_ptr_array_free(all_display_refs, true); g_mutex_unlock(&all_display_refs_mutex); all_display_refs = NULL; if (display_open_errors) { g_ptr_array_free(display_open_errors, true); display_open_errors = NULL; } } // free_sys_drm_connectors(); i2c_discard_buses(); DBGTRC_DONE(debug, TRACE_GROUP, ""); } #ifdef UNUSED /** Checks that a #Display_Ref is in array **all_displays** * of all valid #Display_Ref values. * * @param dref #Display_Ref * @return true/false */ bool ddc_is_known_display_ref(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%p -> %s", dref, dref_repr_t(dref)); bool result = false; if (all_display_refs) { for (int ndx = 0; ndx < all_display_refs->len; ndx++) { Display_Ref* cur = g_ptr_array_index(all_display_refs, ndx); DBGMSF(debug, "Checking vs valid dref %p", cur); if (cur == dref) { // if (cur->dispno > 0) // why? result = true; break; } } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, "dref=%p, dispno=%d", dref, dref->dispno); return result; } #endif /** Replacement for #ddc_is_valid_display_ref() that returns a status code * indicating why a display ref is invalid. * * @param dref display reference to validate * #param validation_options * @retval DDCRC_OK * @retval DDCRC_ARG dref is null or does not point to a Display_Ref * @retval DDCRC_DISCONNECTED display has been disconnected * @retval DDCRC_DPMS_ASLEEP possible if require_not_asleep == true */ DDCA_Status ddc_validate_display_ref2(Display_Ref * dref, Dref_Validation_Options validation_options) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%p -> %s, validation_options=x%02x", dref, dref_reprx_t(dref), validation_options); assert(all_display_refs); DDCA_Status ddcrc = DDCRC_OK; if (!dref || memcmp(dref->marker, DISPLAY_REF_MARKER, 4) != 0) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Invalid marker"); ddcrc = DDCRC_ARG; } else { if (IS_DBGTRC(debug, DDCA_TRC_NONE)) dbgrpt_display_ref(dref, /*include_businfo*/ false, 1); // int d = (IS_DBGTRC(debug, DDCA_TRC_NONE)) ? 1 : -1; if (dref->flags & DREF_REMOVED) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Already marked removed"); ddcrc = DDCRC_DISCONNECTED; } #ifdef DONT_CHECK_EDID else if (all_video_adapters_implement_drm) { int d = (debug) ? 1 : -1; if (!dref->drm_connector) { // start_capture(DDCA_CAPTURE_STDERR); rpt_vstring(0, "Internal error in %s at line %d in file %s. dref->drm_connector == NULL", __func__, __LINE__, __FILE__); SYSLOG2(DDCA_SYSLOG_ERROR, "Internal error in %s at line %d in file %s. dref->drm_connector == NULL", __func__, __LINE__, __FILE__); dbgrpt_display_ref(dref, true, 1); rpt_nl(); report_sys_drm_connectors(true, 1); // Null_Terminated_String_Array lines = end_capture_as_ntsa(); // for (int ndx=0; lines[ndx]; ndx++) { // LOGABLE_MSG(DDCA_SYSLOG_ERROR, "%s", lines[ndx]); // } // ntsa_free(lines, true); // ddcrc = DDCRC_INTERNAL_ERROR; ddcrc = DDCRC_OK; } else { if (ddcrc == 0 && (validation_options&DREF_VALIDATE_EDID)) { if (is_sysfs_reliable_for_busno(DREF_BUSNO(dref))) { int maxtries = 4; int sleep_millis = 500; for (int tryctr = 0; tryctr < maxtries; tryctr++) { if (tryctr > 0) { // usleep(MILLIS2NANOS(sleep_millis)); DW_SLEEP_MILLIS(sleep_millis, "Reading edid from sysfs"); } possibly_write_detect_to_status_by_dref(dref); if (!RPT_ATTR_EDID(d, NULL, "/sys/class/drm/", dref->drm_connector, "edid") ) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "RPT_ATTR_EDID failed. tryctr=%d", tryctr); ddcrc = DDCRC_DISCONNECTED; } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "RPT_ATTR_EDID succeeded. tryctr=%d", tryctr); ddcrc = DDCRC_OK; break; } } } else { // may be wrong if bug in driver, edid persists after disconnection MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "is_sysfs_reliable_for_busno(%d) returned false. Assuming EDID exists", DREF_BUSNO(dref)); } } } if (ddcrc == 0 && ((validation_options&DREF_VALIDATE_AWAKE) && !allow_asleep)) { if (dpms_check_drm_asleep_by_dref(dref)) ddcrc = DDCRC_DPMS_ASLEEP; } } #endif } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, "dref=%p=%s", dref, dref_reprx_t(dref)); return ddcrc; } /** Indicates whether displays have already been detected * * @return true/false */ bool ddc_displays_already_detected() { bool debug = false; DBGTRC_EXECUTED(debug, TRACE_GROUP, "Returning %s", SBOOL(all_display_refs)); return all_display_refs; } /** Controls whether USB displays are to be detected. * * Must be called before any function that triggers display detection. * * @param onoff true if USB displays are to be detected, false if not * @retval DDCRC_OK normal * @retval DDCRC_INVALID_OPERATION function called after displays have been detected * @retval DDCRC_UNIMPLEMENTED ddcutil was not built with USB support * * @remark * If this function is not called, the default (if built with USB support) is on */ DDCA_Status ddc_enable_usb_display_detection(bool onoff) { bool debug = false; DBGMSF(debug, "Starting. onoff=%s", sbool(onoff)); DDCA_Status rc = DDCRC_UNIMPLEMENTED; #ifdef ENABLE_USB if (ddc_displays_already_detected()) { rc = DDCRC_INVALID_OPERATION; } else { detect_usb_displays = onoff; rc = DDCRC_OK; } #endif DBGMSF(debug, "Done. Returning %s", psc_name_code(rc)); return rc; } #ifdef UNUSED /** Indicates whether USB displays are to be detected * * @return true/false */ bool ddc_is_usb_display_detection_enabled() { return detect_usb_displays; } #endif #ifdef UNUSED /** Tests if communication working for a Display_Ref * * @param dref display reference * @return true/false */ bool is_dref_alive(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s", dref_repr_t(dref)); Display_Handle* dh = NULL; Error_Info * erec = NULL; bool is_alive = true; if (dref->io_path.io_mode == DDCA_IO_I2C) { // punt on DDCA_IO_USB for now bool check_needed = true; if (dref->drm_connector) { char * status = NULL; int depth = ( IS_DBGTRC(debug, TRACE_GROUP) ) ? 2 : -1; RPT_ATTR_TEXT(depth,&status, "/sys/class/drm", dref->drm_connector, "status"); if (!streq(status, "connected")) // WRONG: Nvidia driver always "disconnected", check edid instead check_needed = false; free(status); } if (check_needed) { erec = ddc_open_display(dref, CALLOPT_WAIT, &dh); assert(!erec); Parsed_Nontable_Vcp_Response * parsed_nontable_response = NULL; // vs interpreted .. erec = ddc_get_nontable_vcp_value(dh, 0x10, &parsed_nontable_response); // seen: -ETIMEDOUT, DDCRC_NULL_RESPONSE then -ETIMEDOUT, -EIO, DDCRC_DATA // if (erec && errinfo_all_causes_same_status(erec, 0)) if (erec) is_alive = false; ERRINFO_FREE_WITH_REPORT(erec, IS_DBGTRC(debug, TRACE_GROUP)); ddc_close_display_wo_return(dh); } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, is_alive, ""); return is_alive; } /** Check all display references to determine if they are active. * Sets or clears the DREF_ALIVE flag in the display reference. */ void check_drefs_alive() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); if (ddc_displays_already_detected()) { GPtrArray * all_displays = ddc_get_all_display_refs(); for (int ndx = 0; ndx < all_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); bool alive = is_dref_alive(dref); if (alive != (dref->flags & DREF_ALIVE) ) (void) dref_set_alive(dref, alive); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dref=%s, is_alive=%s", dref_repr_t(dref), SBOOL(dref->flags & DREF_ALIVE)); } } else { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "displays not yet detected"); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } #endif void init_ddc_displays() { RTTI_ADD_FUNC(ddc_async_scan); RTTI_ADD_FUNC(ddc_close_all_displays); RTTI_ADD_FUNC(ddc_detect_all_displays); RTTI_ADD_FUNC(ddc_discard_detected_displays); RTTI_ADD_FUNC(ddc_displays_already_detected); RTTI_ADD_FUNC(ddc_ensure_displays_detected); RTTI_ADD_FUNC(ddc_get_all_display_refs); RTTI_ADD_FUNC(ddc_non_async_scan); RTTI_ADD_FUNC(ddc_validate_display_ref2); RTTI_ADD_FUNC(threaded_initial_checks_by_dref); } void terminate_ddc_displays() { ddc_discard_detected_displays(); } ddcutil-2.2.0/src/ddc/ddc_display_ref_reports.c0000644000175000001440000006751514754153540015224 /** @file ddc_display_ref_reports.c * * Report functions factored out of ddc_displays.c due to size of that file. * ddc_display_ref_reports.c and ddc_displays.c cross-reference each other. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include #include #include #include "util/data_structures.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/dsa2.h" #include "base/monitor_model_key.h" #include "base/monitor_quirks.h" #include "base/per_display_data.h" #include "base/rtti.h" #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_conflicting_drivers.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "sysfs/sysfs_top.h" #include "i2c/i2c_bus_core.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #endif #include "dynvcp/dyn_feature_files.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_display_ref_reports.h" // Default trace class for this file static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; struct Results_Table; // // Display_Ref reports // /** Gets the controller firmware version as a string * * @param dh pointer to display handle * @return pointer to character string, which is valid until the next * call to this function. * * @remark * Consider caching the value in dh->dref */ // static char * get_firmware_version_string_t(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); static GPrivate firmware_version_key = G_PRIVATE_INIT(g_free); char * version = get_thread_fixed_buffer(&firmware_version_key, 40); DDCA_Any_Vcp_Value * valrec = NULL; Public_Status_Code psc = 0; Error_Info * ddc_excp = ddc_get_vcp_value( dh, 0xc9, // firmware detection DDCA_NON_TABLE_VCP_VALUE, &valrec); psc = (ddc_excp) ? ddc_excp->status_code : 0; if (psc != 0) { strcpy(version, "Unspecified"); if (psc != DDCRC_REPORTED_UNSUPPORTED && psc != DDCRC_DETERMINED_UNSUPPORTED) { DBGMSF(debug, "get_vcp_value(0xc9) returned %s", psc_desc(psc)); strcpy(version, "DDC communication failed"); if (debug || IS_TRACING() || is_report_ddc_errors_enabled()) errinfo_report(ddc_excp, 1); } errinfo_free(ddc_excp); } else { g_snprintf(version, 40, "%d.%d", valrec->val.c_nc.sh, valrec->val.c_nc.sl); free_single_vcp_value(valrec); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", version); return version; } /** Gets the controller manufacturer name for an open display. * * @param dh pointer to display handle * @return pointer to character string, which is valid until the next * call to this function. * * @remark * Consider caching the value in dh->dref */ static char * get_controller_mfg_string_t(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh = %s", dh_repr(dh)); const int MFG_NAME_BUF_SIZE = 100; static GPrivate buf_key = G_PRIVATE_INIT(g_free); char * mfg_name_buf = get_thread_fixed_buffer(&buf_key, MFG_NAME_BUF_SIZE); char * mfg_name = NULL; DDCA_Any_Vcp_Value * valrec; DDCA_Status ddcrc = 0; Error_Info * ddc_excp = ddc_get_vcp_value(dh, 0xc8, DDCA_NON_TABLE_VCP_VALUE, &valrec); ddcrc = (ddc_excp) ? ddc_excp->status_code : 0; if (ddcrc == 0) { DDCA_Feature_Value_Entry * vals = pxc8_display_controller_type_values; mfg_name = sl_value_table_lookup( vals, valrec->val.c_nc.sl); if (!mfg_name) { g_snprintf(mfg_name_buf, MFG_NAME_BUF_SIZE, "Unrecognized manufacturer code 0x%02x", valrec->val.c_nc.sl); mfg_name = mfg_name_buf; } free_single_vcp_value(valrec); } else if (ddcrc == DDCRC_REPORTED_UNSUPPORTED || ddcrc == DDCRC_DETERMINED_UNSUPPORTED) { mfg_name = "Unspecified"; errinfo_free(ddc_excp); } else { // if (debug) { // DBGMSG("get_nontable_vcp_value(0xc8) returned %s", psc_desc(ddcrc)); // DBGMSG(" Try errors: %s", errinfo_causes_string(ddc_excp)); // } ERRINFO_FREE_WITH_REPORT(ddc_excp, debug || IS_TRACING() || is_report_ddc_errors_enabled() ); mfg_name = "DDC communication failed"; } DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", mfg_name); return mfg_name; } static void report_drm_dpms_status(int depth, const char * connector_name) { char * drm_dpms = NULL; possibly_write_detect_to_status_by_connector_name(connector_name); RPT_ATTR_TEXT(-1, &drm_dpms, "/sys/class/drm", connector_name, "dpms"); if (drm_dpms && !streq(drm_dpms,"On")) { rpt_vstring(1, "DRM reports the monitor is in a DPMS sleep state (%s).", drm_dpms); free(drm_dpms); } char * drm_enabled = NULL; RPT_ATTR_TEXT(-1, &drm_enabled, "/sys/class/drm", connector_name, "enabled"); if (drm_enabled && !streq(drm_enabled, "enabled")) { rpt_vstring(1, "DRM reports the monitor is %s.", drm_enabled); free(drm_enabled); } char * drm_status = NULL; RPT_ATTR_TEXT(-1, &drm_status, "/sys/class/drm", connector_name, "status"); if (drm_status && !streq(drm_status, "connected")) { rpt_vstring(1, "DRM reports the monitor status is %s.", drm_status); free(drm_status); } } /** Shows information about a display, specified by a #Display_Ref * * This function is used by the DISPLAY command. * * Output is written using report functions * * @param dref pointer to display reference * @param depth logical indentation depth * * @remark * The detail level shown is controlled by the output level setting * for the current thread. */ void ddc_report_display_by_dref(Display_Ref * dref, int depth) { bool debug = false; // DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s, communication flags: %s", // dref_repr_t(dref), dref_basic_flags_t(dref->flags)); DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s", dref_repr_t(dref)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dref->flags: %s", interpret_dref_flags_t(dref->flags)); TRACED_ASSERT(dref && memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); int d1 = depth+1; I2C_Bus_Info * businfo = (dref->io_path.io_mode == DDCA_IO_I2C) ? dref->detail : NULL; TRACED_ASSERT(businfo && memcmp(businfo, I2C_BUS_INFO_MARKER, 4) == 0); switch(dref->dispno) { case DISPNO_DDC_DISABLED: rpt_vstring(depth, "DDC_disabled"); break; case DISPNO_BUSY: // -4 rpt_vstring(depth, "Busy display"); break; case DISPNO_REMOVED: // -3 rpt_vstring(depth, "Removed display"); break; case DISPNO_PHANTOM: // -2 rpt_vstring(depth, "Phantom display"); rpt_vstring(d1, "Associated non-phantom display: %s", dref_short_name_t(dref->actual_display)); break; case DISPNO_INVALID: // -1 rpt_vstring(depth, "Invalid display"); break; case 0: // valid display, no assigned display number d1 = depth; // adjust indent ?? break; default: // normal case rpt_vstring(depth, "Display %d", dref->dispno); } switch(dref->io_path.io_mode) { case DDCA_IO_I2C: { i2c_report_active_bus(businfo, d1); } break; case DDCA_IO_USB: #ifdef ENABLE_USB usb_show_active_display_by_dref(dref, d1); #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif break; } TRACED_ASSERT(dref->flags & (DREF_DDC_COMMUNICATION_CHECKED|DREF_DPMS_SUSPEND_STANDBY_OFF)); DDCA_Output_Level output_level = get_output_level(); Monitor_Model_Key mmk = mmk_value_from_edid(dref->pedid); // DBGMSG("mmk = %s", mmk_repr(mmk) ); if (output_level >= DDCA_OL_NORMAL) { if (!(dref->flags & DREF_DDC_COMMUNICATION_WORKING) ) { char * drm_status = NULL; char * drm_dpms = NULL; char * drm_enabled = NULL; // char * drm_connector_name = i2c_get_drm_connector_name(businfo); char * drm_connector_name = businfo->drm_connector_name; possibly_write_detect_to_status_by_businfo(businfo); if (drm_connector_name) { // would be null for a non drm driver RPT_ATTR_TEXT(-1, &drm_dpms, "/sys/class/drm", drm_connector_name, "dpms"); RPT_ATTR_TEXT(-1, &drm_status, "/sys/class/drm", drm_connector_name, "status"); // connected, disconnected RPT_ATTR_TEXT(-1, &drm_enabled, "/sys/class/drm", drm_connector_name, "enabled"); //enabled, disabled } I2C_Bus_Info * bus_info = dref->detail; if (!(bus_info->flags & I2C_BUS_LVDS_OR_EDP) && bus_info->flags & I2C_BUS_ADDR_X37) { rpt_vstring(d1, "DDC communication failed"); if (output_level >= DDCA_OL_VERBOSE && dref->communication_error_summary) { rpt_vstring(d1, "Failure detail: getvcp of feature x10 returned %s", dref->communication_error_summary); } } char msgbuf[100] = {0}; char * msg = NULL; char * vmsg = NULL; if (dref->dispno == DISPNO_PHANTOM) { if (dref->actual_display) { snprintf(msgbuf, 100, "Use non-phantom device %s", dref_short_name_t(dref->actual_display)); msg = msgbuf; } else { // should never occur msg = "Use non-phantom device"; } } else if (businfo->flags & I2C_BUS_DDC_DISABLED) msg = "DDC communication disabled"; else { // non-phantom if (dref->io_path.io_mode == DDCA_IO_I2C) { #ifdef OLD if (businfo->flags & I2C_BUS_EDP) msg = "This is an eDP laptop display. Laptop displays do not support DDC/CI."; else if (businfo->flags & I2C_BUS_LVDS) msg = "This is a LVDS laptop display. Laptop displays do not support DDC/CI."; else if ( is_laptop_parsed_edid(dref->pedid) ) msg = "This appears to be a laptop display. Laptop displays do not support DDC/CI."; #endif if (businfo->flags & I2C_BUS_LVDS_OR_EDP) msg = "This is a laptop display. Laptop displays do not support DDC/CI."; else if (businfo->flags & I2C_BUS_APPARENT_LAPTOP) msg = "This appears to be a laptop display. Laptop displays do not support DDC/CI."; else if (!(businfo->flags & I2C_BUS_ADDR_X37)) { msg = "This monitor does not support DDC/CI. (I2C slave address x37 is unresponsive.)"; vmsg = "If the monitor's on screen display has a DDC/CI setting, check it is enabled."; } else if (drm_dpms || drm_status || drm_enabled) { if (drm_dpms && !streq(drm_dpms,"On")) { rpt_vstring(d1, "DRM reports the monitor is in a DPMS sleep state (%s).", drm_dpms); } if (drm_enabled && !streq(drm_enabled,"enabled")) { rpt_vstring(d1, "DRM reports the monitor is %s.", drm_enabled); } if (drm_status && !streq(drm_status, "connected")) { rpt_vstring(d1, "DRM reports the monitor status is %s.", drm_status); } } // else if ( curinfo->flags & I2C_BUS_BUSY) { else if ( dref->dispno == DISPNO_BUSY) { rpt_label(d1, "I2C device is busy"); int busno = dref->io_path.path.i2c_busno; GPtrArray * conflicts = collect_conflicting_drivers(busno, -1); if (conflicts && conflicts->len > 0) { // report_conflicting_drivers(conflicts); rpt_vstring(d1, "Likely conflicting drivers: %s", conflicting_driver_names_string_t(conflicts)); free_conflicting_drivers(conflicts); } else { struct stat stat_buf; char buf[20]; g_snprintf(buf, 20, "/dev/bus/ddcci/%d", dref->io_path.path.i2c_busno); // DBGMSG("buf: %s", buf); int rc = stat(buf, &stat_buf); // DBGMSG("stat returned %d", rc); if (rc == 0) rpt_label(d1, "I2C device is busy. Likely conflict with driver ddcci."); } // #ifndef I2C_IO_IOCTL_ONLY msg = "Try using option --force-slave-address"; // #endif } } } if (msg) { rpt_vstring(d1, msg); if (vmsg && output_level >= DDCA_OL_VERBOSE) rpt_vstring(d1, vmsg); if (dref->dispno > 0 && (dref->flags & DREF_DPMS_SUSPEND_STANDBY_OFF)) { report_drm_dpms_status(d1, businfo->drm_connector_name); } } free(drm_dpms); free(drm_status); free(drm_enabled); } // communication not working else { // communication working // if (dref->dispno == DISPNO_PHANTOM) // rpt_vstring(d1, "Associated non-phantom display: %s", dref_repr_t(dref->actual_display)); if (dref->flags & DREF_DPMS_SUSPEND_STANDBY_OFF) { report_drm_dpms_status(1, businfo->drm_connector_name); rpt_label(1, "DDC communication appears to work, but output is likely invalid."); } bool comm_error_occurred = false; DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dref(dref); // DBGMSG("vspec = %d.%d", vspec.major, vspec.minor); if ( vspec.major == 0) { rpt_vstring(d1, "VCP version: Detection failed"); comm_error_occurred = true; } else rpt_vstring(d1, "VCP version: %d.%d", vspec.major, vspec.minor); if (output_level >= DDCA_OL_VERBOSE) { // n. requires write access since may call get_vcp_value(), which does a write Display_Handle * dh = NULL; DBGMSF(debug, "Calling ddc_open_display() ..."); Error_Info * err = ddc_open_display(dref, CALLOPT_NONE, &dh); if (err) { rpt_vstring(d1, "Error opening display %s: %s", dref_short_name_t(dref), psc_desc(err->status_code)); comm_error_occurred = true; errinfo_free(err); err = NULL; } else { // display controller mfg, firmware version rpt_vstring(d1, "Controller mfg: %s", get_controller_mfg_string_t(dh) ); rpt_vstring(d1, "Firmware version: %s", get_firmware_version_string_t(dh)); DBGMSF(debug, "Calling ddc_close_display()..."); ddc_close_display_wo_return(dh); } if (dref->io_path.io_mode != DDCA_IO_USB) { if (dref->flags & DREF_DDC_DOES_NOT_INDICATE_UNSUPPORTED) rpt_vstring(d1, "Unable to determine how monitor reports unsupported features"); else { char * how = "unknown"; // DBGMSG("flags: %s", interpret_dref_flags_t(dref->flags)); if (dref->flags & DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED) how = "invalid feature flag in DDC reply packet"; else if (dref->flags & DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED) how = "DDC Null Message"; else if (dref->flags & DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED) how = "all data bytes 0 in DDC reply packet"; rpt_vstring(d1, "Monitor uses %s to indicate unsupported feature.", how); } } if (dref->pdd->dsa2_enabled) { struct Results_Table * rt = (void *)dref->pdd->dsa2_data; DDCA_Sleep_Multiplier cur_multiplier = dsa2_get_adjusted_sleep_mult(rt); rpt_vstring(1, "Current dynamic sleep adjustment multiplier: %5.2f", cur_multiplier); } } if (comm_error_occurred) { // if (dref->flags & DREF_DPMS_SUSPEND_STANDBY_OFF) { // rpt_vstring(d1, "Display is asleep"); // } } Monitor_Quirk_Data * quirk = get_monitor_quirks(&mmk); if (quirk) { char * msg = NULL; switch(quirk->quirk_type) { case MQ_NONE: break; case MQ_NO_SETTING: msg = "WARNING: Setting feature values has been reported to permanently cripple this monitor!"; break; case MQ_NO_MFG_RANGE: msg = "WARNING: Setting manufacturer reserved features has been reported to permanently cripple this monitor!"; break; case MQ_OTHER: msg = quirk->quirk_msg; } if (msg) rpt_vstring(d1, msg); } } if (output_level >= DDCA_OL_VERBOSE) { char * smmk = mmk_model_id_string(mmk.mfg_id, mmk.model_name, mmk.product_code); rpt_vstring(d1, "Monitor Model Id: %s", smmk); char * fqfn = dfr_find_feature_def_file(smmk); if (fqfn) { rpt_vstring(d1, "Uses feature definition file: %s", fqfn); free(fqfn); } else { rpt_vstring(d1, "Feature definition file %s.mccs not found.", smmk); } free(smmk); } } DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** The following set of definitions and functions, called from ddc_report_displays(), * address a highly unlikely corner case, but one which has been reported. * (See https://github.com/rockowitz/ddcutil/issues/280) * * Normally, the drm connector associated with an I2C bus, e.g. CARD0-DP-1, * is obtained by traversing /sys, starting with /sys/bus/i2c, * using function find_sys_drm_connector_by_busion(). * * However, it is possible that a driver does not put sufficient information * in /sys. This is the case with the proprietary nvidia driver. In this * situation function find_sys_drm_connector_by_edid() is used instead. * However, this method can give the wrong answer if two monitors have the same * EDID, i.e. the EDID inadequately distinguishes monitors. * * In issue #280, the nvidia proprietary driver was in use, and there were two * identical Asus PG239Q monitors. The EDID contained neither an ASCII nor a * binary serial number, and the monitors had the same manufacture year/week, * so the EDIDs were identical. In this case the wrong connector name was * reported for one monitor. * * It is at least possible in this situation to warn the user that the * DRM connector name may be incorrect. */ typedef struct { Byte * edid; ///< 128 byte EDID Bit_Set_256 bus_numbers; ///< numbers of the busses whose monitor has this EDID } EDID_Use_Record; void free_edid_use_record0(EDID_Use_Record * rec, bool free_edid) { if (rec) { if (free_edid) free(rec->edid); free(rec); } } /** Free an EDID_Use_Record but not the underlying edid byte array * * @param rec EDID_Use_Record */ void free_edid_use_record(EDID_Use_Record * rec) { free_edid_use_record0(rec, false); } /** Create array of #Edid_Use_Record */ static GPtrArray * create_edid_use_table() { GPtrArray * result = g_ptr_array_new(); return result; } /** Frees an array of #Edid_Use_Record */ static void free_edid_use_table(GPtrArray* table) { // free's each Edid_Use_Record, but not the edid the records point to g_ptr_array_set_free_func(table, (void*)free_edid_use_record); g_ptr_array_free(table, true); } /** Returns the EDID_Use_Record for a particular EDID. * If one does not yet exist, it is created. * * @param records #GPtrArray of #EDID_Use_Record * @param edid edid to search for * @return #EDID_Use_Record */ static EDID_Use_Record * get_edid_use_record(GPtrArray * records, Byte * edid) { assert(edid); bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "records = %p, records->len = %d, edid -> ...%s", records, records->len, hexstring_t(edid+122,6)); EDID_Use_Record * result = NULL; for (int ndx = 0; ndx < records->len; ndx++) { EDID_Use_Record * cur = g_ptr_array_index(records, ndx); if (memcmp(cur->edid,edid,128) == 0) { result = cur; DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning existing EDID_Use_Record %p for edid %s", cur, hexstring_t(edid+122,6)); break; } } if (!result) { result = calloc(1, sizeof(EDID_Use_Record)); result->edid = edid; DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning new EDID_Use_Record %p for edid %s", result, hexstring_t(edid+122,6) ); g_ptr_array_add(records, result); } return result; } /** Record the #Display_Ref's I2C bus number in the #EDID_Use_Record * for the display. * * @param records #GPtrArray of #EDID_Use_Record * @param dref display reference * * @remark * Does nothing unless the display reference is for an I2C device and the * drm connector was found using the EDID. */ static void record_i2c_edid_use(GPtrArray * edid_use_records, Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "edid_use_records=%p, dref=%s", edid_use_records, dref_repr_t(dref)); if (dref->io_path.io_mode == DDCA_IO_I2C) { I2C_Bus_Info * binfo = (I2C_Bus_Info *) dref->detail; if (binfo -> drm_connector_found_by == DRM_CONNECTOR_FOUND_BY_EDID) { EDID_Use_Record * cur = get_edid_use_record(edid_use_records, binfo->edid->bytes); cur->bus_numbers = bs256_insert(cur->bus_numbers, binfo->busno); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Updated bus list %s for edid %s", bs256_to_string_decimal_t(cur->bus_numbers, NULL, ", "), hexstring_t(binfo->edid->bytes+122,6)); } } DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } /** Report i2c buses having identical EDID, for which the DRM * connector name was found using the EDID * * @param edid_use_records GPtrArray of #EDID_Use_Record * @param depth logical indentation depth */ static void report_ambiguous_connector_for_edid(GPtrArray * edid_use_records, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "edid_use_records->len = %d", edid_use_records->len); for (int ndx = 0; ndx < edid_use_records->len; ndx++) { EDID_Use_Record * cur_use_record = g_ptr_array_index(edid_use_records, ndx); if (bs256_count(cur_use_record->bus_numbers) > 1) { rpt_vstring(depth,"Displays with I2C bus numbers %s have identical EDIDs.", bs256_to_string_decimal_t(cur_use_record->bus_numbers, NULL, ", ")); rpt_label(depth, "DRM connector names may not be accurate."); } } DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } /** Reports all displays found. * * Output is written to the current report destination using report functions. * * @param include_invalid_displays if false, report only valid displays\n * if true, report all displays * @param depth logical indentation depth * * @return total number of displays reported */ int ddc_report_displays(bool include_invalid_displays, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); ddc_ensure_displays_detected(); int display_ct = 0; GPtrArray * all_displays = ddc_get_all_display_refs(); GPtrArray * edid_use_records = create_edid_use_table(); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Created edid_use_records = %p", edid_use_records); for (int ndx=0; ndxlen; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); TRACED_ASSERT(memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); if (dref->dispno > 0 || include_invalid_displays) { display_ct++; ddc_report_display_by_dref(dref, depth); rpt_title("",0); // Note the EDID for each bus record_i2c_edid_use(edid_use_records, dref); } } if (display_ct == 0) { rpt_vstring(depth, "No %sdisplays found.", (!include_invalid_displays) ? "active " : ""); if ( get_output_level() >= DDCA_OL_NORMAL ) { // rpt_label(depth, "Is DDC/CI enabled in the monitor's on screen display?"); rpt_label(depth, "Run \"ddcutil environment\" to check for system configuration problems."); } } else if (get_output_level() >= DDCA_OL_VERBOSE && display_ct > 1) { report_ambiguous_connector_for_edid(edid_use_records, depth); } free_edid_use_table(edid_use_records); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %d", display_ct); return display_ct; } /** Debugging function to display the contents of a #Display_Ref. * * @param dref pointer to #Display_Ref * @param depth logical indentation depth */ void ddc_dbgrpt_display_ref(Display_Ref * dref, int depth) { assert(dref); bool debug = false; DBGMSF(debug, "Starting. dref=%s", dref_repr_t(dref)); int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("Display_Ref", dref, depth); rpt_int("dispno", NULL, dref->dispno, d1); dbgrpt_display_ref(dref, true, d1); rpt_vstring(d1, "io_mode: %s", io_mode_name(dref->io_path.io_mode)); switch(dref->io_path.io_mode) { case(DDCA_IO_I2C): rpt_vstring(d1, "I2C bus information: "); I2C_Bus_Info * businfo = dref->detail; TRACED_ASSERT( memcmp(businfo->marker, I2C_BUS_INFO_MARKER, 4) == 0); i2c_dbgrpt_bus_info(businfo, true, d2); break; case(DDCA_IO_USB): #ifdef ENABLE_USB rpt_vstring(d1, "USB device information: "); Usb_Monitor_Info * moninfo = dref->detail; TRACED_ASSERT(memcmp(moninfo->marker, USB_MONITOR_INFO_MARKER, 4) == 0); dbgrpt_usb_monitor_info(moninfo, d2); #else PROGRAM_LOGIC_ERROR("Built without USB support"); #endif break; } // set_output_level(saved_output_level); DBGMSF(debug, "Done"); } /** Emits a debug report a GPtrArray of display references * * @param msg initial message line * @param ptrarray array of pointers to #Display_Ref * @param depth logical indentation depth */ void ddc_dbgrpt_drefs(char * msg, GPtrArray * ptrarray, int depth) { int d1 = depth + 1; rpt_vstring(depth, "%s", msg); if (ptrarray->len == 0) rpt_vstring(d1, "None"); else { for (int ndx = 0; ndx < ptrarray->len; ndx++) { Display_Ref * dref = g_ptr_array_index(ptrarray, ndx); TRACED_ASSERT(dref); dbgrpt_display_ref(dref, true, d1); } } } #ifdef UNUSED void dbgrpt_valid_display_refs(int depth) { rpt_vstring(depth, "Valid display refs = all_displays:"); if (all_displays) { if (all_displays->len == 0) rpt_vstring(depth+1, "None"); else { for (int ndx = 0; ndx < all_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); rpt_vstring(depth+1, "%p, dispno=%d", dref, dref->dispno); } } } else rpt_vstring(depth+1, "all_displays == NULL"); } #endif void init_ddc_display_ref_reports() { RTTI_ADD_FUNC(ddc_report_display_by_dref); RTTI_ADD_FUNC(ddc_report_displays); RTTI_ADD_FUNC(get_controller_mfg_string_t); RTTI_ADD_FUNC(get_edid_use_record); RTTI_ADD_FUNC(get_firmware_version_string_t); RTTI_ADD_FUNC(record_i2c_edid_use); RTTI_ADD_FUNC(report_ambiguous_connector_for_edid); } ddcutil-2.2.0/src/ddc/ddc_display_selection.c0000644000175000001440000001741514754153540014651 /** @file ddc_display_selection.c */ // Copyright (C) 2022-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include "util/debug_util.h" #include "util/edid.h" #include "util/report_util.h" #include "util/string_util.h" #ifdef ENABLE_UDEV #include "util/udev_usb_util.h" #include "util/udev_util.h" #endif /** \endcond */ #include "public/ddcutil_types.h" #include "base/core.h" #include "base/rtti.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #endif #include "ddc/ddc_display_ref_reports.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_display_selection.h" static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; // // Display Selection // /** Display selection criteria */ typedef struct { int dispno; int i2c_busno; int hiddev; int usb_busno; int usb_devno; char * mfg_id; char * model_name; char * serial_ascii; Byte * edidbytes; } Display_Criteria; /** Allocates a new #Display_Criteria and initializes it to contain no criteria. * * @return initialized #Display_Criteria */ static Display_Criteria * new_display_criteria() { bool debug = false; DBGMSF(debug, "Starting"); Display_Criteria * criteria = calloc(1, sizeof(Display_Criteria)); criteria->dispno = -1; criteria->i2c_busno = -1; criteria->hiddev = -1; criteria->usb_busno = -1; criteria->usb_devno = -1; DBGMSF(debug, "Done. Returning: %p", criteria); return criteria; } /** Checks if a given #Display_Ref satisfies all the criteria specified in a * #Display_Criteria struct. * * @param drec pointer to #Display_Ref to test * @param criteria pointer to criteria * @retval true all specified criteria match * @retval false at least one specified criterion does not match * * @remark * In the degenerate case that no criteria are set in **criteria**, returns true. */ static bool ddc_test_display_ref_criteria(Display_Ref * dref, Display_Criteria * criteria) { TRACED_ASSERT(dref && criteria); bool result = false; if (criteria->dispno >= 0 && criteria->dispno != dref->dispno) goto bye; if (criteria->i2c_busno >= 0) { if (dref->io_path.io_mode != DDCA_IO_I2C || dref->io_path.path.i2c_busno != criteria->i2c_busno) goto bye; } #ifdef ENABLE_USB if (criteria->hiddev >= 0) { if (dref->io_path.io_mode != DDCA_IO_USB) goto bye; char buf[40]; snprintf(buf, 40, "%s/hiddev%d", usb_hiddev_directory(), criteria->hiddev); Usb_Monitor_Info * moninfo = dref->detail; TRACED_ASSERT(memcmp(moninfo->marker, USB_MONITOR_INFO_MARKER, 4) == 0); if (!streq( moninfo->hiddev_device_name, buf)) goto bye; } if (criteria->usb_busno >= 0) { if (dref->io_path.io_mode != DDCA_IO_USB) goto bye; // Usb_Monitor_Info * moninfo = drec->detail2; // assert(memcmp(moninfo->marker, USB_MONITOR_INFO_MARKER, 4) == 0); // if ( moninfo->hiddev_devinfo->busnum != criteria->usb_busno ) if ( dref->usb_bus != criteria->usb_busno ) goto bye; } if (criteria->usb_devno >= 0) { if (dref->io_path.io_mode != DDCA_IO_USB) goto bye; // Usb_Monitor_Info * moninfo = drec->detail2; // assert(memcmp(moninfo->marker, USB_MONITOR_INFO_MARKER, 4) == 0); // if ( moninfo->hiddev_devinfo->devnum != criteria->usb_devno ) if ( dref->usb_device != criteria->usb_devno ) goto bye; } if (criteria->hiddev >= 0) { if (dref->io_path.io_mode != DDCA_IO_USB) goto bye; if ( dref->io_path.path.hiddev_devno != criteria->hiddev ) goto bye; } #endif if (criteria->mfg_id && (strlen(criteria->mfg_id) > 0) && !streq(dref->pedid->mfg_id, criteria->mfg_id) ) goto bye; if (criteria->model_name && (strlen(criteria->model_name) > 0) && !streq(dref->pedid->model_name, criteria->model_name) ) goto bye; if (criteria->serial_ascii && (strlen(criteria->serial_ascii) > 0) && !streq(dref->pedid->serial_ascii, criteria->serial_ascii) ) goto bye; if (criteria->edidbytes && memcmp(dref->pedid->bytes, criteria->edidbytes, 128) != 0) goto bye; result = true; bye: return result; } /** Finds the first display reference satisfying a set of display criteria. * Phantom displays are ignored. * * @param criteria identifiers to check * @return display reference if found, NULL if not */ static Display_Ref * ddc_find_display_ref_by_criteria(Display_Criteria * criteria) { Display_Ref * result = NULL; GPtrArray * all_displays = ddc_get_all_display_refs(); for (int ndx = 0; ndx < all_displays->len; ndx++) { Display_Ref * drec = g_ptr_array_index(all_displays, ndx); TRACED_ASSERT(memcmp(drec->marker, DISPLAY_REF_MARKER, 4) == 0); if (ddc_test_display_ref_criteria(drec, criteria)) { // Ignore the match if it's a phantom display if (drec->dispno != DISPNO_PHANTOM) { result = drec; break; } } } return result; } /** Searches the master display list for a display matching the * specified #Display_Identifier, returning its #Display_Ref. * Phantom displays are ignored. * * @param did display identifier to search for * @return #Display_Ref for the display, NULL if not found or * display doesn't support DDC * * @remark * The returned value is a pointer into an internal data structure * and should not be freed by the caller. */ static Display_Ref * ddc_find_display_ref_by_display_identifier(Display_Identifier * did) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "did=%s", did_repr(did)); if (debug) dbgrpt_display_identifier(did, 1); Display_Ref * result = NULL; Display_Criteria * criteria = new_display_criteria(); switch(did->id_type) { case DISP_ID_BUSNO: criteria->i2c_busno = did->busno; break; case DISP_ID_MONSER: criteria->mfg_id = did->mfg_id; criteria->model_name = did->model_name; criteria->serial_ascii = did->serial_ascii; break; case DISP_ID_EDID: criteria->edidbytes = did->edidbytes; break; case DISP_ID_DISPNO: criteria->dispno = did->dispno; break; case DISP_ID_USB: criteria->usb_busno = did->usb_bus; criteria->usb_devno = did->usb_device; break; case DISP_ID_HIDDEV: criteria->hiddev = did->hiddev_devno; } result = ddc_find_display_ref_by_criteria(criteria); // Is this the best location in the call chain to make this check? if (result && (result->dispno < 0)) { DBGMSF(debug, "Found a display that doesn't support DDC. Ignoring."); result = NULL; } free(criteria); // do not free pointers in criteria, they are owned by Display_Identifier DBGTRC_RET_STRING(debug, DDCA_TRC_NONE, dref_repr_t(result), ""); return result; } /** Searches the detected displays for one matching the criteria in a * #Display_Identifier. Phantom displays are ignored. * * @param pdid pointer to a #Display_Identifier * @param callopts standard call options * @return pointer to #Display_Ref for the display, NULL if not found * * \todo * If the criteria directly specify an access path (e.g. I2C bus number) and * CALLOPT_FORCE is specified, then create a temporary #Display_Ref, * bypassing the list of detected monitors. */ Display_Ref * get_display_ref_for_display_identifier( Display_Identifier* pdid, Call_Options callopts) { Display_Ref * dref = ddc_find_display_ref_by_display_identifier(pdid); return dref; } void init_ddc_display_selection() { RTTI_ADD_FUNC(ddc_find_display_ref_by_display_identifier); } ddcutil-2.2.0/src/ddc/ddc_dumpload.c0000644000175000001440000007417014754153540012745 /** @file dumpload.c * * Load/store VCP settings from/to file. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include "util/error_info.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/glib_string_util.h" #include "util/report_util.h" #include "ddcutil_types.h" /** \endcond */ #include "base/core.h" #include "base/ddc_errno.h" #include "base/ddc_packets.h" #include "base/displays.h" #include "base/monitor_model_key.h" #include "base/parms.h" #include "base/rtti.h" #include "base/status_code_mgt.h" #include "base/vcp_version.h" #include "dynvcp/dyn_feature_codes.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_display_selection.h" #include "ddc/ddc_output.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_read_capabilities.h" #include "ddc/ddc_vcp.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_dumpload.h" static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; /** Frees a #Dumpload_Data struct. The underlying Vcp_Value_set is also freed. * * @param data pointer to #Dumpload_Data struct to free,\n * if NULL, do nothing */ void free_dumpload_data(Dumpload_Data * data) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "data=%p", data); if (data) { if (data->vcp_values) free_vcp_value_set(data->vcp_values); free(data); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Reports the contents of a #Dumpload_Data struct * * @param data pointer to #Dumpload_Data struct * @param depth logical indentation depth */ void dbgrpt_dumpload_data(Dumpload_Data * data, int depth) { int d1 = depth+1; rpt_structure_loc("Dumpload_Data", data, depth); // rptIval("busno", NULL, data->busno, d1); // TODO: timestamp_millis // TODO: show abbreviated edidstr rpt_str( "mfg_id", NULL, data->mfg_id, d1); rpt_str( "model", NULL, data->model, d1); rpt_unsigned( " product_code", NULL, data->product_code, d1); rpt_str( "serial_ascii", NULL, data->serial_ascii, d1); rpt_str( "edid", NULL, data->edidstr, d1); rpt_str( "vcp_version", NULL, format_vspec(data->vcp_version), d1); rpt_int( "vcp_value_ct", NULL, data->vcp_value_ct, d1); rpt_structure_loc("vcp_values", data->vcp_values, d1); if (data->vcp_values) dbgrpt_vcp_value_set(data->vcp_values, d1); } #define ADD_DATA_ERROR(_expl) \ errinfo_add_cause( \ errs, \ errinfo_new( \ DDCRC_BAD_DATA, __func__, \ _expl " at line %d: %s", linectr, line) ); /** Given an array of strings stored in a GPtrArray, * convert it a #Dumpload_Data struct. * * @param garray array of strings * @return pointer to newly allocated Dumpload_Data struct, or * NULL if the data is not valid. * It is the responsibility of the caller to free this struct. */ Error_Info * create_dumpload_data_from_g_ptr_array( GPtrArray * garray, Dumpload_Data ** dumpload_data_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); Error_Info * errs = errinfo_new(DDCRC_BAD_DATA, __func__, NULL); *dumpload_data_loc = NULL; Dumpload_Data * data = calloc(1, sizeof(Dumpload_Data)); #ifndef NDEBUG bool valid_data = true; #endif // default: data->vcp_version.major = 2; data->vcp_version.minor = 0; data->vcp_values = vcp_value_set_new(15); // 15 = initial size int ct; int linectr = 0; while ( linectr < garray->len ) { char * line = NULL; char s0[32], s1[257], s2[16]; char * head; char * rest; line = g_ptr_array_index(garray,linectr); linectr++; *s0 = '\0'; *s1 = '\0'; *s2 = '\0'; head = line; while (*head == ' ') head++; ct = sscanf(head, "%31s %256s %15s", s0, s1, s2); if (ct > 0 && *s0 != '*' && *s0 != '#') { if (ct == 1) { // printf("Invalid data at line %d: %s\n", linectr, line); // Error_Info * err = errinfo_new2( // DDCRC_BAD_DATA, __func__, // "Invalid data at line %d: %s", linectr, line); // errinfo_add_cause(errs, err); ADD_DATA_ERROR("Invalid data"); #ifndef NDEBUG valid_data = false; #endif } else { rest = head + strlen(s0);; while (*rest == ' ') rest++; char * last = rest + strlen(rest) - 1; // we already parsed a second token, so don't need to worry that last becomes < head while (*last == ' ' || *last == '\n') { *last-- = '\0'; } // DBGMSG("rest=|%s|", rest ); if (streq(s0, "BUS")) { // ignore // ct = sscanf(s1, "%d", &data->busno); // if (ct == 0) { // fprintf(stderr, "Invalid bus number at line %d: %s\n", linectr, line); // valid_data = false; // } } else if (streq(s0, "PRODUCT_CODE")) { int ival; bool ok = str_to_int(s1, &ival, 10); if (ok && ival >= 0 && ival <= 65535) data->product_code = (uint16_t) ival; #ifndef NDEBUG else valid_data = false; #endif } else if (streq(s0, "EDID") || streq(s0, "EDIDSTR")) { STRLCPY(data->edidstr, s1, sizeof(data->edidstr)); } else if (streq(s0, "MFG_ID")) { STRLCPY(data->mfg_id, s1, sizeof(data->mfg_id)); } else if (streq(s0, "MODEL")) { STRLCPY(data->model, rest, sizeof(data->model)); } else if (streq(s0, "SN")) { STRLCPY(data->serial_ascii, rest, sizeof(data->serial_ascii)); } else if (streq(s0, "VCP_VERSION")) { data->vcp_version = parse_vspec(s1); // using VCP_SPEC_UNKNOWN as value when invalid, // what if monitor had no version, so 0.0 was output? if ( vcp_version_eq( data->vcp_version, DDCA_VSPEC_UNKNOWN) ) { // f0printf(ferr(), "Invalid VCP VERSION at line %d: %s\n", linectr, line); // errinfo_add_cause( // errs, // errinfo_new2( // DDCRC_BAD_DATA, __func__, // "Invalid VCP VERSION at line %d: %s\n", linectr, line) ); ADD_DATA_ERROR("Invalid VCP VERSION"); #ifndef NDEBUG valid_data = false; #endif } } else if (streq(s0, "TIMESTAMP_TEXT") || streq(s0, "TIMESTAMP_MILLIS") ) { // do nothing, just recognize valid field } else if (streq(s0, "VCP")) { if (ct != 3) { // f0printf(ferr(), "Invalid VCP data at line %d: %s\n", linectr, line); ADD_DATA_ERROR("Invalid VCP data"); #ifndef NDEBUG valid_data = false; #endif } else { // found feature id and value Byte feature_id; bool ok = hhs_to_byte_in_buf(s1, &feature_id); if (!ok) { // f0printf(ferr(), "Invalid opcode at line %d: %s", linectr, s1); ADD_DATA_ERROR("Invalid opcode"); #ifndef NDEBUG valid_data = false; #endif } else { // valid opcode DDCA_Any_Vcp_Value * valrec = NULL; // look up opcode, is it valid? // table values need special handling // Problem: without VCP version, can't look up feature in // VCP code table and definitively know if it's a table feature. // One solution: rework data structures to parse later // second solution: vcp version in dumpload data Monitor_Model_Key mmk = mmk_value( data->mfg_id, data->model, data->product_code); Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_mmk_and_vspec( feature_id, mmk, data->vcp_version, true, /* check_udf */ /*with_default=*/ true); bool is_table_feature = dfm->version_feature_flags & DDCA_NORMAL_TABLE; if (is_table_feature) { // s2 is hex string Byte * ba; int bytect = hhs_to_byte_array(s2, &ba); if (bytect < 0) { // f0printf(ferr(), // "Invalid hex string value for opcode at line %d: %s\n", // linectr, line); ADD_DATA_ERROR("Invalid hex string value for opcode"); #ifndef NDEBUG valid_data = false; #endif } else { valrec = create_table_vcp_value_by_bytes( feature_id, ba, bytect); free(ba); } } else { // non-table feature gushort feature_value; ct = sscanf(s2, "%hu", &feature_value); if (ct == 0) { // f0printf(ferr(), "Invalid value for opcode at line %d: %s\n", linectr, line); ADD_DATA_ERROR("Invalid value for opcode"); #ifndef NDEBUG valid_data = false; #endif } else { // good opcode and value // TODO: opcode and value should be saved in local vars valrec = create_cont_vcp_value( feature_id, 0, // max_val, unused for LOADVCP feature_value); } } // non-table feature if (valrec) { data->vcp_value_ct++; vcp_value_set_add(data->vcp_values, valrec); } dfm_free(dfm); } // valid opcode } // found feature id and value } // VCP else { // f0printf(ferr(), "Unexpected field \"%s\" at line %d: %s\n", s0, linectr, line ); errinfo_add_cause( errs, errinfo_new( DDCRC_BAD_DATA, __func__, "Unexpected field \"%s\" at line %d: %s", s0, linectr, line) ); #ifndef NDEBUG valid_data = false; #endif } } // more than 1 field on line } // non-comment line } // one line of file assert( ( valid_data && errs->cause_ct == 0 ) || (!valid_data && errs->cause_ct > 0) ); if (errs->cause_ct == 0) { errinfo_free(errs); errs = NULL; } else { if (data) { free_dumpload_data(data); data = NULL; } } *dumpload_data_loc = data; DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, errs, ""); return errs; } #undef ADD_DATA_ERROR /** Sets multiple VCP values. * * @param dh display handle * @param vset values to set * @return #Ddc_Error reflecting the first error, or NULL if no errors * * This function stops applying values on the first error encountered, and * returns the value of that error as its status code. * * @remark * Consider not stopping on error, instead accumulate errors in Error_Info. */ Error_Info * ddc_set_multiple( Display_Handle* dh, Vcp_Value_Set vset) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); Public_Status_Code psc = 0; Error_Info * ddc_excp = NULL; int value_ct = vcp_value_set_size(vset); int ndx; for (ndx=0; ndx < value_ct; ndx++) { DDCA_Any_Vcp_Value * vrec = vcp_value_set_get(vset, ndx); Byte feature_code = vrec->opcode; // HACK: will this affect intermittent error of silently failing sets? // pointless, ddc_it2_write_only) calls call_tuned_sleep() after write // if (ndx > 0) { // sleep_millis_with_trace(DDC_TIMEOUT_MILLIS_DEFAULT, __func__, "before set_vcp_value()"); // } ddc_excp = ddc_set_verified_vcp_value_with_retry(dh, vrec, NULL); psc = (ddc_excp) ? ddc_excp->status_code : 0; if (ddc_excp) { SYSLOG2(DDCA_SYSLOG_ERROR, "Error setting value for VCP feature code 0x%02x: %s", feature_code, psc_desc(psc) ); if (psc == DDCRC_RETRIES) SYSLOG2(DDCA_SYSLOG_ERROR, " Try errors: %s", errinfo_causes_string(ddc_excp)); if (ndx < value_ct-1) SYSLOG2(DDCA_SYSLOG_ERROR, "Not attempt to set additional values."); break; } } // for loop DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } /** Applies VCP settings from a #Dumpload_Data struct to * the monitor specified in that data structure. * * @param pdata pointer to #Dumpload_Data instance * @param dh display handle for open display, * if NULL, open the find the display based on the identifiers * in the data and open it * * @return #Ddc_Error describing the first error, or NULL if no error */ Error_Info * loadvcp_by_dumpload_data( Dumpload_Data * pdata, Display_Handle * dh) { assert(pdata); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Loading VCP settings for monitor \"%s\", sn \"%s\", dh=%p \n", pdata->model, pdata->serial_ascii, dh); if ( IS_DBGTRC(debug, TRACE_GROUP) ) dbgrpt_dumpload_data(pdata, 0); Error_Info * ddc_excp = NULL; Display_Handle * dh_argument = dh; if (dh) { // If explicit display specified, check that the data is valid for it assert(dh->dref->pedid); bool ok = true; if ( !streq(dh->dref->pedid->model_name, pdata->model) ) { const char * fmt = "Monitor model in data (%s) does not match that for specified device (%s)"; MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, fmt, pdata->model, dh->dref->pedid->model_name); ddc_excp = errinfo_new(DDCRC_INVALID_DISPLAY, __func__, fmt, pdata->model, dh->dref->pedid->model_name); ok = false; } if (!streq(dh->dref->pedid->serial_ascii, pdata->serial_ascii) ) { const char * fmt = "Monitor serial number in data (%s) does not match that for specified device (%s)"; MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, fmt, pdata->serial_ascii, dh->dref->pedid->serial_ascii); ddc_excp = errinfo_new(DDCRC_INVALID_DISPLAY, pdata->serial_ascii, dh->dref->pedid->serial_ascii); ok = false; } if (!ok) { goto bye; } } else if ( strlen(pdata->mfg_id) + strlen(pdata->model) + strlen(pdata->serial_ascii) == 0) { // Pathological. Someone's been messing with the VCP file. MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Monitor manufacturer id, model, and serial number all missing from input."); ddc_excp = errinfo_new(DDCRC_INVALID_DISPLAY, __func__, "Monitor manufacturer id, model, and serial number all missing from input."); goto bye; } else { // no Display_Ref passed as argument, just use the identifiers in the data to pick the display Display_Identifier * did = create_mfg_model_sn_display_identifier( pdata->mfg_id, pdata->model, pdata->serial_ascii); assert(did); Display_Ref * dref = get_display_ref_for_display_identifier(did, CALLOPT_NONE); free_display_identifier(did); if (!dref) { SYSLOG2(DDCA_SYSLOG_ERROR, "Monitor not connected: %s - %s", pdata->model, pdata->serial_ascii ); ddc_excp = errinfo_new(DDCRC_INVALID_DISPLAY, __func__, "Monitor not connected: %s - %s", pdata->model, pdata->serial_ascii ); goto bye; } // return code == 0 iff dh set ddc_excp = ddc_open_display(dref, CALLOPT_NONE, &dh); ASSERT_IFF(dh, !ddc_excp); // avoid bogus coverity error if (ddc_excp) { SYSLOG2(DDCA_SYSLOG_ERROR, "Error opening display %s: %s", dref_repr_t(dref), ddcrc_desc_t(ddc_excp->status_code)); goto bye; } } ddc_excp = ddc_set_multiple(dh, pdata->vcp_values); // close the display only if this function opened it if (!dh_argument) ddc_excp = ddc_close_display(dh); bye: DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp;; } /** Reads the monitor identification and VCP values from a null terminated * string array and applies those values to the selected monitor. * * \param ntsa null terminated array of strings * \param dh display handle * \return pointer to #Ddc_Error describing the first error, NULL if if success */ Error_Info * loadvcp_by_ntsa( Null_Terminated_String_Array ntsa, Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "ntsa=%p", ntsa); bool verbose = (get_output_level() >= DDCA_OL_VERBOSE) || debug; Error_Info * ddc_excp = NULL; GPtrArray * garray = ntsa_to_g_ptr_array(ntsa); Dumpload_Data * pdata = NULL; ddc_excp = create_dumpload_data_from_g_ptr_array(garray, &pdata); DBGMSF(debug, "create_dumpload_data_from_g_ptr_array() returned %p", pdata); assert( (ddc_excp == NULL && pdata != NULL) || (ddc_excp != NULL && pdata == NULL) ); if (!pdata) { // f0printf(ferr(), "Unable to load VCP data from string\n"); // psc = DDCRC_ARG; // was DDCRC_INVALID_DATA; // ddc_excp = errinfo_new(psc, __func__); } else { if (verbose) { f0printf(fout(), "Loading VCP settings for monitor \"%s\", sn \"%s\" \n", pdata->model, pdata->serial_ascii); rpt_push_output_dest(fout()); dbgrpt_dumpload_data(pdata, 0); rpt_pop_output_dest(); } ddc_excp = loadvcp_by_dumpload_data(pdata, dh); free_dumpload_data(pdata); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } /** Reads the monitor identification and VCP values from a single string * whose fields are separated by ';' and applies those values to the * selected monitor. * * \param catenated data string * \param dh display handle * \return pointer to #Ddc_Error describing first error, NULL if success */ // n. called from ddct_public: Error_Info * loadvcp_by_string( char * catenated, Display_Handle * dh) { Null_Terminated_String_Array nta = strsplit(catenated, ";"); Error_Info * ddc_excp = loadvcp_by_ntsa(nta, dh); ntsa_free(nta, /* free_strings */ true); return ddc_excp; } // // DUMPVCP // // // Support for the DUMPVCP command and for returning profile info in the API // /** Formats a timestamp in a way usable in a filename, specifically: * YYYMMDD-HHMMSS * * \param time_millis timestamp in milliseconds * \param buf buffer in which to return the formatted timestamp * \param bufsz buffer size * \return formatted timestamp * * \remark * If buf == NULL or bufsz == 0, then this function allocates a buffer. * It is the responsibility of the caller to free this buffer. */ char * format_timestamp(time_t time_millis, char * buf, int bufsz) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "buf=%p, bufsz=%d", buf, bufsz); if (bufsz == 0 || buf == NULL) { bufsz = 128; buf = calloc(1, bufsz); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Allocated new buffer: %p", buf); } struct tm tm = *localtime(&time_millis); snprintf(buf, bufsz, "%4d%02d%02d-%02d%02d%02d", tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec ); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: %p", buf); return buf; } #ifdef UNUSED /* Returns monitor identification information in an array of strings. * The strings are written in the format of the DUMPVCP command. * * Arguments: * dh display handle for monitor * vals GPtrArray to which the identification strings are appended. * * Returns: nothing */ void collect_machine_readable_monitor_id(Display_Handle * dh, GPtrArray * vals) { char buf[400]; int bufsz = sizeof(buf)/sizeof(char); Parsed_Edid * edid = ddc_get_parsed_edid_by_dh(dh); snprintf(buf, bufsz, "MFG_ID %s", edid->mfg_id); g_ptr_array_add(vals, g_strdup(buf)); snprintf(buf, bufsz, "MODEL %s", edid->model_name); g_ptr_array_add(vals, g_strdup(buf)); snprintf(buf, bufsz, "SN %s", edid->serial_ascii); g_ptr_array_add(vals, g_strdup(buf)); char hexbuf[257]; hexstring2(edid->bytes, 128, NULL /* no separator */, true /* uppercase */, hexbuf, 257); snprintf(buf, bufsz, "EDID %s", hexbuf); g_ptr_array_add(vals, g_strdup(buf)); } #endif /** Appends TIMESTAMP_TEXT and TIMESTAMP_MILLIS lines to an array of strings. * The strings are written in the format of the DUMPVCP command. * * \param time_millis timestamp in milliseconds * \param vals GPtrArray to which the timestamp strings are appended. */ void collect_machine_readable_timestamp(time_t time_millis, GPtrArray* vals) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, ""); // temporarily use same output format as filename, but format the // date separately here for flexibility char timestamp_buf[30]; // n. since buffer provided, format_timestamp() does not allocate format_timestamp(time_millis, timestamp_buf, sizeof(timestamp_buf)); char buf[400]; int bufsz = sizeof(buf)/sizeof(char); snprintf(buf, bufsz, "TIMESTAMP_TEXT %s", timestamp_buf ); g_ptr_array_add(vals, g_strdup(buf)); // time_t is problematic. %jd handles x32_abi where time_t is of type long long // but per the c11 spec time_t can be a real type // Value is ignored on input, so just don't output it and avoid the issues. (11/2018) // snprintf(buf, bufsz, "TIMESTAMP_MILLIS %jd", time_millis); // g_ptr_array_add(vals, g_strdup(buf)); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Appended %s", buf); } #ifdef UNUSED // for completeness, currently unused /* Save profile related information (timestamp, monitor identification, * VCP values) in external form in a GPtrArray of string. * * Arguments: * dh display handle * time_millis timestamp in milliseconds * pvals Location of newly allocated GptrArray * * Returns: * status code * * It is the responsibility of the caller to free the newly allocated * GPtrArray. */ Public_Status_Code collect_profile_related_values( Display_Handle* dh, time_t timestamp_millis, GPtrArray** pvals) { bool debug = false; DBGMSF(debug, "Starting"); assert( get_output_level() == OL_PROGRAM); Public_Status_Code psc = 0; GPtrArray * vals = g_ptr_array_sized_new(50); collect_machine_readable_timestamp(timestamp_millis, vals); collect_machine_readable_monitor_id(dh, vals); psc = show_vcp_values( dh, VCP_SUBSET_PROFILE, vals, false /* force_show_unsupported */); *pvals = vals; if (debug) { DBGMSG("Done. *pvals->len=%d *pvals: ", vals->len); int ndx = 0; for (;ndx < vals->len; ndx++) { DBGMSG(" |%s|", g_ptr_array_index(vals,ndx) ); } } return psc; } #endif /** Primary function for the DUMPVCP command. * * Writes DUMPVCP data to the in-core Dumpload_Data structure * * \param dh display handle for connected display * \param dumpload_data_loc address at which to return pointer to newly allocated * Dumpload_Data struct. It is the responsibility of the * caller to free this data structure. * \return status code */ Public_Status_Code dumpvcp_as_dumpload_data( Display_Handle * dh, Dumpload_Data** dumpload_data_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); Public_Status_Code psc = 0; Dumpload_Data * dumped_data = calloc(1, sizeof(Dumpload_Data)); // timestamp: dumped_data->timestamp_millis = time(NULL); DBGMSF(debug, "Before get_vcp_version_by_dh()"); dumped_data->vcp_version = get_vcp_version_by_dh(dh); // use function to ensure set // identification information from edid: // Parsed_Edid * edid = ddc_get_parsed_edid_by_dh(dh); Parsed_Edid * edid = dh->dref->pedid; assert(edid); DBGMSF(debug, "Have EDID"); dumped_data->product_code = edid->product_code; memcpy(dumped_data->mfg_id, edid->mfg_id, sizeof(dumped_data->mfg_id)); memcpy(dumped_data->model, edid->model_name, sizeof(dumped_data->model)); memcpy(dumped_data->serial_ascii, edid->serial_ascii, sizeof(dumped_data->serial_ascii)); memcpy(dumped_data->edidbytes, edid->bytes, 128); assert(sizeof(dumped_data->edidstr) == 257); hexstring2(edid->bytes, 128, NULL /* no separator */, true /* uppercase */, dumped_data->edidstr, 257); // VCP values Vcp_Value_Set vset = vcp_value_set_new(50); psc = ddc_collect_raw_subset_values( dh, VCP_SUBSET_PROFILE, vset, true, // ignore_unsupported ferr()); if (psc == 0) { dumped_data->vcp_values = vset; // NOTE REFERENCE, BE CAREFUL WHEN FREE dumped_data->vcp_value_ct = vcp_value_set_size(vset); } if (psc != 0 && dumped_data) free(dumped_data); else *dumpload_data_loc = dumped_data; DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, "*dumpload_data_loc = %p", *dumpload_data_loc); if ( *dumpload_data_loc && IS_DBGTRC(debug, TRACE_GROUP) ) dbgrpt_dumpload_data(*dumpload_data_loc, 1); return psc; } /** Converts a Dumpload_Data structure to an array of strings * * \param data pointer to Dumpload_Data instance * \return array of strings, caller must free * * \remark * Note that the result shares no memory with data */ GPtrArray * convert_dumpload_data_to_string_array(Dumpload_Data * data) { bool debug = false; DBGMSF(debug, "Starting. data=%p", data); assert(data); if (debug) dbgrpt_dumpload_data(data, 1); GPtrArray * strings = g_ptr_array_sized_new(30); g_ptr_array_set_free_func(strings, g_free); collect_machine_readable_timestamp(data->timestamp_millis, strings); char buf[300]; int bufsz = sizeof(buf)/sizeof(char); snprintf(buf, bufsz, "MFG_ID %s", data->mfg_id); g_ptr_array_add(strings, g_strdup(buf)); snprintf(buf, bufsz, "MODEL %s", data->model); g_ptr_array_add(strings, g_strdup(buf)); snprintf(buf, bufsz, "PRODUCT_CODE %d", data->product_code); g_ptr_array_add(strings, g_strdup(buf)); snprintf(buf, bufsz, "SN %s", data->serial_ascii); g_ptr_array_add(strings, g_strdup(buf)); char hexbuf[257]; hexstring2(data->edidbytes, 128, NULL /* no separator */, true /* uppercase */, hexbuf, 257); snprintf(buf, bufsz, "EDID %s", hexbuf); g_ptr_array_add(strings, g_strdup(buf)); if (!vcp_version_eq(data->vcp_version, DDCA_VSPEC_UNKNOWN)) { snprintf(buf, bufsz, "VCP_VERSION %d.%d", data->vcp_version.major, data->vcp_version.minor); g_ptr_array_add(strings, g_strdup(buf)); } for (int ndx=0; ndx < data->vcp_values->len; ndx++) { // n. get_formatted_value_for_feature_table_entry() also has code for table type values DDCA_Any_Vcp_Value * vrec = vcp_value_set_get(data->vcp_values,ndx); char buf[200]; snprintf(buf, 200, "VCP %02X %5d", vrec->opcode, VALREC_CUR_VAL(vrec)); g_ptr_array_add(strings, g_strdup(buf)); } return strings; } /** Returns the output of the DUMPVCP command in a single string. * Each field is separated by a semicolon. * * The caller is responsible for freeing the returned string. * * \param dh display handle of open monitor * \param result_loc location at which to return string * \return status code */ // n. called from api_feature_access.c Public_Status_Code dumpvcp_as_string(Display_Handle * dh, char ** result_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); Public_Status_Code psc = 0; Dumpload_Data * data = NULL; *result_loc = NULL; psc = dumpvcp_as_dumpload_data(dh, &data); if (psc == 0) { GPtrArray * strings = convert_dumpload_data_to_string_array(data); *result_loc = join_string_g_ptr_array(strings, ";"); g_ptr_array_free(strings, true); free_dumpload_data(data); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, "*result_loc=|%s|", *result_loc); return psc; } void init_ddc_dumpload() { RTTI_ADD_FUNC(free_dumpload_data); RTTI_ADD_FUNC(create_dumpload_data_from_g_ptr_array); RTTI_ADD_FUNC(ddc_set_multiple); RTTI_ADD_FUNC(loadvcp_by_dumpload_data); RTTI_ADD_FUNC(loadvcp_by_ntsa); RTTI_ADD_FUNC(format_timestamp); RTTI_ADD_FUNC(collect_machine_readable_timestamp); RTTI_ADD_FUNC(dumpvcp_as_dumpload_data); RTTI_ADD_FUNC(dumpvcp_as_string); } ddcutil-2.2.0/src/ddc/ddc_initial_checks.c0000644000175000001440000007225314754576332014121 /** @file ddc_initial_checks.c */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #ifdef USE_X11 #include #endif #include "config.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/edid.h" #include "util/error_info.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #ifdef USE_X11 #include "util/x11_util.h" #endif /** \endcond */ #include "public/ddcutil_types.h" #include "base/core.h" #include "base/displays.h" #include "base/ddc_packets.h" #include "base/dsa2.h" #include "base/i2c_bus_base.h" #include "base/monitor_model_key.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/status_code_mgt.h" #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_base.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" #include "ddc/ddc_initial_checks.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; // // Globals // bool skip_ddc_checks = false; bool monitor_state_tests = false; // // Utility Functions // static inline bool value_bytes_zero_for_any_value(DDCA_Any_Vcp_Value * pvalrec) { assert(pvalrec); bool result = pvalrec && pvalrec->value_type == DDCA_NON_TABLE_VCP_VALUE && pvalrec->val.c_nc.mh == 0 && pvalrec->val.c_nc.ml == 0 && pvalrec->val.c_nc.sh == 0 && pvalrec->val.c_nc.sl == 0; return result; } static inline bool value_bytes_zero_for_nontable_value(Parsed_Nontable_Vcp_Response* valrec) { assert(valrec); bool result = valrec->mh == 0 && valrec->ml == 0 && valrec->sh == 0 && valrec->sl == 0; return result; } // // Monitor Checks // /** Attempt to read a non-table feature code that should never be valid. * Check that it is in fact reported as unsupported. * * @param dh Display Handle * @param feature code VCP feature code * @return Error_Info if unsupported, NULL if supported * * @remark * Possible return settings * Error_Info.status = DDCRC_DETERMINED_UNSUPPORTED, set DREF_DDC_USES_MH_ML_SHL_SL_ZERO_FOR_UNSUPPORTED * Error_Info.status = DDCRC_ALL_RESPONSES_NULL, set DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED * Error_Info.status = DDCRC_RETRIES * */ STATIC Error_Info * read_unsupported_feature( Display_Handle * dh, DDCA_Vcp_Feature_Code feature_code) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s. feature_code=0x%02x", dh_repr(dh), feature_code); I2C_Bus_Info * businfo = (I2C_Bus_Info *) dh->dref->detail; Per_Display_Data * pdd = dh->dref->pdd; Parsed_Nontable_Vcp_Response * parsed_response_loc = NULL; // turns off possible abbreviated NULL msg handling in ddc_write_read_with_retry() dh->testing_unsupported_feature_active = true; bool dynamic_sleep_was_active = false; Error_Info * ddc_excp = ddc_get_nontable_vcp_value(dh, feature_code, &parsed_response_loc); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, sleep-multiplier=%5.2f, ddc_get_nontable_vcp_value() for feature 0x%02x returned: %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); retry: if (!ddc_excp) { if (value_bytes_zero_for_nontable_value(parsed_response_loc)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Setting DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED"); dh->dref->flags |= DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED; ddc_excp = ERRINFO_NEW(DDCRC_DETERMINED_UNSUPPORTED, "Set DREF_DDC_USES_MH_ML_SH_SL for unsupported"); } else { if (get_output_level() >= DDCA_OL_VERBOSE) rpt_vstring(0, "/dev/i2c-%d, Feature 0x%02x should not exist, but the monitor reports it as valid", businfo->busno, feature_code); SYSLOG2(DDCA_SYSLOG_WARNING, "busno=%d, Feature 0x%02x should not exist but ddc_get_nontable_vcp_value() succeeds," " returning mh=0x%02x ml=0x%02x sh=0x%02x sl=0x%02x", businfo->busno, feature_code, parsed_response_loc->mh, parsed_response_loc->ml, parsed_response_loc->sh, parsed_response_loc->ml); } } else if ( ERRINFO_STATUS(ddc_excp) == DDCRC_RETRIES ) { if (errinfo_all_causes_same_status(ddc_excp, DDCRC_NULL_RESPONSE)) { errinfo_free(ddc_excp); ddc_excp = ERRINFO_NEW(DDCRC_ALL_RESPONSES_NULL, ""); dh->dref->flags |= DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED; } else { if (!dynamic_sleep_was_active) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, sleep-multiplier=%d, Testing for unsupported feature 0x%02x returned %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); SYSLOG2(DDCA_SYSLOG_ERROR, "busno=%d, sleep-multiplier=%5.2f, Testing for unsupported feature 0x%02x returned %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); } if (pdd_is_dynamic_sleep_active(pdd) ) { dynamic_sleep_was_active = true; ERRINFO_FREE(ddc_excp); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Turning off dynamic sleep and retrying"); SYSLOG2(DDCA_SYSLOG_ERROR, "Turning off dynamic sleep and retrying"); pdd_set_dynamic_sleep_active(pdd, false); ddc_excp = ddc_get_nontable_vcp_value(dh, feature_code, &parsed_response_loc); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, sleep-multiplier=%5.2f, Retesting for unsupported feature 0x%02x returned %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); SYSLOG2(DDCA_SYSLOG_ERROR, "busno=%d, sleep-multiplier =%5.2f, Retesting for unsupported feature 0x%02x returned %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); goto retry; } } } if (dynamic_sleep_was_active) pdd_set_dynamic_sleep_active(pdd, true); dh->testing_unsupported_feature_active = false; free(parsed_response_loc); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } /** Determines how an unsupported non-table feature is reported. * * @param dh Display Handle * * Sets relevant DREF_DDC_* flags in the associated Display Reference to * indicate how unsupported features are reported. * Possible values: * DREF_DDC_DOES_NOT_INDICATE_UNSUPPORTED * DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED * DREF_DDC_USES_MH_ML_SHL_SL_ZERO_FOR_UNSUPPORTED * DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED */ STATIC void check_how_unsupported_reported(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); Display_Ref* dref = dh->dref; I2C_Bus_Info * businfo = (I2C_Bus_Info *) dref->detail; assert(dref->io_path.io_mode == DDCA_IO_I2C); // Try features that should never exist Error_Info * erec = read_unsupported_feature(dh, 0xdd); // not defined in MCCS if ((!erec || ERRINFO_STATUS(erec) == DDCRC_RETRIES) && is_input_digital(dh->dref->pedid)) { ERRINFO_FREE(erec); erec = read_unsupported_feature(dh, 0x41); // CRT only feature } if (!erec || ERRINFO_STATUS(erec) == DDCRC_RETRIES) { ERRINFO_FREE(erec); erec = read_unsupported_feature(dh, 0x00); } Public_Status_Code psc = ERRINFO_STATUS(erec); if (psc == 0) { dh->dref->flags |= DREF_DDC_DOES_NOT_INDICATE_UNSUPPORTED; SYSLOG2(DDCA_SYSLOG_ERROR, "busno=%d, All features that should not exist detected. " "Monitor does not indicate unsupported", businfo->busno); } else { if (psc == DDCRC_RETRIES) { dref->flags |= DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED; // our best guess SYSLOG2(DDCA_SYSLOG_ERROR, "busno=%d, DDCRC_RETRIES failure reading all unsupported features. " "Setting DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED", businfo->busno); } else if (psc == DDCRC_DETERMINED_UNSUPPORTED) { // already handled in read_unsupported_feature() } else if (psc == DDCRC_REPORTED_UNSUPPORTED) { // the monitor is well-behaved dref->flags |= DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED; } else if ( (psc == DDCRC_NULL_RESPONSE || psc == DDCRC_ALL_RESPONSES_NULL) && !ddc_never_uses_null_response_for_unsupported) { // for testing // Null Msg really means unsupported dref->flags |= DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED; } // What if returns -EIO? Dell AW3418D returns -EIO for unsupported features // EXCEPT that it returns mh=ml=sh=sl=0 for feature 0x00 (2/2019) // Too dangerous to always treat -EIO as unsupported else if (psc == -EIO) { MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "busno=%d. Monitor apparently returns -EIO for unsupported features. This cannot be relied on.", businfo->busno); } } errinfo_free(erec); dh->dref->flags |= DREF_UNSUPPORTED_CHECKED; #ifdef OUT // EIO case fails this assertion assert(dh->dref->flags & (DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED | DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED | DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED | DREF_DDC_DOES_NOT_INDICATE_UNSUPPORTED ) ); #endif DBGTRC_DONE(debug, TRACE_GROUP, "dref->flags=%s", interpret_dref_flags_t(dref->flags)); } STATIC Error_Info * check_supported_feature(Display_Handle * dh, bool newly_added, DDCA_Vcp_Feature_Code feature_code, uint16_t * p_shsl) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, newly_added=%s feature=0x%02x, p_shsl=%p", dh_repr(dh), SBOOL(newly_added), feature_code,p_shsl); Error_Info * ddc_excp = NULL; *p_shsl = 0; Per_Display_Data * pdd = dh->dref->pdd; Display_Ref * dref = dh->dref; I2C_Bus_Info * businfo = dh->dref->detail; DDCA_Sleep_Multiplier initial_multiplier = pdd_get_adjusted_sleep_multiplier(pdd); Parsed_Nontable_Vcp_Response* parsed_response_loc = NULL; // feature that always exists // Byte feature_code = 0x10; ddc_excp = ddc_get_nontable_vcp_value(dh, feature_code, &parsed_response_loc); // may return DDCRC_DISCONNECTED from i2c_check_open_bus_alive() if (!ddc_excp) { *p_shsl = HI_LO_BYTES_TO_SHORT(parsed_response_loc->sh, parsed_response_loc->sl); } #ifdef TESTING if (businfo->busno == 6) { ddc_excp = ERRINFO_NEW(DDCRC_BAD_DATA, "Dummy error"); DBGMSG("Setting dummy ddc_excp(DDCRC_BAD_DATA)"); } #endif if (ddc_excp) { char * msg = g_strdup_printf( "busno=%d, sleep-multiplier = %5.2f. Testing for supported feature 0x%02x returned %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "!!!! %s", msg); SYSLOG2(DDCA_SYSLOG_NOTICE, "(%s) %s", __func__, msg); free(msg); dref->communication_error_summary = g_strdup(errinfo_summary(ddc_excp)); if (ddc_excp->status_code != DDCRC_DISCONNECTED) { bool dynamic_sleep_active = pdd_is_dynamic_sleep_active(pdd); if (newly_added || (ERRINFO_STATUS(ddc_excp) == DDCRC_RETRIES && dynamic_sleep_active && initial_multiplier < 1.0f)) { if (newly_added) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Additional 1 second sleep for newly added display (A)"); DW_SLEEP_MILLIS(1000, "Additional 1 second sleep for newly added display (C)"); } // turn off optimization in case it's on if (dynamic_sleep_active ) { FREE(dref->communication_error_summary); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Turning off dynamic sleep"); pdd_set_dynamic_sleep_active(dref->pdd, false); ERRINFO_FREE_WITH_REPORT(ddc_excp, IS_DBGTRC(debug, TRACE_GROUP)); ddc_excp = ddc_get_nontable_vcp_value(dh, 0x10, &parsed_response_loc); if (!ddc_excp) { *p_shsl = HI_LO_BYTES_TO_SHORT(parsed_response_loc->sh, parsed_response_loc->sl); } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, sleep-multiplier=%5.2f. " "Retesting for supported feature 0x%02x returned %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); dref->communication_error_summary = g_strdup(errinfo_summary(ddc_excp)); SYSLOG2((ddc_excp) ? DDCA_SYSLOG_ERROR : DDCA_SYSLOG_NOTICE, "busno=%d, sleep-multiplier=%5.2f." "Retesting for supported feature 0x%02x returned %s", businfo->busno, pdd_get_adjusted_sleep_multiplier(pdd), feature_code, errinfo_summary(ddc_excp)); } } } } // if (businfo->busno == 6) { // ddc_excp = ERRINFO_NEW(DDCRC_BAD_DATA, "Dummy error"); // DBGMSG("Setting dummy ddc_excp(DDCRC_BAD_DATA)"); // } free(parsed_response_loc); Public_Status_Code psc = ERRINFO_STATUS(ddc_excp); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ddc_get_nontable_vcp_value() for feature 0x%02x returned: %s, status: %s", feature_code, errinfo_summary(ddc_excp), psc_desc(psc)); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, "*p_shsl=0x%04x", *p_shsl); return ddc_excp; } /** Collects initial monitor checks to perform them on a single open of the * monitor device, and to avoid repeating them. * * Performs the following tests: * - Checks that DDC communication is working. * - Checks if the monitor uses DDC Null Response to indicate invalid VCP code * - Checks if the monitor uses mh=ml=sh=sl=0 to indicate invalid VCP code * * @param dh pointer to #Display_Handle for open monitor device * @param newly_added called by display watch when adding a display * @return #Error_Info struct if error, caller responsible for freeing * * @remark * Sets bits in dh->dref->flags * * @remark * It has been observed that DDC communication can fail even if slave address x37 * is valid on the I2C bus. * @remark * ADL does not notice that a reported display, e.g. Dell 1905FP, does not support * DDC. * @remark * Monitors are supposed to set the unsupported feature bit in a valid DDC * response, but a few monitors (mis)use the Null Response instead to indicate * an unsupported feature. Others return with the unsupported feature bit not * set, but all bytes (mh, ml, sh, sl) zero. * @remark * Note that the test here is not perfect, as a Null Response might * in fact indicate a transient error, but that is rare. * @remark * Output level should have been set <= DDCA_OL_NORMAL prior to this call since * verbose output is distracting. */ STATIC Error_Info * ddc_initial_checks_by_dh(Display_Handle * dh, bool newly_added) { bool debug = false; TRACED_ASSERT(dh && dh->dref); DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, newly_added=%s", dh_repr(dh), sbool(newly_added)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Initial flags: %s",interpret_dref_flags_t(dh->dref->flags)); Display_Ref * dref = dh->dref; I2C_Bus_Info * businfo = dref->detail; Per_Display_Data * pdd = dref->pdd; // bool iomode_is_i2c = dh->dref->io_path.io_mode == DDCA_IO_I2C; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "adjusted sleep-multiplier = %5.2f", pdd_get_adjusted_sleep_multiplier(pdd)); Error_Info * ddc_excp = NULL; bool saved_dynamic_sleep_active = pdd_is_dynamic_sleep_active(pdd); if (debug) show_backtrace(0); if (!(dref->flags & DREF_DDC_COMMUNICATION_CHECKED)) { // assert(businfo->flags & I2C_BUS_DRM_CONNECTOR_CHECKED); assert(businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_CHECKED); // if (!(businfo->flags & I2C_BUS_DRM_CONNECTOR_CHECKED)) { // i2c_check_businfo_connector(businfo); // } int depth = IS_DBGTRC(debug, DDCA_TRC_NONE) ? 1 : -1; if (businfo->drm_connector_name) { possibly_write_detect_to_status_by_connector_name(businfo->drm_connector_name); if (depth > 0) rpt_label(0, "Current sysfs attributes:"); RPT_ATTR_TEXT(depth, NULL, "/sys/class/drm",businfo->drm_connector_name, "dpms"); RPT_ATTR_TEXT(depth, NULL, "/sys/class/drm",businfo->drm_connector_name, "status"); RPT_ATTR_TEXT(depth, NULL, "/sys/class/drm",businfo->drm_connector_name, "enabled"); RPT_ATTR_INT (depth, NULL, "/sys/class/drm",businfo->drm_connector_name, "drm_connector_id"); bool edid_found = GET_ATTR_EDID(NULL, "/sys/class/drm",businfo->drm_connector_name, "edid"); rpt_vstring(depth, "/sys/class/drm/%s/edid: %s", businfo->drm_connector_name, (edid_found) ? "Found" : "Not found"); // RPT_ATTR_EDID(depth, NULL, "/sys/class/drm",businfo->drm_connector_name, "edid"); } // DBGMSG("monitor_state_tests = %s", SBOOL(monitor_state_tests)); if (monitor_state_tests) explore_monitor_state(dh); if (businfo->flags & I2C_BUS_LVDS_OR_EDP) { DBGTRC(debug, TRACE_GROUP, "Laptop display definitely detected, not checking feature x10"); dref->flags |= DREF_DDC_COMMUNICATION_CHECKED; } else if (!(businfo->flags & I2C_BUS_ADDR_X37)) { DBGTRC(debug, TRACE_GROUP, "Slave address x37 not responsive, not checking feature x10"); dref->flags |= DREF_DDC_COMMUNICATION_CHECKED; } else { uint16_t shsl; // DDCA_Vcp_Feature_Code fc = (iomode_is_i2c) ? 0xdf : 0x10; DDCA_Vcp_Feature_Code fc = 0x10; ddc_excp = check_supported_feature(dh, newly_added, fc, &shsl); Public_Status_Code psc = ERRINFO_STATUS(ddc_excp); if (psc == 0 || psc == DDCRC_REPORTED_UNSUPPORTED || psc == DDCRC_DETERMINED_UNSUPPORTED) { dref->flags |= DREF_DDC_COMMUNICATION_WORKING; } else if (psc == DDCRC_DISCONNECTED) { dref->flags = DREF_REMOVED; } else if (psc == -EBUSY) { // communication failed, do not set DDCRC_COMMUNICATION_WORKING dref->flags |= DREF_DDC_BUSY; } if (psc != -EBUSY) { dref->flags |= DREF_DDC_COMMUNICATION_CHECKED; } if ( (dref->flags&DREF_DDC_COMMUNICATION_WORKING) && dref->io_path.io_mode == DDCA_IO_I2C) { check_how_unsupported_reported(dh); if ( i2c_force_bus /* && psc == DDCRC_RETRIES */) { // used only when testing DBGTRC_NOPREFIX(debug || true , TRACE_GROUP, "dh=%s, Forcing DDC communication success.", dh_repr(dh) ); dref->flags |= DREF_DDC_COMMUNICATION_WORKING; dref->flags |= DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED; // good_enuf_for_test } } // end, io_mode == DDC_IO_I2C } } // end, !DREF_DDC_COMMUNICATION_CHECKED if ( dref->flags & DREF_DDC_COMMUNICATION_WORKING ) { // Would prefer to defer checking version until actually needed to avoid // additional DDC io during monitor detection. Unfortunately, this would // introduce ddc_open_display(), with its possible error states, // into other functions, e.g. ddca_get_feature_list_by_dref() if ( vcp_version_eq(dref->vcp_version_xdf, DDCA_VSPEC_UNQUERIED)) { // may have been forced by option --mccs set_vcp_version_xdf_by_dh(dh); } } pdd_set_dynamic_sleep_active(dref->pdd, saved_dynamic_sleep_active); // in case it was set false DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, "Final flags: %s", interpret_dref_flags_t(dref->flags)); return ddc_excp; } /** Given a #Display_Ref, opens the monitor device and calls #ddc_initial_checks_by_dh() * to perform initial monitor checks. * * @param dref pointer to #Display_Ref for monitor * @param newly_added * @return **true** if DDC communication with the display succeeded, **false** otherwise. * * @remark * If global flag **skip_ddc_checks** is set, checking is not performed. * DDC communication is assumed to work, and monitor uses the unsupported feature * flag in reply packets to indicate an unsupported feature. */ Error_Info * ddc_initial_checks_by_dref(Display_Ref * dref, bool newly_added) { assert(dref); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s, newly_added=%s", dref_reprx_t(dref), sbool(newly_added)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Initial dref->flags: %s", interpret_dref_flags_t(dref->flags)); bool result = false; Error_Info * err = NULL; I2C_Bus_Info * businfo = NULL; bool disabled_mmk = is_disabled_mmk(*dref->mmid); // is this monitor model disabled? if (disabled_mmk) { dref->flags |= DREF_DDC_DISABLED; dref->flags |= DREF_DDC_COMMUNICATION_CHECKED; goto bye; } bool skip_ddc_checks0 = skip_ddc_checks; if (dref->io_path.io_mode == DDCA_IO_I2C) { businfo = dref->detail; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "I2C_BUS_DDC_CHECKS_IGNORABLE is set: %s", SBOOL(businfo->flags & I2C_BUS_DDC_CHECKS_IGNORABLE) ); if (businfo->flags & I2C_BUS_DDC_CHECKS_IGNORABLE) skip_ddc_checks0 = true; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "skip_ddc_checks0 = %s", SBOOL(skip_ddc_checks0)); if (skip_ddc_checks0) { dref->flags |= (DREF_DDC_COMMUNICATION_CHECKED | DREF_DDC_COMMUNICATION_WORKING | DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED); dref->vcp_version_xdf = DDCA_VSPEC_UNKNOWN; SYSLOG2(DDCA_SYSLOG_NOTICE, "dref=%s, skipping initial ddc checks", dref_reprx_t(dref)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Skipping initial ddc checks"); result = true; } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Performing initial ddc checks"); // if (!(dref->flags & DREF_DPMS_SUSPEND_STANDBY_OFF)) { Display_Handle * dh = NULL; err = ddc_open_display(dref, CALLOPT_ERR_MSG, &dh); if (err) { char * msg = g_strdup_printf("Unable to open %s: %s", dpath_repr_t(&dref->io_path), psc_desc(err->status_code)); SYSLOG2(DDCA_SYSLOG_WARNING, "%s", msg); free(msg); } else { err = ddc_initial_checks_by_dh(dh, newly_added); if (err) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ddc_initial_checks_by_dh() returned %s", psc_desc(err->status_code)); } ddc_close_display_wo_return(dh); } if (!(dref->flags & DREF_REMOVED)) dref->flags |= DREF_DDC_COMMUNICATION_CHECKED; if (err && err->status_code == -EBUSY) dref->flags |= DREF_DDC_BUSY; // return err; // } } if (businfo) { bool last_ddc_check_ok = result && // take the no-skip branch on a reconnection call so that // DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED is not automatically set: (dref->flags & DREF_DDC_USES_DDC_FLAG_FOR_UNSUPPORTED); SETCLR_BIT(businfo->flags, I2C_BUS_DDC_CHECKS_IGNORABLE, last_ddc_check_ok); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "I2C_BUS_DDC_CHECKS_IGNORABLE is set: %s", // SBOOL(businfo->flags & I2C_BUS_DDC_CHECKS_IGNORABLE)); } bye: DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dref=%s, Final flags: %s", dref_reprx_t(dref), interpret_dref_flags_t(dref->flags)); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, "dref=%s", dref_reprx_t(dref)); return err; } // // Exploratory programming, DPMS detection // static void explore_monitor_one_feature(Display_Handle * dh, Byte feature_code) { Parsed_Nontable_Vcp_Response * parsed_response_loc = NULL; rpt_vstring(1, "Getting value of feature 0x%02x", feature_code);; Error_Info * ddc_excp = ddc_get_nontable_vcp_value(dh, feature_code, &parsed_response_loc); ASSERT_IFF(!ddc_excp, parsed_response_loc); if (ddc_excp) { rpt_vstring(2, "ddc_get_nontable_vcp_value() for feature 0x%02x returned: %s", feature_code, errinfo_summary(ddc_excp)); free(ddc_excp); } else { if (!parsed_response_loc->valid_response) rpt_vstring(2, "Invalid Response"); else if (!parsed_response_loc->supported_opcode) rpt_vstring(2, "Unsupported feature code"); else { rpt_vstring(2, "getvcp 0x%02x succeeded", feature_code); rpt_vstring(2, "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", parsed_response_loc->mh, parsed_response_loc->ml, parsed_response_loc->sh, parsed_response_loc->sl); } free(parsed_response_loc); } } void explore_monitor_state(Display_Handle* dh) { rpt_nl(); rpt_label(0, "-----------------------"); #ifdef SYS_DRM_CONNECTOR_DEPENDENCY I2C_Bus_Info * businfo = (I2C_Bus_Info*) dh->dref->detail; char * connector_name = NULL; Sys_Drm_Connector * conn = i2c_check_businfo_connector(businfo); if (!conn) rpt_vstring(0, "i2c_check_businfo_connector() failed for bus %d", businfo->busno); else { connector_name = conn->connector_name; rpt_vstring(0, "Examining monitor state for model: %s, bus /dev/i2c-%d:, connector: %s", dh->dref->pedid->model_name, businfo->busno, connector_name); } rpt_nl(); #endif rpt_vstring(0, "Environment Variables"); char * xdg_session_desktop = getenv("XDG_SESSION_DESKTOP"); rpt_vstring(1, "XDG_SESSION_DESKTOP: %s", xdg_session_desktop); char * xdg_current_desktop = getenv("XDG_CURRENT_DESKTOP"); rpt_vstring(1, "XDG_CURRENT_DESKTOP: %s", xdg_current_desktop); char * xdg_vtnr = getenv("XDG_VTNR"); rpt_vstring(1, "XDG_VTNR: %s", xdg_vtnr); char * xdg_session_type = getenv("XDG_SESSION_TYPE"); rpt_vstring(1, "XDG_SESSION_TYPE = |%s|", xdg_session_type); rpt_nl(); rpt_vstring(0, "Getvcp tests"); pdd_set_dynamic_sleep_active(dh->dref->pdd, false); explore_monitor_one_feature(dh, 0x00); explore_monitor_one_feature(dh, 0x10); explore_monitor_one_feature(dh, 0x41); explore_monitor_one_feature(dh, 0xd6); rpt_nl(); if (streq(xdg_session_type, "x11")) { rpt_vstring(0, "X11 dpms information"); // query X11 // execute_shell_cmd( "xset q | grep DPMS -A 3"); #ifdef USE_X11 unsigned short power_level; unsigned char state; bool ok =get_x11_dpms_info(&power_level, &state); if (ok) { rpt_vstring(1, "power_level=%d = %s, state=%s", power_level, dpms_power_level_name(power_level), sbool(state)); } else DBGMSG("get_x11_dpms_info() failed"); #endif rpt_nl(); } #ifdef SYS_DRM_CONNECTOR_DEPENDENCY rpt_vstring(0, "Probing sysfs"); if (connector_name) { RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", connector_name, "dpms"); RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", connector_name, "enabled"); RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", connector_name, "status"); #ifdef NO_USEFUL_INFO RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", connector_name, "power/runtime_enabled"); RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", connector_name, "power/runtime_status"); RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", connector_name, "power/runtime_suspended_time"); #endif } #endif RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0", "name"); #ifdef NO_USEFUL_INFO RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "async"); RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "autosuspend_delay_ms"); RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "control"); RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "runtime_active_kids"); RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "runtime_active_time"); #endif RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "runtime_enabled"); RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "runtime_status"); RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "runtime_syspended_time"); RPT_ATTR_TEXT(1, NULL, "/sys/class/graphics/fb0/power", "runtime_usage"); rpt_nl(); } void init_ddc_initial_checks() { RTTI_ADD_FUNC(check_how_unsupported_reported); RTTI_ADD_FUNC(ddc_initial_checks_by_dh); RTTI_ADD_FUNC(ddc_initial_checks_by_dref); RTTI_ADD_FUNC(read_unsupported_feature); RTTI_ADD_FUNC(check_supported_feature); } ddcutil-2.2.0/src/ddc/ddc_multi_part_io.c0000644000175000001440000003622714754153540014010 /** \file ddc_multi_part_io.c * * Handle multi-part DDC reads and writes used for Table features and * Capabilities. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include "public/ddcutil_types.h" #include "util/string_util.h" /** \endcond */ #include "base/core.h" #include "base/ddc_errno.h" #include "base/ddc_packets.h" #include "base/execution_stats.h" #include "base/parms.h" #include "base/rtti.h" #include "base/tuned_sleep.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_multi_part_io.h" #include "ddc/ddc_try_data.h" // temp int multi_part_null_adjustment_millis = 0; // Trace management static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; /** Makes one attempt to read the entire capabilities string or table feature value * * @param dh display handle for open i2c device * @param request_type DDC_PACKET_TYPE_CAPABILITIES_REQUEST or DDC_PACKET_TYPE_TABLE_REQD_REQUEST * @param request_subtype VCP feature code for table read, ignore for capabilities * @param write_read_flags if flag all_zero_response_ok is set, an all zero response is not regarded * as an error * @param accumulator buffer in which to return result (already allocated) * @return #Error_Info struct with error detail, NULL if no error */ static Error_Info * try_multi_part_read( Display_Handle * dh, Byte request_type, Byte request_subtype, DDC_Write_Read_Flags write_read_flags, Buffer * accumulator) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "request_type=0x%02x, request_subtype=x%02x, all_zero_response_ok=%s, accumulator=%p", request_type, request_subtype, sbool(write_read_flags & Write_Read_Flag_All_Zero_Response_Ok), accumulator); Error_Info * excp = NULL; DDC_Packet * request_packet_ptr = NULL; DDC_Packet * response_packet_ptr = NULL; request_packet_ptr = create_ddc_multi_part_read_request_packet( request_type, request_subtype, 0, "try_multi_part_read"); buffer_set_length(accumulator,0); int cur_offset = 0; bool complete = false; while (!complete && !excp) { // loop over fragments DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Top of fragment loop"); int fragment_size; update_ddc_multi_part_read_request_packet_offset(request_packet_ptr, cur_offset); response_packet_ptr = NULL; Byte expected_response_type = (request_type == DDC_PACKET_TYPE_CAPABILITIES_REQUEST) ? DDC_PACKET_TYPE_CAPABILITIES_RESPONSE : DDC_PACKET_TYPE_TABLE_READ_RESPONSE; Byte expected_subtype = request_subtype; // 0x00 for capabilities, VCP feature code for table read excp = ddc_write_read_with_retry( dh, request_packet_ptr, MAX_DDC_PACKET_SIZE, expected_response_type, expected_subtype, write_read_flags, &response_packet_ptr ); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ddc_write_read_with_retry() request_type=0x%02x, request_subtype=0x%02x, returned %s", request_type, request_subtype, errinfo_summary(excp)); char * s = g_strdup_printf("Called from %s, request_subtype=0x%02x", __func__, request_subtype); TUNED_SLEEP_WITH_TRACE(dh, SE_POST_CAP_TABLE_SEGMENT, s); free(s); if (excp) { if (response_packet_ptr) free_ddc_packet(response_packet_ptr); continue; } assert(response_packet_ptr); if ( IS_TRACING_BY_FUNC_OR_FILE() || debug ) { DBGMSG("After try_write_read():"); dbgrpt_interpreted_multi_read_fragment( response_packet_ptr->parsed.multi_part_read_fragment, 0); } Interpreted_Multi_Part_Read_Fragment * aux_data_ptr = response_packet_ptr->parsed.multi_part_read_fragment; int display_current_offset = aux_data_ptr->fragment_offset; if (display_current_offset != cur_offset) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "display_current_offset %d != cur_offset %d", display_current_offset, cur_offset); excp = ERRINFO_NEW(DDCRC_MULTI_PART_READ_FRAGMENT, NULL); COUNT_STATUS_CODE(DDCRC_MULTI_PART_READ_FRAGMENT); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "display_current_offset = %d matches cur_offset", display_current_offset); fragment_size = aux_data_ptr->fragment_length; // *** DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "fragment_size = %d", fragment_size); if (fragment_size == 0) { complete = true; // redundant } else { buffer_append(accumulator, aux_data_ptr->bytes, fragment_size); cur_offset = cur_offset + fragment_size; if ( IS_TRACING_BY_FUNC_OR_FILE() || debug ) { DBGMSG("Currently assembled fragment: |%.*s|", accumulator->len, accumulator->bytes); DBGMSG("cur_offset = %d", cur_offset); } write_read_flags = write_read_flags & ~Write_Read_Flag_All_Zero_Response_Ok; } } free_ddc_packet(response_packet_ptr); } // while loop assembling fragments free_ddc_packet(request_packet_ptr); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, excp, ""); return excp; } /** Gets the DDC capabilities string for a monitor, performing retries if necessary. * Also used for VCP features of type Table. * * @param dh handle of open display * @param request_type * @param request_subtype VCP function code for table read, ignore for capabilities * @param write_read_flags * @param buffer_loc address at which to return newly allocated #Buffer in which * result is returned * @retval NULL success * @retval #Ddc_Error containing status DDCRC_UNSUPPORTED does not support Capabilities Request * @retval #Ddc_Error containing status DDCRC_TRIES maximum retries exceeded: * * *buffer_loc is set iff returned value is NULL */ Error_Info * multi_part_read_with_retry( Display_Handle * dh, Byte request_type, Byte request_subtype, // VCP feature code for table read, ignore for capabilities DDC_Write_Read_Flags write_read_flags, Buffer** buffer_loc) { bool debug = false; Retry_Op_Value max_multi_part_read_tries = try_data_get_maxtries2(MULTI_PART_READ_OP); DBGTRC_STARTING(debug, TRACE_GROUP, "request_type=0x%02x, request_subtype=0x%02x, all_zero_response_ok=%s" ", max_multi_part_read_tries=%d", request_type, request_subtype, sbool(write_read_flags & Write_Read_Flag_All_Zero_Response_Ok), max_multi_part_read_tries); assert(write_read_flags & (Write_Read_Flag_Capabilities|Write_Read_Flag_Table_Read)); Public_Status_Code rc = -1; // dummy value for first call of while loop Error_Info * ddc_excp = NULL; Error_Info * try_errors[MAX_MAX_TRIES]; int tryctr = 0; bool can_retry = true; Buffer * accumulator = buffer_new(2048, "multi part read buffer"); // not here // if (write_read_flags & Write_Read_Flag_Table_Read) // write_read_flags |= Write_Read_Flag_All_Zero_Response_Ok; // valid on first call, can indicate unsupported on Table while (tryctr < max_multi_part_read_tries && rc < 0 && can_retry) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Start of while loop. try_ctr=%d, max_multi_part_read_tries=%d", tryctr, max_multi_part_read_tries); ddc_excp = try_multi_part_read( dh, request_type, request_subtype, write_read_flags, accumulator); try_errors[tryctr] = ddc_excp; rc = (ddc_excp) ? ddc_excp->status_code : 0; if (rc == DDCRC_NULL_RESPONSE || rc == DDCRC_ALL_RESPONSES_NULL || errinfo_all_causes_same_status(ddc_excp, DDCRC_NULL_RESPONSE)) { // generally means this, but could conceivably indicate a protocol error. // try multiple times to ensure it's really unsupported? // Null Msg always indicates error for Capabilities command if ( write_read_flags & Write_Read_Flag_Table_Read ) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Terminating loop for %s", psc_name(rc)); can_retry = false; } else { int adjustment = multi_part_null_adjustment_millis; if (adjustment > 0) { SPECIAL_TUNED_SLEEP_WITH_TRACE(dh, adjustment, "special adjustment to recover from DDC_NULL_MSG"); DBGTRC_NOPREFIX(true, TRACE_GROUP, "Ad Hoc %d milliscecond sleep", adjustment); } } } else if (rc == DDCRC_READ_ALL_ZERO) { DBGMSG("Accepting DDCRC_READ_ALL_ZERO"); // if (write_read_flags & Write_Read_Flag_All_Zero_Response_Ok) // rc = DDCRC_OK; can_retry = false; } else if (rc == DDCRC_ALL_TRIES_ZERO) { can_retry = false; } else if (rc == -EBADF) { can_retry = false; } // WRONG LOCATION! This is not a fragment loop // write_read_flags = write_read_flags & ~Write_Read_Flag_All_Zero_Response_Ok; // accept all zero response only on first fragment tryctr++; } ASSERT_IFF( rc==0, !ddc_excp); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "After try loop. tryctr=%d, rc=%d. ddc_excp=%s", tryctr, rc, errinfo_summary(ddc_excp)); if (debug) { for (int ndx = 0; ndx < tryctr; ndx++) { DBGMSG("try_errors[%d] = %s", ndx, errinfo_summary(try_errors[ndx])); } } if (rc < 0) { buffer_free(accumulator, "capabilities buffer, error"); accumulator = NULL; if (tryctr >= max_multi_part_read_tries) rc = DDCRC_RETRIES; ddc_excp = errinfo_new_with_causes(rc, try_errors, tryctr, __func__, NULL); if (rc != try_errors[tryctr-1]->status_code) COUNT_STATUS_CODE(rc); // new status code, count it } else { for (int ndx = 0; ndx < tryctr-1; ndx++) { // errinfo_free(try_errors[ndx]); ERRINFO_FREE_WITH_REPORT(try_errors[ndx], debug || IS_TRACING() || report_freed_exceptions); } } // if counts for DDCRC_ALL_TRIES_ZERO? try_data_record_tries2(dh, MULTI_PART_READ_OP, rc, tryctr); *buffer_loc = accumulator; ASSERT_IFF(ddc_excp, !*buffer_loc); DBGTRC_RET_ERRINFO_STRUCT(debug, TRACE_GROUP, ddc_excp, buffer_loc, buffer_rpt); #ifdef OLD DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, "*buffer_loc=%p", *buffer_loc); if (IS_DBGTRC(debug, TRACE_GROUP) && *buffer_loc) { buffer_rpt(*buffer_loc, 2); } #endif return ddc_excp; } /** Makes one attempt to write an entire VCP Table value * * @param dh display handle for open i2c or adl device * @param vcp_code VCP feature code * @param value_to_set Table feature value * * @return status code */ static Error_Info * try_multi_part_write( Display_Handle * dh, Byte vcp_code, Buffer * value_to_set) { bool debug = false; Byte request_type = DDC_PACKET_TYPE_TABLE_WRITE_REQUEST; Byte request_subtype = vcp_code; DBGTRC_STARTING(debug, TRACE_GROUP, "request_type=0x%02x, request_subtype=x%02x, accumulator=%p", request_type, request_subtype, value_to_set); Error_Info * ddc_excp = NULL; int MAX_FRAGMENT_SIZE = 32; int max_fragment_size = MAX_FRAGMENT_SIZE - 4; // hack // const int writebbuf_size = 6 + MAX_FRAGMENT_SIZE + 1; DDC_Packet * request_packet_ptr = NULL; int bytes_remaining = value_to_set->len; int offset = 0; while (bytes_remaining >= 0 && !ddc_excp) { int bytect_to_write = (bytes_remaining <= max_fragment_size) ? bytes_remaining : max_fragment_size; request_packet_ptr = create_ddc_multi_part_write_request_packet( DDC_PACKET_TYPE_TABLE_WRITE_REQUEST, vcp_code, // request_subtype, offset, value_to_set->bytes+offset, bytect_to_write, __func__); ddc_excp = ddc_write_only_with_retry(dh, request_packet_ptr); free_ddc_packet(request_packet_ptr); if (!ddc_excp) { if (bytect_to_write == 0) // if just wrote final empty segment to indicate done break; offset += bytect_to_write; bytes_remaining -= bytect_to_write; } } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } /** Writes a VCP table feature, with retry. * * @param dh display handle * @param vcp_code VCP feature code to write * @param value_to_set bytes of Table feature * @return NULL if success, pointer to #Ddc_Error if failure */ Error_Info * multi_part_write_with_retry( Display_Handle * dh, Byte vcp_code, Buffer * value_to_set) { Retry_Op_Value max_multi_part_write_tries = try_data_get_maxtries2(MULTI_PART_WRITE_OP); bool debug = false; if (IS_TRACING()) puts(""); DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, vcp_code=0x%02x", dh_repr(dh), vcp_code); Public_Status_Code rc = -1; // dummy value for first call of while loop Error_Info * ddc_excp = NULL; Error_Info * try_errors[MAX_MAX_TRIES]; int tryctr = 0; bool can_retry = true; while (tryctr < max_multi_part_write_tries && rc < 0 && can_retry) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Start of while loop. try_ctr=%d, max_multi_part_write_tries=%d", tryctr, max_multi_part_write_tries); ddc_excp = try_multi_part_write( dh, vcp_code, value_to_set); try_errors[tryctr] = ddc_excp; rc = (ddc_excp) ? ddc_excp->status_code : 0; assert( (ddc_excp && rc<0) || (!ddc_excp && rc==0) ); // TODO: What rc values set can_retry = false? tryctr++; } assert( (ddc_excp && rc < 0) || (!ddc_excp && rc==0) ); if (rc < 0) { if (can_retry) rc = DDCRC_RETRIES; ddc_excp= errinfo_new_with_causes(rc, try_errors, tryctr, __func__, NULL); if (rc != try_errors[tryctr-1]->status_code) COUNT_STATUS_CODE(rc); // new status code, count it } else { for (int ndx=0; ndx // SPDX-License-Identifier: GPL-2.0-or-later #include /** \cond */ #include #include #include #include #include #include "util/error_info.h" #include "util/report_util.h" /** \endcond */ #include "base/ddc_errno.h" #include "base/ddc_packets.h" #include "base/linux_errno.h" #include "base/parms.h" #include "base/rtti.h" #include "base/sleep.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_strategy_dispatcher.h" #ifdef USE_USB #include "usb/usb_displays.h" #include "usb/usb_vcp.h" #endif #include "vcp/parse_capabilities.h" #include "dynvcp/dyn_feature_set.h" #include "dynvcp/dyn_feature_codes.h" #include "ddc/ddc_multi_part_io.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_output.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; // Standard format strings for reporting feature codes. const char* FMT_CODE_NAME_DETAIL_WO_NL = "VCP code 0x%02x (%-30s): %s"; const char* FMT_CODE_NAME_DETAIL_W_NL = "VCP code 0x%02x (%-30s): %s\n"; // // VCP Feature Table inquiry // #ifdef OLD /* Checks if a feature is a table type feature, given * the VCP version of a monitor. * * For a handful of features, whether the feature is of * type Table varies based on the the VCP version. This * function encapsulates that check. * * Arguments: * frec pointer to VCP feature table entry * dh display handle of monitor * * Returns: * true if the specified feature is a table feature, * false if not */ bool is_table_feature_by_dh( VCP_Feature_Table_Entry * frec, Display_Handle * dh) { // bool debug = false; bool result = false; DDCA_MCCS_Version_Spec vcp_version = get_vcp_version_by_dh(dh); DDCA_Version_Feature_Flags feature_flags = get_version_sensitive_feature_flags(frec, vcp_version); assert(feature_flags); result = (feature_flags & DDCA_TABLE); // DBGMSF(debug, "returning: %d", result); return result; } #endif #ifdef FUTURE // For possible future use - currently unused Public_Status_Code check_valid_operation_by_feature_rec_and_version( VCP_Feature_Table_Entry * frec, DDCA_MCCS_Version_Spec vcp_version, DDCA_Version_Feature_Flags operation_flags) { DDCA_Version_Feature_Flags feature_flags = get_version_sensitive_feature_flags(frec, vcp_version); assert(feature_flags); ushort rwflags = operation_flags & DDCA_RW; ushort typeflags = operation_flags & (DDCA_NORMAL_TABLE | DDCA_CONT | DDCA_NC); Public_Status_Code result = DDCRC_INVALID_OPERATION; if ( (feature_flags & rwflags) && (feature_flags & typeflags) ) result = 0; return result; } Public_Status_Code check_valid_operation_by_feature_id_and_dh( Byte feature_id, Display_Handle * dh, DDCA_Version_Feature_Flags operation_flags) { Public_Status_Code result = 0; VCP_Feature_Table_Entry * frec = vcp_find_feature_by_hexid(feature_id); if (!frec) result = DDCRC_UNKNOWN_FEATURE; else { DDCA_MCCS_Version_Spec vcp_version = get_vcp_version_by_dh(dh); result = check_valid_operation_by_feature_rec_and_version(frec, vcp_version, operation_flags); } return result; } #endif // // Get raw VCP feature values // /* Get the raw value (i.e. bytes) for a feature table entry. * * Convert and refine status codes, issue error messages. * * Arguments; * dh display handle * frec pointer to VCP_Feature_Table_Entry for feature * ignore_unsupported if false, issue error message for unsupported feature * pvalrec location where to return pointer to feature value * msg_fh file handle for error messages * * Returns: * status code */ static Error_Info * get_raw_value_for_feature_metadata( Display_Handle * dh, Display_Feature_Metadata * frec, bool ignore_unsupported, DDCA_Any_Vcp_Value ** pvalrec, FILE * msg_fh) { assert(frec); assert(dh); assert(dh->dref); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "frec=%p, feature_code=0x%02x", frec, (frec) ? frec->feature_code : 0x00); Error_Info * ddc_excp = NULL; char * feature_name = frec->feature_name; Byte feature_code = frec->feature_code; bool is_table_feature = frec->version_feature_flags & DDCA_TABLE; DDCA_Vcp_Value_Type feature_type = (is_table_feature) ? DDCA_TABLE_VCP_VALUE : DDCA_NON_TABLE_VCP_VALUE; DDCA_Output_Level output_level = get_output_level(); DDCA_Any_Vcp_Value * valrec = NULL; if (dh->dref->io_path.io_mode == DDCA_IO_USB) { #ifdef USE_USB Public_Status_Code psc = usb_get_vcp_value( dh, feature_code, feature_type, &valrec); if (psc != 0) ddc_excp = errinfo_new(psc, __func__, NULL); #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif } else { ddc_excp = ddc_get_vcp_value( dh, feature_code, feature_type, &valrec); } ASSERT_IFF( ddc_excp, !valrec); // For now, only regard -EIO as unsupported feature for the // single model on which this has been observed if (ERRINFO_STATUS(ddc_excp) == -EIO && dh->dref->io_path.io_mode == DDCA_IO_I2C && streq(dh->dref->pedid->mfg_id, "DEL") && streq(dh->dref->pedid->model_name, "AW3418DW") ) { // Dell AW3418DW returns -EIO for unsupported features // (except for feature 0x00, which returns mh=ml=sh=sl=0) (2/2019) if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code (EIO)"); } // psc = DDCRC_DETERMINED_UNSUPPORTED; COUNT_STATUS_CODE(DDCRC_DETERMINED_UNSUPPORTED); ddc_excp = errinfo_new_with_cause( DDCRC_DETERMINED_UNSUPPORTED, ddc_excp, __func__, "EIO"); } else { Public_Status_Code psc = ERRINFO_STATUS(ddc_excp); switch( psc ) { case 0: break; case DDCRC_DDC_DATA: // was DDCRC_INVALID_DATA if (output_level >= DDCA_OL_NORMAL) f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Invalid response"); break; case DDCRC_NULL_RESPONSE: // for unsupported features, some monitors return null response rather than a valid response // with unsupported feature indicator set if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code (Null response)"); } COUNT_STATUS_CODE(DDCRC_DETERMINED_UNSUPPORTED); // psc = DDCRC_DETERMINED_UNSUPPORTED; ddc_excp = errinfo_new_with_cause( DDCRC_DETERMINED_UNSUPPORTED, ddc_excp, __func__, "DDC NULL Response"); break; case DDCRC_READ_ALL_ZERO: // treat as invalid response if not table type? if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code (All zero response)"); } // psc = DDCRC_DETERMINED_UNSUPPORTED; COUNT_STATUS_CODE(DDCRC_DETERMINED_UNSUPPORTED); ddc_excp = errinfo_new_with_cause( DDCRC_DETERMINED_UNSUPPORTED, ddc_excp, __func__, "MH=ML=SH=SL=0"); break; #ifdef FUTURE case -EIO: // Dell AW3418DW returns -EIO for unsupported features // (except for feature 0x00, which returns mh=ml=sh=sl=0) (2/2019) if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code (EIO)"); } psc = DDCRC_DETERMINED_UNSUPPORTED; COUNT_STATUS_CODE(DDCRC_DETERMINED_UNSUPPORTED); break; #endif case DDCRC_RETRIES: f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Maximum retries exceeded"); break; case DDCRC_REPORTED_UNSUPPORTED: if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code"); } break; case DDCRC_DETERMINED_UNSUPPORTED: if (!ignore_unsupported) { char text[100]; g_snprintf(text, 100, "Unsupported feature code (%s)", ddc_excp->detail); f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, text); } break; default: { char buf[200]; snprintf(buf, 200, "Invalid response. status code=%s, %s", psc_name_code(psc), dh_repr(dh)); f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, buf); } } } *pvalrec = valrec; ASSERT_IFF(!ddc_excp, *pvalrec);; DBGTRC_RET_ERRINFO_STRUCT(debug, TRACE_GROUP, ddc_excp, pvalrec, dbgrpt_single_vcp_value); return ddc_excp; } #ifdef IN_PROGRESS Public_Status_Code get_raw_value_for_feature_metadata_dfm( Display_Handle * dh, DDCA_Feature_Metadata * frec, bool ignore_unsupported, DDCA_Any_Vcp_Value ** pvalrec, FILE * msg_fh) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Starting", NULL); assert(dh); assert(dh->dref); Public_Status_Code psc = 0; Error_Info * ddc_excp = NULL; // DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); // char * feature_name = get_version_sensitive_feature_name(frec, vspec); char * feature_name = frec->feature_name; Byte feature_code = frec->feature_code; // bool is_table_feature = is_table_feature_by_dh(frec, dh); bool is_table_feature = frec->feature_flags & DDCA_TABLE; DDCA_Vcp_Value_Type feature_type = (is_table_feature) ? DDCA_TABLE_VCP_VALUE : DDCA_NON_TABLE_VCP_VALUE; DDCA_Output_Level output_level = get_output_level(); DDCA_Any_Vcp_Value * valrec = NULL; if (dh->dref->io_path.io_mode == DDCA_IO_USB) { #ifdef USE_USB psc = usb_get_vcp_value( dh, feature_code, feature_type, &valrec); if (psc != 0) ddc_excp = errinfo_new(psc, __func__); #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif } else { ddc_excp = ddc_get_vcp_value( dh, feature_code, feature_type, &valrec); psc = ERRINFO_STATUS(ddc_excp); } assert ( (psc==0 && valrec) || (psc!=0 && !valrec) ); switch(psc) { case 0: break; case DDCRC_DDC_DATA: // was DDCRC_INVALID_DATA if (output_level >= DDCA_OL_NORMAL) f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Invalid response"); break; case DDCRC_NULL_RESPONSE: // for unsupported features, some monitors return null response rather than a valid response // with unsupported feature indicator set if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code (Null response)"); } COUNT_STATUS_CODE(DDCRC_DETERMINED_UNSUPPORTED); psc = DDCRC_DETERMINED_UNSUPPORTED; break; case DDCRC_READ_ALL_ZERO: // treat as invalid response if not table type? if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code (All zero response)"); } psc = DDCRC_DETERMINED_UNSUPPORTED; COUNT_STATUS_CODE(DDCRC_DETERMINED_UNSUPPORTED); break; case DDCRC_RETRIES: f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Maximum retries exceeded"); break; case DDCRC_REPORTED_UNSUPPORTED: case DDCRC_DETERMINED_UNSUPPORTED: if (!ignore_unsupported) { f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, "Unsupported feature code"); } break; default: { char buf[200]; snprintf(buf, 200, "Invalid response. status code=%s, %s", psc_desc(psc), dh_repr(dh)); f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, buf); } } *pvalrec = valrec; DBGTRC(debug, TRACE_GROUP, "Done. Returning: %s, *pvalrec=%p", psc_desc(psc), *pvalrec); assert( (psc == 0 && *pvalrec) || (psc != 0 && !*pvalrec) ); if (*pvalrec && (debug || IS_TRACING())) { dbgrpt_single_vcp_value(*pvalrec, 1); } if (ddc_excp) { #ifdef OLD if (debug || IS_TRACING() || report_freed_exceptions) { DBGMSG("Freeing exception:"); errinfo_report(ddc_excp, 1); } errinfo_free(ddc_excp); #endif ERRINFO_FREE_WITH_REPORT(ddc_excp, debug || IS_TRACING() || report_freed_exceptions); } return psc; } #endif /* Gather values for the features in a feature set. * * Arguments: * dh display handle * feature_set feature set identifying features to be queried * vset append values retrieved to this value set * ignore_unsupported unsupported features are not an error * msg_fh destination for error messages * * Returns: * status code */ Public_Status_Code collect_raw_feature_set_values2_dfm( Display_Handle * dh, Dyn_Feature_Set* feature_set, Vcp_Value_Set vset, bool ignore_unsupported, // if false, is error if unsupported FILE * msg_fh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, msg_fh=%p", dh_repr(dh), msg_fh); Public_Status_Code master_status_code = 0; int features_ct = dyn_get_feature_set_size(feature_set); // needed when called from C API, o.w. get get NULL response for first feature // DBGMSG("Inserting sleep() before first call to get_raw_value_for_feature_table_entry()"); // sleep_millis_with_trace(DDC_TIMEOUT_MILLIS_DEFAULT, __func__, "initial"); int ndx; for (ndx=0; ndx< features_ct; ndx++) { Display_Feature_Metadata * dfm = dyn_get_feature_set_entry(feature_set, ndx); DBGMSF(debug,"ndx=%d, feature = 0x%02x", ndx, dfm->feature_code); DDCA_Any_Vcp_Value * pvalrec; // DDCA_Feature_Metadata * ddca_meta = dfm_to_ddca_feature_metadata(dfm); Error_Info * cur_ddc_excp = get_raw_value_for_feature_metadata( dh, dfm, // ddca_meta, ignore_unsupported, &pvalrec, msg_fh); // todo: free ddca_meta Public_Status_Code cur_status_code = ERRINFO_STATUS(cur_ddc_excp); if (!cur_ddc_excp) { // changed from (cur_status_code == 0) to avoid coverity complaint re resource leak vcp_value_set_add(vset, pvalrec); } else if ( (cur_status_code == DDCRC_REPORTED_UNSUPPORTED || cur_status_code == DDCRC_DETERMINED_UNSUPPORTED ) && ignore_unsupported ) { // no problem ERRINFO_FREE_WITH_REPORT(cur_ddc_excp, IS_DBGTRC(debug, TRACE_GROUP) || report_freed_exceptions); } else { ERRINFO_FREE_WITH_REPORT(cur_ddc_excp, IS_DBGTRC(debug, TRACE_GROUP) || report_freed_exceptions); master_status_code = cur_status_code; break; } } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, master_status_code, ""); return master_status_code; } /* Gather values for the features in a named feature subset * * Arguments: * dh display handle * subset feature set identifier * vset append values retrieved to this value set * ignore_unsupported unsupported features are not an error * msg_fh destination for error messages * * Returns: * status code */ Public_Status_Code ddc_collect_raw_subset_values( Display_Handle * dh, VCP_Feature_Subset subset, Vcp_Value_Set vset, bool ignore_unsupported, FILE * msg_fh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "subset=%s dh=%s, msg_fn=%p", feature_subset_name(subset), dh_repr(dh), msg_fh ); assert(subset == VCP_SUBSET_PROFILE); // currently the only use of this function, // will need to reconsider handling of Feature_Set_Flags if other // uses arise Public_Status_Code psc = 0; Feature_Set_Flags flags = FSF_NOTABLE; if (subset == VCP_SUBSET_PROFILE) flags |= FSF_RW_ONLY; Dyn_Feature_Set * feature_set = dyn_create_feature_set( subset, dh->dref, // vcp_version, flags); if (debug) dbgrpt_dyn_feature_set(feature_set, true, 0); psc = collect_raw_feature_set_values2_dfm( dh, feature_set, vset, ignore_unsupported, msg_fh); dyn_free_feature_set(feature_set); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, ""); return psc; } // // Get formatted feature values // /** Queries the monitor for a VCP feature value, and returns * a formatted interpretation of the value. * * \param dh handle for open display * \param dfm feature metadata * \param suppress_unsupported * if true, do not report unsupported features * \param prefix_value_with_feature_code * include feature code in formatted value * \param formatted_value_loc * where to return pointer to formatted value * \param msg_fh where to write extended messages for verbose * value retrieval, etc. * \return status code * * \remark * This function is a kitchen sink of functionality, extracted from * earlier code. It needs refactoring. */ Public_Status_Code ddc_get_formatted_value_for_dfm( Display_Handle * dh, Display_Feature_Metadata * dfm, bool suppress_unsupported, bool prefix_value_with_feature_code, char ** formatted_value_loc, FILE * msg_fh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "suppress_unsupported=%s", sbool(suppress_unsupported)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dfm->global_feature_flags = %s", interpret_ddca_global_feature_flags_symbolic_t(dfm->global_feature_flags)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dfm->version_feature_flags = %s", interpret_ddca_version_feature_flags_symbolic_t(dfm->version_feature_flags)); Public_Status_Code psc = 0; Error_Info * ddc_excp; *formatted_value_loc = NULL; DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "vspec=%d.%d", vspec.major, vspec.minor); // DDCA_Feature_Metadata* extmeta = dfm_to_ddca_feature_metadata(dfm); Byte feature_code = dfm->feature_code; char * feature_name = dfm->feature_name; bool is_table_feature = dfm->version_feature_flags & DDCA_TABLE; #ifndef NDEBUG DDCA_Vcp_Value_Type feature_type = (is_table_feature) ? DDCA_TABLE_VCP_VALUE : DDCA_NON_TABLE_VCP_VALUE; #endif DDCA_Output_Level output_level = get_output_level(); if (output_level >= DDCA_OL_VERBOSE) { fprintf(msg_fh, "\nGetting data for %s VCP code 0x%02x - %s:\n", (is_table_feature) ? "table" : "non-table", feature_code, feature_name); } DDCA_Any_Vcp_Value * pvalrec = NULL; // bool ignore_unsupported = !(output_level >= DDCA_OL_NORMAL && !suppress_unsupported); bool ignore_unsupported = suppress_unsupported; ddc_excp = get_raw_value_for_feature_metadata( dh, dfm, // extmeta, ignore_unsupported, &pvalrec, (output_level == DDCA_OL_TERSE) ? NULL : msg_fh); // msg_fh); psc = ERRINFO_STATUS(ddc_excp); assert( (!ddc_excp && (feature_type == pvalrec->value_type)) || (psc!=0 && !pvalrec) ); if (!ddc_excp) { // changed from (psc == 0) to avoid avoid coverity complaint re resource leak // if (!is_table_feature && output_level >= OL_VERBOSE) { // if (!is_table_feature && debug) { if (output_level >= DDCA_OL_VERBOSE || debug) { rpt_push_output_dest(msg_fh); // report_single_vcp_value(pvalrec, 0); rpt_vstring(0, "Raw value: %s", summarize_single_vcp_value(pvalrec)); rpt_pop_output_dest(); } if (output_level == DDCA_OL_TERSE) { if (is_table_feature) { // output VCP code hex values of bytes int bytect = pvalrec->val.t.bytect; int hexbufsize = bytect * 3; char * hexbuf = calloc(hexbufsize, sizeof(char)); char space = ' '; // n. buffer passed to hexstring2(), so no allocation hexstring2(pvalrec->val.t.bytes, bytect, &space, false /* upper case */, hexbuf, hexbufsize); char * formatted = calloc(hexbufsize + 20, sizeof(char)); snprintf(formatted, hexbufsize+20, "VCP %02X T x%s\n", feature_code, hexbuf); *formatted_value_loc = formatted; free(hexbuf); } else { // OL_TERSE, not table feature DDCA_Version_Feature_Flags vflags = dfm->version_feature_flags; // = get_version_sensitive_feature_flags(vcp_entry, vspec); char buf[200]; assert(vflags & (DDCA_CONT | DDCA_SIMPLE_NC | DDCA_EXTENDED_NC | DDCA_COMPLEX_NC | DDCA_NC_CONT)); if (vflags & DDCA_CONT) { snprintf(buf, 200, "VCP %02X C %d %d", feature_code, VALREC_CUR_VAL(pvalrec), VALREC_MAX_VAL(pvalrec)); } else if (vflags & DDCA_SIMPLE_NC) { snprintf(buf, 200, "VCP %02X SNC x%02x", feature_code, pvalrec->val.c_nc.sl); } else if (vflags & DDCA_EXTENDED_NC) { snprintf(buf, 200, "VCP %02X SNC x%02x x%02x", feature_code, pvalrec->val.c_nc.sh, pvalrec->val.c_nc.sl); } else { assert(vflags & (DDCA_COMPLEX_NC|DDCA_NC_CONT)); snprintf(buf, 200, "VCP %02X CNC x%02x x%02x x%02x x%02x", feature_code, pvalrec->val.c_nc.mh, pvalrec->val.c_nc.ml, pvalrec->val.c_nc.sh, pvalrec->val.c_nc.sl ); } *formatted_value_loc = g_strdup(buf); } } else { // output_level >= DDCA_OL_NORMAL bool ok; char * formatted_data = NULL; ok = dyn_format_feature_detail( dfm, vspec, pvalrec, &formatted_data); // DBGMSG("vcp_format_feature_detail set formatted_data=|%s|", formatted_data); if (!ok) { char msg[100]; if (pvalrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { g_snprintf( msg, 100, "!!! UNABLE TO FORMAT OUTPUT. mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", pvalrec->val.c_nc.mh, pvalrec->val.c_nc.ml, pvalrec->val.c_nc.sh, pvalrec->val.c_nc.sl); } else { strcpy(msg, "!!! UNABLE TO FORMAT OUTPUT"); } f0printf(msg_fh, FMT_CODE_NAME_DETAIL_W_NL, feature_code, feature_name, msg); psc = DDCRC_INTERPRETATION_FAILED; ddc_excp = errinfo_new(DDCRC_INTERPRETATION_FAILED, __func__, msg); // TODO: retry with default output function } if (ok) { if (prefix_value_with_feature_code) { *formatted_value_loc = calloc(1, strlen(formatted_data) + 50); snprintf(*formatted_value_loc, strlen(formatted_data) + 49, FMT_CODE_NAME_DETAIL_WO_NL, feature_code, feature_name, formatted_data); free(formatted_data); } else { *formatted_value_loc = formatted_data; } } } // normal (non OL_PROGRAM) output } else { // error // if output_level >= DDCA_OL_NORMAL, get_raw_value_for_feature_table_entry() already issued message if (output_level == DDCA_OL_TERSE && !suppress_unsupported) { f0printf(msg_fh, "VCP %02X ERR\n", feature_code); } } if (pvalrec) free_single_vcp_value(pvalrec); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, "*formatted_value_loc=%p -> %s", *formatted_value_loc, *formatted_value_loc); ASSERT_IFF(psc == 0, !ddc_excp); ERRINFO_FREE_WITH_REPORT(ddc_excp, debug || IS_TRACING() || report_freed_exceptions); return psc; } Public_Status_Code show_feature_set_values2_dfm( Display_Handle * dh, Dyn_Feature_Set* feature_set, GPtrArray * collector, // if null, write to current stdout device Feature_Set_Flags flags, Bit_Set_256 * features_seen) // if non-null, collect list of features seen { bool debug = false; char * s0 = feature_set_flag_names_t(flags); DBGTRC_STARTING(debug, TRACE_GROUP, "flags=%s, collector=%p", s0, collector); Public_Status_Code master_status_code = 0; FILE * outf = fout(); VCP_Feature_Subset subset_id = feature_set->subset; DDCA_Output_Level output_level = get_output_level(); bool show_unsupported = false; if ( (flags & FSF_SHOW_UNSUPPORTED) || output_level >= DDCA_OL_VERBOSE || subset_id == VCP_SUBSET_SINGLE_FEATURE #ifdef FUTURE || subset_id == VCP_SUBSET_MULTI_FEATURES #endif ) show_unsupported = true; bool suppress_unsupported = !show_unsupported; // DDCA_MCCS_Version_Spec vcp_version = get_vcp_version_by_dh(dh); bool prefix_value_with_feature_code = true; // TO FIX FILE * msg_fh = outf; // TO FIX int features_ct = dyn_get_feature_set_size(feature_set); DBGMSF(debug, "features_ct=%d", features_ct); int ndx; for (ndx=0; ndx< features_ct; ndx++) { Display_Feature_Metadata * dfm = dyn_get_feature_set_entry(feature_set, ndx); // DDCA_Feature_Metadata * extmeta = ifm->external_metadata; DBGMSF(debug,"ndx=%d, feature = 0x%02x", ndx, dfm->feature_code); if ( !(dfm->version_feature_flags & DDCA_READABLE) ) { // confuses the output if suppressing unsupported if (show_unsupported) { char * feature_name = dfm->feature_name; char * msg = (dfm->version_feature_flags & DDCA_DEPRECATED) ? "Deprecated" : "Write-only feature"; f0printf(outf, FMT_CODE_NAME_DETAIL_W_NL, dfm->feature_code, feature_name, msg); } } else { bool skip_feature = false; #ifdef NO if (subset_id != VCP_SUBSET_SINGLE_FEATURE && is_feature_table_by_vcp_version(entry, vcp_version) && (feature_flags & FSF_NOTABLE) ) { skip_feature = true; } #endif if (!skip_feature) { char * formatted_value = NULL; Public_Status_Code psc = ddc_get_formatted_value_for_dfm( dh, dfm, suppress_unsupported, prefix_value_with_feature_code, &formatted_value, msg_fh); assert( (psc==0 && formatted_value) || (psc!=0 && !formatted_value) ); if (psc == 0) { if (collector) g_ptr_array_add(collector, formatted_value); else f0printf(outf, "%s\n", formatted_value); free(formatted_value); if (features_seen) *features_seen = bs256_insert(*features_seen, dfm->feature_code); // note that feature was read } else { // or should I check features_ct == 1? VCP_Feature_Subset subset_id = feature_set->subset; if (subset_id == VCP_SUBSET_SINGLE_FEATURE) master_status_code = psc; else { if ( (psc != DDCRC_REPORTED_UNSUPPORTED) && (psc != DDCRC_DETERMINED_UNSUPPORTED) ) { if (master_status_code == 0) master_status_code = psc; } } } } // !skip_feature } DBGMSF(debug,"ndx=%d, feature = 0x%02x Done", ndx, dfm->feature_code); } // loop over features DBGTRC_RET_DDCRC(debug, TRACE_GROUP, master_status_code, ""); return master_status_code; } #ifdef FUTURE //typedef bool (*VCP_Feature_Set_Filter_Func)(VCP_Feature_Table_Entry * ventry); bool hack42(VCP_Feature_Table_Entry * ventry) { bool debug = false; bool result = true; // if (ventry->code >= 0xe0) { // is everything promoted to int before comparison? if ( (ventry->vcp_global_flags & DDCA_SYNTHETIC) && (ventry->v20_flags & DDCA_NORMAL_TABLE) ) { result = false; DBGMSF(debug, "Returning false for vcp code 0x%02x", ventry->code); } return result; } #endif /** Shows the VCP values for all features in a VCP feature subset. * * @param dh display handle for open display * @param subset feature subset id * @param collector accumulates output // if null, write to current stdout device * @param flags feature set flags * @param features_seen collects ids of features that exist * @return status code */ // 11/2019: only call is from app_getvcp.c, move there? Public_Status_Code ddc_show_vcp_values( Display_Handle * dh, VCP_Feature_Subset subset, GPtrArray * collector, // not used Feature_Set_Flags flags, Bit_Set_256 * features_seen) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "subset=%s, flags=%s, dh=%s", feature_subset_name(subset), feature_set_flag_names_t(flags), dh_repr(dh) ); Public_Status_Code psc = 0; // DDCA_MCCS_Version_Spec vcp_version = get_vcp_version_by_dh(dh); // DBGMSG("VCP version = %d.%d", vcp_version.major, vcp_version.minor); Dyn_Feature_Set* feature_set = dyn_create_feature_set( subset, dh->dref, // vcp_version, flags); #ifdef FUTURE Parsed_Capabilities * pcaps = NULL; // TODO: HOW TO GET Parsed_Capabilities?, will only be set for probe/interrogate // special case, if scanning, don't try to do a table read of manufacturer specific // features if it's clear that table read commands are unavailable // convoluted solution to avoid passing additional argument to create_feature_set() if (subset == VCP_SUBSET_SCAN && !parsed_capabilities_may_support_table_commands(pcaps)) { filter_feature_set(feature_set, hack42); } #endif if (IS_DBGTRC(debug, TRACE_GROUP)) { DBGTRC(true, TRACE_GROUP, "feature_set:"); dbgrpt_dyn_feature_set(feature_set, true, 0); } psc = show_feature_set_values2_dfm( dh, feature_set, collector, flags, features_seen); dyn_free_feature_set(feature_set); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, ""); return psc; } void init_ddc_output() { RTTI_ADD_FUNC(get_raw_value_for_feature_metadata); RTTI_ADD_FUNC(collect_raw_feature_set_values2_dfm); RTTI_ADD_FUNC(ddc_collect_raw_subset_values); RTTI_ADD_FUNC(ddc_get_formatted_value_for_dfm); RTTI_ADD_FUNC(show_feature_set_values2_dfm); RTTI_ADD_FUNC(ddc_show_vcp_values); } ddcutil-2.2.0/src/ddc/ddc_packet_io.c0000644000175000001440000011520614754153540013072 /** \file ddc_packet_io.c * * Functions for performing DDC packet IO, using either the I2C bus API * or the ADL API, as appropriate. Handles I2C bus retry. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later // N. ddc_open_display() and ddc_close_display() handle case USB, but the // packet functions are for I2C and ADL only. Consider splitting. /** \cond */ #include #include #include #include #include #include #include #include #include #include #include "public/ddcutil_types.h" #include "util/debug_util.h" #include "util/edid.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #include "util/utilrpt.h" /** \endcond */ #include "base/core.h" #include "base/ddc_errno.h" #include "base/ddc_packets.h" #include "base/displays.h" #include "base/dsa2.h" #include "base/execution_stats.h" #include "base/i2c_bus_base.h" #include "base/parms.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/status_code_mgt.h" #include "base/tuned_sleep.h" #include "base/per_display_data.h" #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_dpms.h" #include "i2c/i2c_bus_core.h" #include "i2c/i2c_strategy_dispatcher.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #endif #include "ddc/ddc_displays.h" #include "ddc/ddc_try_data.h" #include "ddc/ddc_packet_io.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDCIO; bool DDC_Read_Bytewise = DEFAULT_DDC_READ_BYTEWISE; bool simulate_null_msg_means_unsupported = false; static GHashTable * open_displays = NULL; static GMutex open_displays_mutex; #ifdef DEPRECATED // Deprecated - use all_bytes_zero() in string_util.c // Tests if a range of bytes is entirely 0 bool all_zero(Byte * bytes, int bytect) { bool result = true; int ndx = 0; for (; ndx < bytect; ndx++) { if (bytes[ndx] != 0x00) { result = false; break; } } return result; } #endif // Test for DDC null message #ifdef UNUSED bool is_ddc_null_message(Byte * packet) { return (packet[0] == 0x6f && packet[1] == 0x6e && packet[2] == 0x80 && packet[3] == 0xbe ); } #endif #ifdef DEPRECATED bool ddc_is_valid_display_handle(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%p", dh); assert(open_displays); g_mutex_lock (&open_displays_mutex); bool result = g_hash_table_contains(open_displays, dh); g_mutex_unlock(&open_displays_mutex); DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, "dh=%s", dh_repr(dh)); return result; } #endif #ifdef OLD DDCA_Status ddc_validate_display_handle(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%p", dh); assert(open_displays); // DDCA_Status result = ddc_validate_display_ref(dh->dref, /*basic_only*/ false, /*test_asleep*/ true); DDCA_Status result = ddc_validate_display_ref2(dh->dref, DREF_VALIDATE_EDID|DREF_VALIDATE_AWAKE); if (result == DDCRC_OK) { g_mutex_lock (&open_displays_mutex); if (!g_hash_table_contains(open_displays, dh) ) result = DDCRC_ARG; g_mutex_unlock(&open_displays_mutex); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, "dh=%s", dh_repr(dh)); return result; } #endif DDCA_Status ddc_validate_display_handle2(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%p", dh); assert(open_displays); DDCA_Status result = DDCRC_OK; // DDCA_Status result = ddc_validate_display_ref2(dh->dref, DREF_VALIDATE_EDID|DREF_VALIDATE_AWAKE); // DDCA_Status result = ddc_validate_display_ref2(dh->dref, DREF_VALIDATE_BASIC_ONLY); if (dh->dref->flags & DREF_REMOVED) { result = DDCRC_DISCONNECTED; } if (result == DDCRC_OK) { g_mutex_lock (&open_displays_mutex); if (!g_hash_table_contains(open_displays, dh) ) result = DDCRC_ARG; g_mutex_unlock(&open_displays_mutex); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, "dh=%s", dh_repr(dh)); return result; } void ddc_dbgrpt_valid_display_handles(int depth) { rpt_vstring(depth, "Valid display handle = open_displays:"); assert(open_displays); g_mutex_lock (&open_displays_mutex); GList * display_handles = g_hash_table_get_keys(open_displays); if (g_list_length(display_handles) > 0) { for (GList * cur = display_handles; cur; cur = cur->next) { Display_Handle * dh = cur->data; rpt_vstring(depth+1, "%p -> %s", dh, dh_repr(dh)); } } else { rpt_vstring(depth+1, "None"); } g_list_free(display_handles); g_mutex_unlock(&open_displays_mutex); } // TODO: generalize, move to more appropriate location static bool is_drm_conformant_driver(const char * driver_name) { return streq(driver_name, "amdgpu") || streq(driver_name, "i915"); } // // Open/Close Display // /** Opens a DDC display. * * \param dref display reference * \param callopts call option flags * \param dh_loc address at which to return display handle * \return Error_Info if error, with status * status code from #i2c_open_bus(), #usb_open_hiddev_device() * DDCRC_LOCKED display open in another thread * DDCRC_ALREADY_OPEN display already open in current thread * DDCRC_DISCONNECTED display has been disconnected * * **Call_Option** flags recognized: * - CALLOPT_WAIT */ Error_Info * ddc_open_display( Display_Ref * dref, Call_Options callopts, Display_Handle** dh_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s, callopts=%s, dh_loc=%p", dref_reprx_t(dref), interpret_call_options_t(callopts), dh_loc ); TRACED_ASSERT(dh_loc); // TRACED_ASSERT(1==5); // for testing Display_Handle * dh = NULL; Error_Info * err = NULL; int fd = -1; const char * driver_name = dref_get_i2c_driver(dref); DBGTRC_NOPREFIX(false, DDCA_TRC_NONE, "driver_name: %s", driver_name); if (driver_name && is_drm_conformant_driver(driver_name) && dref->drm_connector && strlen(dref->drm_connector) > 0) { possibly_write_detect_to_status_by_dref(dref); char * status; int tryct = 0; retry_status: RPT_ATTR_TEXT(-1, &status, "/sys/class/drm", dref->drm_connector, "status"); if (streq(status, "disconnected")) { if (tryct == 0) { free(status); // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "status == disconnected, sleeping 1 sec and retrying"); DW_SLEEP_MILLIS(1000, "Delay before rechecking attribute status"); tryct++; goto retry_status; } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s still disconnected after 1 second delay and retry", dref_reprx_t(dref)); SYSLOG2(DDCA_SYSLOG_WARNING, "%s still disconnected after 1 second delay and retry", dref_reprx_t(dref)); err = ERRINFO_NEW(DDCRC_DISCONNECTED, "Display disconnected"); } free(status); if (err) goto bye; } #ifdef NO Display_Lock_Flags ddisp_flags = DDISP_NONE; if (callopts & CALLOPT_WAIT) ddisp_flags |= DDISP_WAIT; err = lock_display_by_dref(dref, ddisp_flags); if (err) goto bye; #endif switch (dref->io_path.io_mode) { case DDCA_IO_I2C: { I2C_Bus_Info * bus_info = dref->detail; TRACED_ASSERT(bus_info); // need to convert to a test? TRACED_ASSERT( bus_info && memcmp(bus_info, I2C_BUS_INFO_MARKER, 4) == 0); if (!bus_info->edid) { // How is this even possible? // 1/2017: Observed with x260 laptop and Ultradock, See ddcutil user report. // close(fd) fails char * msg = g_strdup_printf("No EDID for device on bus /dev/"I2C"-%d", dref->io_path.path.i2c_busno); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "%s", msg); err = ERRINFO_NEW(DDCRC_EDID, "%s", msg); free(msg); } if (!err) { DBGMSF(debug, "Calling i2c_open_bus() ..."); Error_Info * err2 = i2c_open_bus(dref->io_path.path.i2c_busno, callopts, &fd); ASSERT_IFF(err2, fd == -1); if (err2) { err = errinfo_new_with_cause(err2->status_code, err2, __func__, "Opening /dev/i2c-%d", dref->io_path.path.i2c_busno); } } if (!err) { dh = create_base_display_handle(fd, dref); if (!dref->pedid) dref->pedid = copy_parsed_edid(bus_info->edid); if (!dref->pdd) dref->pdd = pdd_get_per_display_data(dref->io_path, true); } } break; case DDCA_IO_USB: #ifdef ENABLE_USB { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Opening USB device: %s", dref->usb_hiddev_name); TRACED_ASSERT(dref && dref->usb_hiddev_name); // if (!dref->usb_hiddev_name) { // HACK // DBGMSG("HACK FIXUP. dref->usb_hiddev_name"); // dref->usb_hiddev_name = get_hiddev_devname_by_dref(dref); // } fd = usb_open_hiddev_device(dref->usb_hiddev_name, callopts); if (fd < 0) { err = ERRINFO_NEW(fd, "Error opening %s", dref->usb_hiddev_name); } else { dh = create_base_display_handle(fd, dref); if (!dref->pedid) dref->pedid = copy_parsed_edid(usb_get_parsed_edid_by_dh(dh)); if (!dref->pdd) dref->pdd = pdd_get_per_display_data(dref->io_path, true); } } #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); assert(false); // avoid coverity error re null dreference #endif break; } // switch ASSERT_IFF(!err, dh); if (!err) { assert(dh->dref->pedid); dref->flags |= DREF_OPEN; TRACED_ASSERT(open_displays); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding dh=%s to open_displays hash table", dh_repr_p(dh)); g_mutex_lock (&open_displays_mutex); g_hash_table_add(open_displays, dh); g_mutex_unlock(&open_displays_mutex); } else { #ifdef NO Error_Info * err2 = unlock_display_by_dref(dref); if (err2) { PROGRAM_LOGIC_ERROR("unlock_distinct_display() returned %s", errinfo_summary(err)); errinfo_free(err2); } #endif } bye: if (err) { COUNT_STATUS_CODE(err->status_code); } *dh_loc = dh; TRACED_ASSERT_IFF( !err, *dh_loc ); // dbgrpt_distinct_display_descriptors(0); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, "*dh_loc=%s", dh_repr_p(*dh_loc)); return err; } /** Closes a DDC display. * * @param dh display handle * @return NULL if no error, #Error_Info struct if error * * @remark * Logs underlying status code if error. */ Error_Info * ddc_close_display(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, dref=%s, fd=%d, dpath=%s", dh_repr_p(dh), dref_repr_t(dh->dref), dh->fd, dpath_short_name_t(&dh->dref->io_path)); Display_Ref * dref = dh->dref; Error_Info * err = NULL; Status_Errno rc = 0; if (dh->fd == -1) { rc = DDCRC_INVALID_OPERATION; // or DDCRC_ARG? err = ERRINFO_NEW(rc, "Invalid display handle"); } else { switch(dh->dref->io_path.io_mode) { case DDCA_IO_I2C: { DBGMSF(debug, "Calling is2_close_bus() ..."); rc = i2c_close_bus(dh->dref->io_path.path.i2c_busno, dh->fd, CALLOPT_NONE); if (rc != 0) { TRACED_ASSERT(rc < 0); char * msg = g_strdup_printf("i2c_close_bus returned %d, errno=%s", rc, psc_desc(errno) ); SYSLOG2(DDCA_SYSLOG_ERROR, "%s", msg); err = errinfo_new(rc, __func__, msg); free(msg); COUNT_STATUS_CODE(rc); } dh->fd = -1; // indicate invalid, in case we try to continue using dh break; } case DDCA_IO_USB: #ifdef ENABLE_USB { rc = usb_close_device(dh->fd, dh->dref->usb_hiddev_name, CALLOPT_NONE); if (rc != 0) { TRACED_ASSERT(rc < 0); char * msg = g_strdup_printf("usb_close_bus returned %d, errno=%s", rc, psc_desc(errno) ); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "%s", msg); err = ERRINFO_NEW(rc, "%s", msg); free(msg); COUNT_STATUS_CODE(rc); } dh->fd = -1; break; } #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif } //switch } dh->dref->flags &= (~DREF_OPEN); #ifdef NO Error_Info * err2 = unlock_display_by_dref(dref); if (err2) { SYSLOG2(DDCA_SYSLOG_ERROR, "%s", err2->detail); if (!err) err = err2; else BASE_ERRINFO_FREE_WITH_REPORT(err2, true); } #endif assert(open_displays); g_mutex_lock (&open_displays_mutex); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Removing dh=%s from open_displays hash table of size %d", dh_repr_p(dh), g_hash_table_size(open_displays) ); g_hash_table_remove(open_displays, dh); g_mutex_unlock (&open_displays_mutex); free_display_handle(dh); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, "dref=%s", dref_repr_t(dref)); return err; } // Handles common case where the return value of ddc_close_display is ignored void ddc_close_display_wo_return(Display_Handle * dh) { Error_Info * err = ddc_close_display(dh); if (err) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "%s: %s", err->detail, psc_desc(err->status_code)); ERRINFO_FREE_WITH_REPORT(err, true); } } /** Closes all open displays, ignoring any errors */ void ddc_close_all_displays() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); assert(open_displays); // ddc_dbgrpt_valid_display_handles(2); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Closing %d open displays",g_hash_table_size(open_displays)); GList * display_handles = g_hash_table_get_keys(open_displays); for (GList * cur = display_handles; cur; cur = cur->next) { Display_Handle * dh = cur->data; ddc_close_display_wo_return(dh); } g_free(display_handles); // open_displays should be empty at this point TRACED_ASSERT(g_hash_table_size(open_displays) == 0); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // work in progress // typedef for ddc_i2c_write_read_raw, ddc_adl_write_read_raw, ddc_write_read_raw typedef DDCA_Status (*Write_Read_Raw_Function)( Display_Handle * dh, DDC_Packet * request_packet_ptr, int max_read_bytes, Byte * readbuf, int * pbytes_received ); // // Write and read operations that take DDC_Packets // /* Writes a DDC request packet to an open I2C bus * and returns the raw response. * * Arguments: * dh display handle for open I2C bus * request_packet_ptr DDC packet to write * max_read_bytes maximum number of bytes to read * readbuf where to return response * pbytes_received where to write count of bytes received * (always equal to max_read_bytes * * Returns: * 0 if success * -errno if error in write * DDCRC_READ_ALL_ZERO */ // not static so that function can appear in backtrace DDCA_Status ddc_i2c_write_read_raw( Display_Handle * dh, DDC_Packet * request_packet_ptr, bool read_bytewise, int max_read_bytes, Byte * readbuf, int * pbytes_received ) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, read_bytewise=%s, max_read_bytes=%d, readbuf=%p", dh_repr(dh), SBOOL(read_bytewise), max_read_bytes, readbuf ); // DBGMSG("request_packet_ptr=%p", request_packet_ptr); // dump_packet(request_packet_ptr); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "request_packet_ptr->raw_bytes: %s", hexstring3_t(request_packet_ptr->raw_bytes->bytes, request_packet_ptr->raw_bytes->len, " ", 1, false) ); TRACED_ASSERT(dh); TRACED_ASSERT(dh->dref); TRACED_ASSERT(dh && dh->dref && dh->dref->io_path.io_mode == DDCA_IO_I2C); // This function should not be called for USB #ifdef TEST_THAT_DIDNT_WORK bool single_byte_reads = false; // doesn't work #endif #ifndef NDEBUG Byte slave_addr = request_packet_ptr->raw_bytes->bytes[0]; // 0x6e TRACED_ASSERT(slave_addr >> 1 == 0x37); #endif CHECK_DEFERRED_SLEEP(dh); Status_Errno_DDC rc = invoke_i2c_writer( dh->fd, 0x37, get_packet_len(request_packet_ptr)-1, get_packet_start(request_packet_ptr)+1 ); DBGMSF(debug, "invoke_i2c_writer() returned %d", rc); if (rc == 0) { TUNED_SLEEP_WITH_TRACE(dh, SE_WRITE_TO_READ, "Called from ddc_i2c_write_read_raw"); // ALTERNATIVE_THAT_DIDNT_WORK: // if (single_byte_reads) // fails // rc = invoke_single_byte_i2c_reader(dh->fd, max_read_bytes, readbuf); // else CHECK_DEFERRED_SLEEP(dh); rc = invoke_i2c_reader(dh->fd, 0x37, read_bytewise, max_read_bytes, readbuf); // try adding sleep to see if improves capabilities read for P2411H // tuned_sleep_i2c_with_trace(SE_POST_READ, __func__, NULL); TUNED_SLEEP_WITH_TRACE(dh, SE_POST_READ, "Called from ddc_i2c_write_read_raw"); if (rc == 0) DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Response bytes: %s", hexstring3_t(readbuf, max_read_bytes, " ", 1, false) ); if (rc == 0 && all_bytes_zero(readbuf, max_read_bytes)) { DDCMSG(debug, "All zero response detected in %s", __func__); rc = DDCRC_READ_ALL_ZERO; // printf("(%s) All zero response.", __func__ ); // DBGMSG("Request was: %s", // hexstring(get_packet_start(request_packet_ptr)+1,get_packet_len(request_packet_ptr)-1)); } } if (rc < 0) { COUNT_STATUS_CODE(rc); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } /** Writes a DDC request packet to a monitor and provides basic response parsing * based whether the response type is continuous, non-continuous, or table. * * \param dh display handle (for either I2C or ADL device) * \param request_packet_ptr DDC packet to write * \param max_read_bytes maximum number of bytes to read * \param expected_response_type expected response type to check for * \param expected_subtype expected subtype to check for * \param response_packet_ptr_loc where to write address of response packet received * * \return pointer to #Error_Info struct if failure, NULL if success * \remark * Issue: positive ADL codes, need to handle? */ Error_Info * ddc_write_read( Display_Handle * dh, DDC_Packet * request_packet_ptr, bool read_bytewise, int max_read_bytes, Byte expected_response_type, Byte expected_subtype, DDC_Packet ** response_packet_ptr_loc ) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, read_bytewise=%s, max_read_bytes=%d," " expected_response_type=0x%02x, expected_subtype=0x%02x", dh_repr(dh), SBOOL(read_bytewise), max_read_bytes, expected_response_type, expected_subtype ); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding 1 to max_read_bytes to allow for initial double 0x63 quirk"); max_read_bytes++; //allow for quirk of double 0x6e at start Byte * readbuf = calloc(1, max_read_bytes); int bytes_received = max_read_bytes; DDCA_Status psc; *response_packet_ptr_loc = NULL; psc = ddc_i2c_write_read_raw( dh, request_packet_ptr, read_bytewise, max_read_bytes, readbuf, &bytes_received ); if (psc >= 0) { // readbuf[0] = 0x6e; // hex_dump(readbuf, bytes_received+1); psc = create_ddc_typed_response_packet( readbuf, bytes_received, expected_response_type, expected_subtype, __func__, response_packet_ptr_loc); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "create_ddc_typed_response_packet() returned %s, *response_packet_ptr_loc=%p", ddcrc_desc_t(psc), *response_packet_ptr_loc ); if (psc == DDCRC_OK && simulate_null_msg_means_unsupported) { DDC_Packet * pkt = *response_packet_ptr_loc; if ( pkt && pkt->type == DDC_PACKET_TYPE_QUERY_VCP_RESPONSE) { Parsed_Nontable_Vcp_Response * resp = pkt->parsed.nontable_response; if (resp->valid_response && !resp->supported_opcode) { DBGMSG("Setting DDCRC_NULL_RESPONSE for unsupported feature 0x%02x",resp->vcp_code); psc = DDCRC_NULL_RESPONSE; } } } if (psc != 0 && *response_packet_ptr_loc) { // paranoid, should never occur free(*response_packet_ptr_loc); *response_packet_ptr_loc = NULL; } } free(readbuf); // or does response_packet_ptr_loc point into here? Error_Info * excp = (psc < 0) ? ERRINFO_NEW(psc,NULL) : NULL; DBGTRC_RET_ERRINFO_STRUCT(debug, TRACE_GROUP, excp, response_packet_ptr_loc, dbgrpt_packet); return excp; } /** Wraps #ddc_write_read() in retry logic. * * \param dh display handle (for either I2C or ADL device) * \param request_packet_ptr DDC packet to write * \param max_read_bytes maximum number of bytes to read * \param expected_response_type expected response type to check for * \param expected_subtype expected subtype to check for * \param all_zero_response_ok treat a response of all 0s as valid * \param response_packet_ptr_loc where to write address of response packet received * * \return pointer to #Error_Info struct if failure, NULL if success */ Error_Info * ddc_write_read_with_retry( Display_Handle * dh, DDC_Packet * request_packet_ptr, int max_read_bytes, Byte expected_response_type, Byte expected_subtype, DDC_Write_Read_Flags flags, DDC_Packet ** response_packet_ptr_loc ) { bool debug = false; bool all_zero_response_ok = flags & Write_Read_Flag_All_Zero_Response_Ok; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, max_read_bytes=%d, expected_response_type=0x%02x, expected_subtype=0x%02x," " all_zero_response_ok=%s, Write_Read_Flag_All_Zero_Response_Ok: %s", dh_repr(dh), max_read_bytes, expected_response_type, expected_subtype, sbool(all_zero_response_ok), sbool(flags&Write_Read_Flag_All_Zero_Response_Ok) ); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dref flags: %s", interpret_dref_flags_t(dh->dref->flags)); Per_Display_Data * pdd = dh->dref->pdd; TRACED_ASSERT(dh->dref->io_path.io_mode != DDCA_IO_USB); // show_backtrace(1); // if (debug) // dbgrpt_display_ref(dh->dref, 1); bool read_bytewise = DDC_Read_Bytewise; // normally set to DEFAULT_I2C_READ_BYTEWISE DDCA_Status psc; int tryctr; bool retryable; int ddcrc_read_all_zero_ct = 0; int ddcrc_null_response_ct = 0; int max_tries = try_data_get_maxtries2(WRITE_READ_TRIES_OP); int ddcrc_null_response_max = 3; Error_Info * master_error = NULL; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE,"ddcrc_null_response_max=%d, read_bytewise=%s", ddcrc_null_response_max, sbool(read_bytewise)); Error_Info * try_errors[MAX_MAX_TRIES] = {NULL}; TRACED_ASSERT(max_tries >= 1); for (tryctr=0, psc=-999, retryable=true; tryctr < max_tries && psc < 0 && retryable; tryctr++) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Start of try loop, tryctr=%d, max_tries=%d, psc=%s, retryable=%s, " "read_bytewise=%s, sleep-multiplier=%5.2f", tryctr, max_tries, psc_name_code(psc), sbool(retryable), sbool(read_bytewise), pdd_get_adjusted_sleep_multiplier(pdd) ); Error_Info * cur_excp = ddc_write_read( dh, request_packet_ptr, read_bytewise, max_read_bytes, expected_response_type, expected_subtype, response_packet_ptr_loc); ASSERT_IFF(!cur_excp, *response_packet_ptr_loc); // TESTCASES: // if (tryctr < 2) // cur_excp = ERRINFO_NEW(DDCRC_NULL_RESPONSE, "dummy"); // cur_excp = errinfo_new(-EIO, "dummy"); psc = (cur_excp) ? cur_excp->status_code : 0; try_errors[tryctr] = cur_excp; if (psc == 0 && ddcrc_null_response_ct > 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP | DDCA_TRC_RETRY, "%s, expected_subtype=0x%02x, sleep-multiplier=%5.2f, ddc_write_read() succeeded" " after %d sleep and retry for DDC Null Response", dh_repr(dh), expected_subtype, pdd_get_adjusted_sleep_multiplier(pdd), ddcrc_null_response_ct); SYSLOG2(DDCA_SYSLOG_DEBUG, "%s, expected_subtype=0x%02x, sleep-multiplier=%5.2f, ddc_write_read() succeeded" " after %d sleep and retry for DDC Null Response", dh_repr(dh), expected_subtype, pdd_get_adjusted_sleep_multiplier(pdd), ddcrc_null_response_ct); } bool adjust_remaining_tries_for_null = false; if (psc < 0) { // n. ADL status codes have been modulated DBGMSF(debug, "ddc_write_read() returned %s", psc_desc(psc) ); COUNT_RETRYABLE_STATUS_CODE(psc); TRACED_ASSERT(dh->dref->io_path.io_mode == DDCA_IO_I2C); // The problem: Does NULL response indicate an error condition, or // is the monitor using NULL response to indicate unsupported? // Acer monitor uses NULL response instead of setting the unsupported // flag in a valid response switch (psc) { case DDCRC_NULL_RESPONSE: { // testing_unsupported_feature_active really is redundant, // DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED is set upon completion of // testing for unsupported feature assert( !(dh->testing_unsupported_feature_active && dh->dref->flags & DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED) ); if (!dh->testing_unsupported_feature_active) { bool may_mean_unsupported_feature = (expected_response_type == DDC_PACKET_TYPE_QUERY_VCP_RESPONSE && (dh->dref->flags & DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED)) || expected_response_type == DDC_PACKET_TYPE_TABLE_READ_RESPONSE; if (may_mean_unsupported_feature) { adjust_remaining_tries_for_null = true; retryable = (++ddcrc_null_response_ct <= ddcrc_null_response_max); DBGTRC(debug, DDCA_TRC_NONE, "DDCRC_NULL_RESPONSE, retryable=%s", sbool(retryable)); if (!retryable) { MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "Feature 0x%02x, maximum retries (%d) for DDC Null Response exceeded", expected_subtype, ddcrc_null_response_max); } } } else retryable = true; } break; case (DDCRC_READ_ALL_ZERO): // Sometimes an all-zero response indicates an unsupported feature // instead of an error. On Dell P2411 and U3011 the all zero response occurs // when reading an unsupported table feature. retryable = (all_zero_response_ok) ? false : true; ddcrc_read_all_zero_ct++; break; case (-EIO): retryable = false; // ?? break; case (-EBADF): // DBGMSG("EBADF"); retryable = false; break; case (-ENXIO): // no such device or address, i915 driver // But have seen success after 7 retries of errors including ENXIO, DDCRC_DATA, make retryable? retryable = false; break; case (-EBUSY): retryable = false; break; default: retryable = true; // for now } if (psc == -EIO || psc == -ENXIO) { Error_Info * err = i2c_check_open_bus_alive(dh) ; if (err) { // psc = err->status_code; // retryable = false; // errinfo_free(err); master_error = err; goto bye; } } // try exponential backoff on all errors, not just SE_DDC_NULL // if (retryable) // call_dynamic_tuned_sleep_i2c(SE_DDC_NULL, tryctr+1); } // rc < 0 DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Bottom of try loop. psc=%s, tryctr=%d, ddcrc_null_response_ct=%d, retryable=%s", psc_name_code(psc), tryctr, ddcrc_null_response_ct, sbool(retryable)); int remaining_tries = (max_tries-1) - tryctr; int adjusted_remaining_tries = remaining_tries; if (adjust_remaining_tries_for_null) { adjusted_remaining_tries = (ddcrc_null_response_max-1) - tryctr; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "tryctr = %d, unadjusted remaining_tries=%d, adjusted_remaining_tries=%d", tryctr, remaining_tries, adjusted_remaining_tries); } if (psc != 0 && retryable && remaining_tries > 0) { pdd_note_retryable_failure_by_dh(dh, psc, adjusted_remaining_tries); } } // for loop // tryctr = number of times through loop, i.e. 1..max_tries assert(tryctr >= 1 && tryctr <= max_tries); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "After try loop. tryctr=%d, psc=%s, ddcrc_null_response_ct=%d, retryable=%s", tryctr, psc_name_code(psc), ddcrc_null_response_ct, sbool(retryable) ); bool all_responses_null_meant_unsupported = false; int adjusted_tryctr = tryctr; if ( ( (dh->dref->flags & DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED) || expected_response_type == DDC_PACKET_TYPE_TABLE_READ_RESPONSE ) && !(flags & Write_Read_Flag_Capabilities) && ddcrc_null_response_ct == tryctr) { all_responses_null_meant_unsupported = true; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "DREF_DDC_USES_NULL_RESPONSE_FOR_UNSUPPORTED or table read and all responses null"); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "adjusting try count passed to pdd_record_final_by_dh() to 1"); // don't pollute the stats with try counts that don't reflect real errors adjusted_tryctr = 1; } pdd_record_final_by_dh(dh, psc, adjusted_tryctr); Error_Info * errors_found[MAX_MAX_TRIES]; int errct = 0; for (int ndx = 0; ndx < MAX_MAX_TRIES; ndx++) { if (try_errors[ndx]) errors_found[errct++] = try_errors[ndx]; } char * s = errinfo_array_summary(errors_found, errct); DBGTRC_NOPREFIX(debug, TRACE_GROUP | DDCA_TRC_RETRY, "%s,%s after %d error(s): %s", dh_repr(dh), (psc == 0) ? "Succeeded" : "Failed", errct, s); free(s); if (psc < 0) { // int last_try_index = tryctr-1; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "After try loop. tryctr=%d, retryable=%s", tryctr, sbool(retryable)); if (retryable) psc = DDCRC_RETRIES; else if (ddcrc_read_all_zero_ct == max_tries) psc = DDCRC_ALL_TRIES_ZERO; else if (all_responses_null_meant_unsupported) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Converting DDCRC_ALL_RESPONSES_NULL to DDCRC_DETERMINED_UNSUPPORTED"); psc = DDCRC_DETERMINED_UNSUPPORTED; } else if (ddcrc_null_response_ct > ddcrc_null_response_max) { psc = DDCRC_ALL_RESPONSES_NULL; } master_error = errinfo_new_with_causes(psc, errors_found, errct, __func__, NULL); if (psc != try_errors[tryctr-1]->status_code) COUNT_STATUS_CODE(psc); // new status code, count it } else { for (int ndx = 0; ndx < tryctr-1; ndx++) { BASE_ERRINFO_FREE_WITH_REPORT(try_errors[ndx], IS_DBGTRC(debug, TRACE_GROUP)); } } try_data_record_tries2(dh, WRITE_READ_TRIES_OP, psc, tryctr); bye: DBGTRC_DONE(debug, TRACE_GROUP, "Total Tries (tryctr): %d. *response_packet_pointer_loc=%p, Returning: %s", tryctr, *response_packet_ptr_loc, errinfo_summary(master_error)); ASSERT_IFF(!master_error, *response_packet_ptr_loc); return master_error; } /* Writes a DDC request packet to an open I2C bus. * * Arguments: * fh Linux file handle for open I2C bus * request_packet_ptr DDC packet to write * * Returns: * 0 if success * -errno if error */ static Status_Errno_DDC ddc_i2c_write_only( Display_Handle * dh, DDC_Packet * request_packet_ptr ) { bool debug = false; int fh = dh->fd; DBGTRC_STARTING(debug, TRACE_GROUP, ""); if (debug) dbgrpt_packet(request_packet_ptr, 2); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "request_packet_ptr->raw_bytes: %s", hexstring3_t(request_packet_ptr->raw_bytes->bytes, request_packet_ptr->raw_bytes->len, " ", 1, false) ); Byte slave_address = 0x37; CHECK_DEFERRED_SLEEP(dh); Status_Errno_DDC rc = invoke_i2c_writer(fh, slave_address, get_packet_len(request_packet_ptr)-1, get_packet_start(request_packet_ptr)+1 ); if (rc < 0) log_status_code(rc, __func__); Sleep_Event_Type sleep_type = (request_packet_ptr->type == DDC_PACKET_TYPE_SAVE_CURRENT_SETTINGS ) ? SE_POST_SAVE_SETTINGS : SE_POST_WRITE; TUNED_SLEEP_WITH_TRACE(dh, sleep_type, "Called from ddc_i2c_write_only"); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } /* Writes a DDC request packet to a monitor * * \param dh Display_Handle for open I2C or ADL device * \param request_packet_ptr DDC packet to write * \return NULL if success, #Error_Info struct if error * * @todo * Eliminate this function, it used to route to the ADL version as * well as ddc_i2c_write_only() */ Error_Info * ddc_write_only( Display_Handle * dh, DDC_Packet * request_packet_ptr) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); TRACED_ASSERT(dh->dref->io_path.io_mode == DDCA_IO_I2C); DDCA_Status psc = ddc_i2c_write_only(dh, request_packet_ptr); Error_Info * ddc_excp = (psc) ? ERRINFO_NEW(psc,NULL) : NULL; DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", errinfo_summary(ddc_excp)); return ddc_excp; } /* Wraps ddc_write_only() in retry logic. * * \param dh display handle (for either I2C or ADL device) * \param request_packet_ptr DDC packet to write * \return pointer to #Error_Info struct if failure, NULL if success * * The maximum number of tries allowed has been set in global variable * max_write_only_exchange_tries. */ Error_Info * ddc_write_only_with_retry( Display_Handle * dh, DDC_Packet * request_packet_ptr) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "" ); TRACED_ASSERT(dh->dref->io_path.io_mode == DDCA_IO_I2C); DDCA_Status psc; int tryctr; bool retryable; Error_Info * try_errors[MAX_MAX_TRIES]; int max_tries = try_data_get_maxtries2(WRITE_ONLY_TRIES_OP); TRACED_ASSERT(max_tries > 0); for (tryctr=0, psc=-999, retryable=true; tryctr < max_tries && psc < 0 && retryable; tryctr++) { DBGMSF(debug, "Start of try loop, tryctr=%d, max_tries=%d, rc=%d, retryable=%d", tryctr, max_tries, psc, retryable ); Error_Info * cur_excp = ddc_write_only(dh, request_packet_ptr); psc = (cur_excp) ? cur_excp->status_code : 0; try_errors[tryctr] = cur_excp; if (psc == -EBUSY) retryable = false; } Error_Info * ddc_excp = NULL; if (psc < 0) { // now: // tryctr = number of tries // tryctr-1 = index of last try // tryctr == max_tries && retryable // tryctr < max_tries && !retryable // tryctr == max_tries && !retryable // int last_try_index = tryctr-1; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "After try loop. tryctr=%d, retryable=%s", tryctr, sbool(retryable)); if (retryable) { psc = DDCRC_RETRIES; ddc_excp = errinfo_new_with_causes(psc, try_errors, tryctr, __func__, NULL); if (psc != try_errors[tryctr-1]->status_code) COUNT_STATUS_CODE(psc); // new status code, count it } else { assert (tryctr == 1); ddc_excp = try_errors[0]; } } else { // 2 possibilities: // succeeded after retries, there will be some errors (tryctr > 1) // no errors (tryctr == 1) // int last_bad_try_index = tryctr-2; for (int ndx = 0; ndx < tryctr-1; ndx++) { BASE_ERRINFO_FREE_WITH_REPORT(try_errors[ndx], IS_DBGTRC(debug, TRACE_GROUP) ); } } try_data_record_tries2(dh, WRITE_ONLY_TRIES_OP, psc, tryctr); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } static void init_ddc_packet_io_func_name_table() { RTTI_ADD_FUNC(ddc_open_display); RTTI_ADD_FUNC(ddc_close_display); RTTI_ADD_FUNC(ddc_i2c_write_read_raw); RTTI_ADD_FUNC(ddc_i2c_write_only); // RTTI_ADD_FUNC(ddc_write_read_raw); RTTI_ADD_FUNC(ddc_write_read); RTTI_ADD_FUNC(ddc_write_read_with_retry); RTTI_ADD_FUNC(ddc_write_only); RTTI_ADD_FUNC(ddc_write_only_with_retry); RTTI_ADD_FUNC(ddc_validate_display_handle2); } void init_ddc_packet_io() { init_ddc_packet_io_func_name_table(); open_displays = g_hash_table_new(g_direct_hash, NULL); } void terminate_ddc_packet_io() { // ddc_close_all_displays(); g_hash_table_destroy(open_displays); } ddcutil-2.2.0/src/ddc/ddc_phantom_displays.c0000644000175000001440000002433514754576332014524 /** @file ddc_phantom_displays.c Phantom display detection*/ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include "util/sysfs_util.h" #include "base/core.h" #include "base/displays.h" #include "base/i2c_bus_base.h" #include "base/rtti.h" #include "sysfs/sysfs_base.h" #include "ddc_phantom_displays.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; bool detect_phantom_displays = true; STATIC bool edid_ids_match(Parsed_Edid * edid1, Parsed_Edid * edid2) { bool result = false; result = streq(edid1->mfg_id, edid2->mfg_id) && streq(edid1->model_name, edid2->model_name) && edid1->product_code == edid2->product_code && streq(edid1->serial_ascii, edid2->serial_ascii) && edid1->serial_binary == edid2->serial_binary; return result; } /** Check if an invalid #Display_Reference can be regarded as a phantom * of a given valid #Display_Reference. * * @param invalid_dref * @param valid_dref * @return true/false * * - Both are /dev/i2c devices * - The EDID id fields must match * - For the invalid #Display_Reference: * - attribute status must exist and equal "disconnected" * - attribute enabled must exist and equal "disabled" * - attribute edid must not exist */ STATIC bool is_phantom_display(Display_Ref* invalid_dref, Display_Ref * valid_dref) { bool debug = false; char * invalid_repr = g_strdup(dref_repr_t(invalid_dref)); char * valid_repr = g_strdup(dref_repr_t(valid_dref)); DBGTRC_STARTING(debug, TRACE_GROUP, "invalid_dref=%s, valid_dref=%s", invalid_repr, valid_repr); free(invalid_repr); free(valid_repr); bool result = false; // User report has shown that 128 byte EDIDs can differ for the valid and // invalid display. Specifically, byte 24 was seen to differ, with one // having RGB 4:4:4 and the other RGB 4:4:4 + YCrCb 4:2:2!. So instead of // simply byte comparing the 2 EDIDs, check the identifiers. if (edid_ids_match(invalid_dref->pedid, valid_dref->pedid)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "EDIDs match"); if (invalid_dref->io_path.io_mode == DDCA_IO_I2C && valid_dref->io_path.io_mode == DDCA_IO_I2C) { int invalid_busno = invalid_dref->io_path.path.i2c_busno; // int valid_busno = valid_dref->io_path.path.i2c_busno; char buf0[40]; snprintf(buf0, 40, "/sys/bus/i2c/devices/i2c-%d", invalid_busno); bool old_silent = set_rpt_sysfs_attr_silent(!(debug|| IS_TRACING())); char * invalid_rpath = NULL; bool ok = RPT_ATTR_REALPATH(0, &invalid_rpath, buf0, "device"); if (ok) { result = true; char * attr_value = NULL; possibly_write_detect_to_status_by_connector_path(invalid_rpath); ok = RPT_ATTR_TEXT(0, &attr_value, invalid_rpath, "status"); if (!ok || !streq(attr_value, "disconnected")) result = false; ok = RPT_ATTR_TEXT(0, &attr_value, invalid_rpath, "enabled"); if (!ok || !streq(attr_value, "disabled")) result = false; GByteArray * edid; ok = RPT_ATTR_EDID(0, &edid, invalid_rpath, "edid"); // is "edid" needed if (ok) { result = false; g_byte_array_free(edid, true); } } set_rpt_sysfs_attr_silent(old_silent); } } DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", sbool(result) ); return result; } /** Tests if 2 #Display_Ref instances have each have EDIDs and * they are identical. * @param dref1 * @param dref2 * @return true/false */ bool drefs_edid_equal(Display_Ref * dref1, Display_Ref * dref2) { bool debug = false; if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { char * s = g_strdup( dref_repr_t(dref2)); DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dref1=%s, dref2=%s", dref_repr_t(dref1), s); free(s); } assert(dref1); assert(dref2); Parsed_Edid * pedid1 = dref1->pedid; Parsed_Edid * pedid2 = dref2->pedid; bool edids_equal = false; if (pedid1 && pedid2) { if (memcmp(pedid1->bytes, pedid2->bytes, 128) == 0) { edids_equal = true; } } DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, edids_equal, ""); return edids_equal; } /** Checks if any 2 #Display_Ref instances in a GPtrArray of instances * have identical EDIDs. * @param drefs array of Display_Refs * @return true/false */ static bool has_duplicate_edids(GPtrArray * drefs) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "drefs->len = %d", drefs->len); bool found_duplicate = false; for (int i = 0; i < drefs->len; i++) { for (int j = i+1; j < drefs->len; j++) { if (drefs_edid_equal(g_ptr_array_index(drefs, i), g_ptr_array_index(drefs, j)) ) { found_duplicate = true; break; } } } DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, found_duplicate, ""); return found_duplicate; } /** Mark phantom displays. * * Split the #Display_Ref's in a GPtrArray into those that have * already been determined to be valid (dispno > 0) and those * that are invalid (dispno < 0). * * For each invalid display ref, check to see if it is a phantom display * corresponding to one of the valid displays. If so, set its dispno * to DISPNO_INVALID and save a pointer to the valid display ref. * * @param all_displays array of pointers to #Display_Ref * @return true if phantom displays detected, false if not * * @remark * This handles the case where DDC communication works for one /dev/i2c bus * but not another. It also handles the case where there are 2 valid display * refs and the connector for one has name DPMST. */ bool filter_phantom_displays(GPtrArray * all_displays) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "all_displays->len=%d, detect_phantom_displays=%s", all_displays->len, sbool(detect_phantom_displays)); bool phantom_displays_found = false; if (detect_phantom_displays && all_displays->len > 1) { GPtrArray* valid_displays = g_ptr_array_sized_new(all_displays->len); GPtrArray* invalid_displays = g_ptr_array_sized_new(all_displays->len); GPtrArray* valid_non_mst_displays = g_ptr_array_sized_new(all_displays->len); GPtrArray* valid_mst_displays = g_ptr_array_sized_new(all_displays->len); for (int ndx = 0; ndx < all_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); if (dref->io_path.io_mode == DDCA_IO_I2C) { TRACED_ASSERT( memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0 ); if (dref->dispno < 0) // DISPNO_INVALID, DISPNO_PHANTOM, DISPNO_REMOVED g_ptr_array_add(invalid_displays, dref); else g_ptr_array_add(valid_displays, dref); } } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%d valid displays, %d invalid displays", valid_displays->len, invalid_displays->len); if (invalid_displays->len > 0 && valid_displays->len > 0 ) { for (int invalid_ndx = 0; invalid_ndx < invalid_displays->len; invalid_ndx++) { Display_Ref * invalid_ref = g_ptr_array_index(invalid_displays, invalid_ndx); for (int valid_ndx = 0; valid_ndx < valid_displays->len; valid_ndx++) { Display_Ref * valid_ref = g_ptr_array_index(valid_displays, valid_ndx); if (is_phantom_display(invalid_ref, valid_ref)) { invalid_ref->dispno = DISPNO_PHANTOM; // -2 invalid_ref->actual_display = valid_ref; } } } } for (int ndx = 0; ndx < valid_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(valid_displays, ndx); I2C_Bus_Info * businfo = dref->detail; char * bus_name = get_i2c_device_sysfs_name(businfo->busno); if (streq(bus_name, "DPMST")) g_ptr_array_add(valid_mst_displays, dref); else g_ptr_array_add(valid_non_mst_displays, dref); free(bus_name); } if (valid_mst_displays->len > 0 && valid_non_mst_displays->len > 0) { // handle remote possibility of 2 monitors with identical edid: if (!has_duplicate_edids(valid_non_mst_displays)) { for (int mst_ndx = 0; mst_ndx < valid_mst_displays->len; mst_ndx++) { Display_Ref * valid_mst_display_ref = g_ptr_array_index(valid_mst_displays, mst_ndx); for (int non_mst_ndx = 0; non_mst_ndx < valid_non_mst_displays->len; non_mst_ndx++) { Display_Ref * valid_non_mst_display_ref = g_ptr_array_index(valid_non_mst_displays, non_mst_ndx); Parsed_Edid * pedid1 = valid_mst_display_ref->pedid; Parsed_Edid * pedid2 = valid_non_mst_display_ref->pedid; if (pedid1 && pedid2) { if (memcmp(pedid1->bytes, pedid2->bytes, 128) == 0) { valid_non_mst_display_ref->dispno = DISPNO_PHANTOM; valid_non_mst_display_ref->actual_display = valid_mst_display_ref; } } } } } } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%d valid mst_displays, %d valid_non_mst_displays", valid_mst_displays->len, valid_non_mst_displays->len); phantom_displays_found = invalid_displays->len > 0; // n. frees the underlying array, but not the Display_Refs pointed to by // array members, since no GDestroyNotify() function defined g_ptr_array_free(valid_mst_displays, true); g_ptr_array_free(valid_non_mst_displays, true); g_ptr_array_free(invalid_displays, true); g_ptr_array_free(valid_displays, true); } DBGTRC_RET_BOOL(debug, TRACE_GROUP, phantom_displays_found, ""); return phantom_displays_found; } void init_ddc_phantom_displays() { RTTI_ADD_FUNC(drefs_edid_equal); RTTI_ADD_FUNC(filter_phantom_displays); RTTI_ADD_FUNC(has_duplicate_edids); RTTI_ADD_FUNC(is_phantom_display); } ddcutil-2.2.0/src/ddc/ddc_read_capabilities.c0000644000175000001440000001477314634376340014571 /** @file ddc_read_capabilities.c */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include /** \cond */ #include #include #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/report_util.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/status_code_mgt.h" #include "base/tuned_sleep.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #endif #include "vcp/persistent_capabilities.h" #include "ddc/ddc_multi_part_io.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_read_capabilities.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; /** Executes the VCP Get Capabilities command to obtain the * capabilities string. The string is returned in null terminated * form in a Buffer struct. It is the responsibility of the caller to * free this struct. * * @param dh display handle * @param capabilities_buffer_loc address at which to return pointer to allocated Buffer * @return pointer to #Error_Info struct, NULL if no error */ static Error_Info * get_capabilities_into_buffer( Display_Handle * dh, Buffer** capabilities_buffer_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s", dh_repr(dh)); Error_Info * ddc_excp = NULL; TUNED_SLEEP_WITH_TRACE(dh, SE_PRE_MULTI_PART_READ, "Before reading capabilities"); ddc_excp = multi_part_read_with_retry( dh, DDC_PACKET_TYPE_CAPABILITIES_REQUEST, 0x00, // no subtype for capabilities Write_Read_Flag_Capabilities, // special all zero response handling capabilities_buffer_loc); Buffer * cap_buffer = *capabilities_buffer_loc; ASSERT_IFF(cap_buffer, !ddc_excp); if (!ddc_excp) { // trim trailing blanks and nulls int len = buffer_length(*capabilities_buffer_loc); while ( len > 0 ) { Byte ch = cap_buffer->bytes[len-1]; if (ch == ' ' || ch == '\0') len--; else break; } // since buffer contains a string, put a single null at end buffer_set_byte(cap_buffer, len, '\0'); buffer_set_length(cap_buffer, len+1); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, "*capabilities_buffer_loc=%p", *capabilities_buffer_loc); ASSERT_IFF(*capabilities_buffer_loc, !ddc_excp); return ddc_excp; } /** Gets the capabilities string for a display. * * For a display with an I2C device path: * - First, checks to see if it is already in the Display_Ref. * - If not, checks if the string is available in the capabilities cache. * - Finally, executes the VCP Get Capabilities command to obtain the * capabilities string. * * For display with a USB device path * - Returns a synthesized capabilities string. * * @param dh display handle * @param caps_loc location where to return pointer to capabilities string. * @return pointer to #Error_Info struct, NULL if no error * * The returned pointer is to a string that is part of the display reference * associated with the display handle. It should NOT be freed by the caller. */ Error_Info * ddc_get_capabilities_string( Display_Handle * dh, char** caps_loc) { bool debug = false; assert(dh); assert(dh->dref); DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, dh->dref->capabilities_string=|%s|", dh_repr(dh), dh->dref->capabilities_string); Error_Info * ddc_excp = NULL; if (!dh->dref->capabilities_string) { if (dh->dref->io_path.io_mode == DDCA_IO_USB) { #ifdef ENABLE_USB // newly created string, can just reference dh->dref->capabilities_string = usb_get_capabilities_string_by_dh(dh); #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif } else { // n. persistent_capabilities_enabled handled in get_persistent_capabilities() dh->dref->capabilities_string = g_strdup(get_persistent_capabilities(dh->dref->mmid)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "get_persistent_capabilities() returned |%s|", dh->dref->capabilities_string); if (dh->dref->capabilities_string && get_output_level() >= DDCA_OL_VERBOSE) { char * s = capabilities_cache_file_name(); rpt_vstring(0, "Read cached capabilities string from %s", s); SYSLOG2(DDCA_SYSLOG_INFO, "Read cached capabilities string from %s", s); free(s); } if (!dh->dref->capabilities_string) { Buffer * pcaps_buffer; ddc_excp = get_capabilities_into_buffer(dh, &pcaps_buffer); if (!ddc_excp) { dh->dref->capabilities_string = g_strdup((char *) pcaps_buffer->bytes); buffer_free(pcaps_buffer,__func__); set_persistent_capabilites(dh->dref->mmid, dh->dref->capabilities_string); } } } } *caps_loc = dh->dref->capabilities_string; ASSERT_IFF(*caps_loc, !ddc_excp); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, "*caps_loc -> |%s|", *caps_loc); return ddc_excp; } #ifdef UNUSED Error_Info * get_capabilities_string_by_dref(Display_Ref * dref, char **pcaps) { assert(dref); bool debug = false; DBGMSF(debug, "Starting. dref=%s", dref_repr_t(dref)); Public_Status_Code psc = 0; Error_Info * ddc_excp = NULL; if (!dref->capabilities_string) { Display_Handle * dh = NULL; psc = ddc_open_display(dref, CALLOPT_NONE, &dh); if (psc == 0) { ddc_excp = ddc_get_capabilities_string(dh, &dref->capabilities_string); int rc = ERRINFO_STATUS(ddc_excp); if (rc == -EBADF) { DBGMSF(debug, "EBADF, skipping ddc_close_display()"); } else ddc_close_display(dh); } else ddc_excp = errinfo_new(psc, __func__); } *pcaps = dref->capabilities_string; DBGMSF(debug, "Done. Returning: %p", ddc_excp); DBGMSF(debug, "Done. dref = %s, error_info = %s, capabilities: %s", dref_repr_t(dref), errinfo_summary(ddc_excp), *pcaps); return ddc_excp; } #endif void init_ddc_read_capabilities() { RTTI_ADD_FUNC(ddc_get_capabilities_string); RTTI_ADD_FUNC(get_capabilities_into_buffer); } ddcutil-2.2.0/src/ddc/ddc_save_current_settings.c0000644000175000001440000000357714754153540015563 /** @file ddc_save_current_settings.c * Implement DDC command Save Current Settings */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include "public/ddcutil_status_codes.h" #include "util/error_info.h" #include "base/core.h" #include "base/ddc_packets.h" #include "base/displays.h" #include "base/rtti.h" #include "ddc_packet_io.h" #include "ddc_save_current_settings.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; // // DDC command Save Current Settings // /** Executes the DDC Save Current Settings command. * * @param dh handle of open display device * @return NULL if success, pointer to #Error_Info if failure */ Error_Info * ddc_save_current_settings( Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Invoking DDC Save Current Settings command. dh=%s", dh_repr(dh)); Error_Info * ddc_excp = NULL; if (dh->dref->io_path.io_mode == DDCA_IO_USB) { // command line parser should block this case PROGRAM_LOGIC_ERROR("MCCS over USB does not have Save Current Settings command"); ddc_excp = ERRINFO_NEW(DDCRC_UNIMPLEMENTED, "MCCS over USB does not have Save Current Settings command" ); } else { DDC_Packet * request_packet_ptr = create_ddc_save_settings_request_packet("save_current_settings:request packet"); // DBGMSG("create_ddc_save_settings_request_packet returned packet_ptr=%p", request_packet_ptr); // dump_packet(request_packet_ptr); ddc_excp = ddc_write_only_with_retry(dh, request_packet_ptr); free_ddc_packet(request_packet_ptr); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } void init_ddc_save_current_settings() { RTTI_ADD_FUNC(ddc_save_current_settings); } ddcutil-2.2.0/src/ddc/ddc_serialize.c0000644000175000001440000005252714754153540013131 /** @file ddc_serialize.c */ // Copyright (C) 2023-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include "public/ddcutil_types.h" #include "util/file_util.h" #include "util/string_util.h" #include "util/xdg_util.h" #include "base/core.h" #include "base/displays.h" #include "base/i2c_bus_base.h" #include "base/monitor_model_key.h" #include "base/rtti.h" #include "ddc/ddc_displays.h" #include "ddc_serialize.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_NONE; bool display_caching_enabled = false; GPtrArray* deserialized_displays = NULL; // array of Display_Ref * GPtrArray* deserialized_buses = NULL; // array of Display_Ref * // #define CACHE_BUS_INFO // not used Display_Ref * ddc_find_deserialized_display(int busno, Byte* edidbytes) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDCIO, "busno = %d", busno); Display_Ref * result = NULL; if (deserialized_displays) { for (int ndx = 0; ndx < deserialized_displays->len; ndx++) { Display_Ref * cur = g_ptr_array_index(deserialized_displays, ndx); if (cur->io_path.io_mode == DDCA_IO_I2C && cur->io_path.path.i2c_busno == busno && cur->pedid && memcmp(cur->pedid->bytes, edidbytes, 128) == 0 ) { result = cur; break; } } } if (result) DBGTRC_RET_STRUCT(debug, DDCA_TRC_DDCIO, Display_Ref, dbgrpt_display_ref0, result); else DBGTRC_DONE(debug, DDCA_TRC_DDCIO, "Not found. Returning NULL"); return result; } void ddc_enable_displays_cache(bool onoff) { bool debug = false; display_caching_enabled = onoff; DBGMSF(debug, "Executed. onoff=%s", sbool(onoff)); } json_t* serialize_dpath(DDCA_IO_Path iopath) { json_t* jpath = json_object(); json_t* jpath_mode = json_integer(iopath.io_mode); json_t* jpath_busno = json_integer(iopath.path.i2c_busno); json_object_set_new(jpath, "io_mode", jpath_mode); json_object_set_new(jpath, "busno_or_hiddev", jpath_busno); return jpath; } json_t * serialize_vspec(DDCA_MCCS_Version_Spec vspec) { json_t* jpath = json_object(); json_t* jpath_mode = json_integer(vspec.major); json_t* jpath_busno = json_integer(vspec.minor); json_object_set_new(jpath, "major", jpath_mode); json_object_set_new(jpath, "minor", jpath_busno); return jpath; } json_t * serialize_parsed_edid(Parsed_Edid * pedid) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "pedid=%p", pedid); json_t* jpath = json_object(); char edid_bytes[257]; hexstring2( pedid->bytes, // bytes to convert 128, // number of bytes "", // separator string between hex digits true, // use upper case hex characters edid_bytes, // buffer in which to return hex string 257) ; // buffer size DBGMSF(debug, "edid_bytes=%s", edid_bytes); json_t* jpath_raw = json_string(edid_bytes); json_object_set_new(jpath, "bytes", jpath_raw); json_t* jnode = json_string(pedid->edid_source); json_object_set_new(jpath, "edid_source", jnode); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning %p", jpath); return jpath; } json_t * serialize_mmk(Monitor_Model_Key * mmk) { json_t* jpath = json_object(); json_t* jmfg = json_string(mmk->mfg_id); json_object_set_new(jpath, "mfg_id", jmfg); json_t* jmodel = json_string(mmk->model_name); json_object_set_new(jpath, "model_name", jmodel); json_t* jproduct = json_integer(mmk->product_code); json_object_set_new(jpath, "product_code", jproduct); return jpath; } json_t* serialize_one_display(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDCIO, "dref=%s", dref_repr_t(dref)); if (debug) dbgrpt_display_ref(dref, true, 2); json_t * jtmp = NULL; json_t * jdisp = json_object(); json_object_set_new(jdisp, "io_path", serialize_dpath(dref->io_path)); json_object_set_new(jdisp, "usb_bus", json_integer(dref->usb_bus)); json_object_set_new(jdisp, "usb_device", json_integer(dref->usb_device)); json_t* jnode; if (dref->usb_hiddev_name) { jnode = json_string(dref->usb_hiddev_name); json_object_set_new(jdisp, "usb_hiddev_name", jnode); } json_object_set_new(jdisp, "vcp_version_xdf", serialize_vspec(dref->vcp_version_xdf)); json_object_set_new(jdisp, "vcp_version_cmdline", serialize_vspec(dref->vcp_version_cmdline)); json_object_set_new(jdisp, "flags", json_integer(dref->flags)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "capabilities_string: %s", dref->capabilities_string); if (dref->capabilities_string) { jnode = json_string(dref->capabilities_string); json_object_set_new(jdisp, "capabilities_string", jnode); } jtmp = serialize_parsed_edid(dref->pedid); json_object_set_new(jdisp, "pedid", jtmp); json_object_set_new(jdisp, "dispno", json_integer(dref->dispno)); json_object_set_new(jdisp, "mmid", serialize_mmk(dref->mmid)); if (dref->dispno == -2) { jtmp = serialize_dpath(dref->actual_display->io_path); json_object_set_new(jdisp, "actual_display_path", jtmp); } #ifdef OLD if (dref->driver_name) { json_object_set_new(jdisp, "driver_name", json_string(dref->driver_name)); } #endif // json_decref(jdisp); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning %p", jdisp); return jdisp; } DDCA_IO_Path deserialize_dpath(json_t* jpath) { bool debug = false; json_t* jtmp = json_object_get(jpath, "io_mode"); DDCA_IO_Mode mode = json_integer_value(jtmp); jtmp = json_object_get(jpath, "busno_or_hiddev"); int busno = json_integer_value(jtmp); DDCA_IO_Path dpath; dpath.io_mode = mode; dpath.path.i2c_busno = busno; DBGMSF(debug, "Returning: %s", dpath_repr_t(&dpath)); return dpath; } DDCA_MCCS_Version_Spec deserialize_vspec(json_t* jpath) { DDCA_MCCS_Version_Spec vspec = {0,0}; json_t* jtmp = json_object_get(jpath, "major"); vspec.major = json_integer_value(jtmp); jtmp = json_object_get(jpath, "minor"); vspec.minor = json_integer_value(jtmp); // DBGMSG("vspec=%d.%d", vspec.major, vspec.minor); return vspec; } Parsed_Edid * deserialize_parsed_edid(json_t* jpath) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); Parsed_Edid * parsed_edid = NULL; json_t* jtmp = json_object_get(jpath, "bytes"); if (!jtmp) { DBGMSF(debug, "bytes not found"); } else { const char * sbytes = json_string_value(jtmp); if (!sbytes) { DBGMSF(debug, "Unable to read sbytes"); } else { assert(strlen(sbytes) == 256); Byte * hbytes; int ct = hhs_to_byte_array(sbytes, &hbytes); assert (ct == 128); json_t* jtmp1 = json_object_get(jpath, "edid_source"); const char * edid_source = json_string_value(jtmp1); // json_decref(jtmp1); if (ct == 128) { parsed_edid = create_parsed_edid2(hbytes, edid_source); } free(hbytes); } // json_decref(jtmp); } if (parsed_edid && debug) report_parsed_edid(parsed_edid, true, 1); DBGTRC_DONE(debug, TRACE_GROUP, "Returning parsed_edid=%p", parsed_edid); return parsed_edid; } Monitor_Model_Key * deserialize_mmid(json_t* jpath) { bool debug = false; const char * mfg_id = json_string_value( json_object_get(jpath, "mfg_id")); const char * model_name = json_string_value( json_object_get(jpath, "model_name")); int product_code = json_integer_value( json_object_get(jpath, "product_code")); Monitor_Model_Key* mmk = mmk_new(mfg_id, model_name, product_code); DBGMSF(debug, "Executed. Returning: %s", mmk_repr(*mmk) ); return mmk; } Display_Ref * deserialize_one_display(json_t* disp_node) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, ""); json_t* jtmp = NULL; jtmp = json_object_get(disp_node, "io_path"); DDCA_IO_Path io_path = deserialize_dpath(jtmp); Display_Ref * dref = create_base_display_ref(io_path); jtmp = json_object_get(disp_node, "usb_bus"); dref->usb_bus = json_integer_value(jtmp); jtmp = json_object_get(disp_node, "usb_device"); dref->usb_device = json_integer_value(jtmp); jtmp = json_object_get(disp_node, "usb_hiddev_name"); dref->usb_hiddev_name = NULL; if (jtmp) { dref->usb_hiddev_name = g_strdup(json_string_value(jtmp)); } jtmp = json_object_get(disp_node, "vcp_version_xdf"); dref->vcp_version_xdf = deserialize_vspec(jtmp); jtmp = json_object_get(disp_node, "vcp_version_cmdline"); dref->vcp_version_cmdline = deserialize_vspec(jtmp); jtmp = json_object_get(disp_node, "flags"); dref->flags = json_integer_value(jtmp); jtmp = json_object_get(disp_node, "capabilities_string"); dref->capabilities_string = NULL; if (jtmp) { dref->capabilities_string = g_strdup(json_string_value(jtmp)); } jtmp = json_object_get(disp_node, "pedid"); dref->pedid = deserialize_parsed_edid(jtmp); jtmp = json_object_get(disp_node, "mmid"); dref->mmid = deserialize_mmid(jtmp); jtmp = json_object_get(disp_node, "dispno"); dref->dispno = json_integer_value(jtmp); jtmp = json_object_get(disp_node, "actual_display_path"); if (jtmp) { DDCA_IO_Path actual_display_path = deserialize_dpath(jtmp); dref->actual_display_path = calloc(1, sizeof(DDCA_IO_Path)); memcpy(dref->actual_display_path, &actual_display_path, sizeof(DDCA_IO_Path)); } #ifdef OLD jtmp = json_object_get(disp_node, "driver_name"); if (jtmp) { dref->driver_name = g_strdup(json_string_value(jtmp)); } #endif DBGTRC_RET_STRUCT(debug, DDCA_TRC_NONE, Display_Ref, dbgrpt_display_ref0, dref); return dref; } #ifdef CACHE_BUS_INFO json_t* serialize_one_i2c_bus(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "busno=%d, Before serialization:", businfo->busno); if (IS_TRACING() || debug) i2c_dbgrpt_bus_info(businfo, 2); json_t * jtmp = NULL; json_t * jbus = json_object(); json_object_set_new(jbus, "busno", json_integer(businfo->busno)); json_object_set_new(jbus, "functionality", json_integer(businfo->busno)); if (businfo->edid) { jtmp = serialize_parsed_edid(businfo->edid); json_object_set_new(jbus, "edid", jtmp); } json_object_set_new(jbus, "flags", json_integer(businfo->flags)); if (businfo->driver) json_object_set_new(jbus, "driver", json_string(businfo->driver)); if (businfo->drm_connector_name) json_object_set_new(jbus, "drm_connector_name", json_string(businfo->drm_connector_name)); json_object_set_new(jbus, "drm_connector_found_by", json_integer(businfo->drm_connector_found_by)); // if (jtmp) // json_decref(jtmp); // json_decref(jbus); DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning %p", jbus); return jbus; } I2C_Bus_Info * deserialize_one_i2c_bus(json_t* jbus) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "jbus=%p", jbus); json_t* jtmp = NULL; json_t* busno_node = json_object_get(jbus, "busno"); if (!(busno_node && json_is_integer(busno_node))) { if (busno_node) SEVEREMSG("error: busno is not an integer\n"); else SEVEREMSG("member busno not found"); // json_decref(jbus); return NULL; } int busno = json_integer_value(busno_node); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d", busno); I2C_Bus_Info * businfo = i2c_new_bus_info(busno); businfo->functionality = json_integer_value(json_object_get(jbus, "functionality")); jtmp = json_object_get(jbus, "edid"); if (jtmp) businfo->edid = deserialize_parsed_edid(jtmp); businfo->flags = json_integer_value(json_object_get(jbus, "flags")); jtmp = json_object_get(jbus, "driver"); if (jtmp) businfo->driver = g_strdup(json_string_value(jtmp)); jtmp = json_object_get(jbus, "drm_connector_name"); if (jtmp) businfo->drm_connector_name = g_strdup(json_string_value(jtmp)); businfo->drm_connector_found_by = json_integer_value(json_object_get(jbus, "drm_connector_found_by")); DBGTRC_RET_STRUCT(debug, DDCA_TRC_NONE, I2C_Bus_Info, i2c_dbgrpt_bus_info, businfo); return businfo; } #endif typedef enum { serialize_mode_display, serialize_mode_bus } Serialize_Mode; const char * serialize_mode_name(Serialize_Mode mode) { char * result = (mode == serialize_mode_display) ? "serialize_mode_display" : "serialize_mode_bus"; return result; } char * ddc_serialize_displays_and_buses() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, ""); json_t* root = json_object(); json_object_set_new(root, "version", json_integer(1)); GPtrArray* all_displays = ddc_get_all_display_refs(); json_t* jdisplays = json_array(); for (int ndx = 0; ndx < all_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(all_displays, ndx); if (dref->flags & DREF_DDC_COMMUNICATION_WORKING) { json_t* node = serialize_one_display(dref); json_array_append(jdisplays, node); json_decref(node); } } json_object_set_new(root, "all_displays", jdisplays); #ifdef CACHE_BUS_INFO GPtrArray* all_buses = i2c_get_all_buses(); json_t* jbuses = json_array(); for (int ndx = 0; ndx < all_buses->len; ndx++) { json_t* node = serialize_one_i2c_bus(g_ptr_array_index(all_buses, ndx)); json_array_append(jbuses, node); json_decref(node); } json_object_set_new(root, "all_buses", jbuses); #endif char * result = json_dumps(root, JSON_INDENT(3)); DBGTRC_RET_STRING(debug, TRACE_GROUP, result, ""); json_decref(root); return result; } GPtrArray * ddc_deserialize_displays_or_buses(const char * jstring, Serialize_Mode mode) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDCIO, "mode=%s, jstring:", serialize_mode_name(mode)); DBGTRC_NOPREFIX(debug, DDCA_TRC_DDCIO, "%s", jstring); GPtrArray * restored = g_ptr_array_new(); #ifndef CACHE_BUS_INFO assert(mode == serialize_mode_display); #endif json_error_t error; bool ok = true; json_t* root = json_loads(jstring, 0, &error); if (!root) { SEVEREMSG( "error: on line %d: %s\n", error.line, error.text); ok = false; goto bye; } if(!json_is_object(root)) { SEVEREMSG( "error: root is not an object\n"); // json_decref(root); ok = false; goto bye; } json_t* version_node = json_object_get(root, "version"); if (!(version_node && json_is_integer(version_node))) { if (version_node) SEVEREMSG("error: version is not an integer\n"); else SEVEREMSG("member version not found"); // json_decref(root); ok = false; goto bye; } int version = json_integer_value(version_node); DBGMSF(debug, "version = %d", version); assert(version == 1); char * all = "all_displays"; #ifdef CACHE_BUS_INFO if (mode == serialize_mode_bus) all = "all_buses"; #endif json_t* disp_nodes = json_object_get(root, all); if (!(disp_nodes && json_is_array(disp_nodes))) { if (disp_nodes) SEVEREMSG("error: %s is not an array", all); else SEVEREMSG("member %s not found", all); // json_decref(root); ok = false; goto bye; } for (int dispctr = 0; dispctr < json_array_size(disp_nodes); dispctr++) { json_t* one_display_or_bus = json_array_get(disp_nodes, dispctr); if (! (one_display_or_bus && json_is_object(one_display_or_bus))) { if (one_display_or_bus) SEVEREMSG("%s[%d] not found", all, dispctr); else SEVEREMSG("%s[%d] is not an object", all, dispctr); // json_decref(root); ok = false; goto bye; } #ifdef CACHE_BUS_INFO if (mode == serialize_mode_display) { Display_Ref * dref = deserialize_one_display(one_display_or_bus); g_ptr_array_add(restored, dref); } else { I2C_Bus_Info * businfo = deserialize_one_i2c_bus(one_display_or_bus); g_ptr_array_add(restored, businfo); } #else Display_Ref * dref = deserialize_one_display(one_display_or_bus); g_ptr_array_add(restored, dref); #endif } bye: if (root) json_decref(root); if (!ok) { g_ptr_array_remove_range (restored, 0, restored->len); } DBGTRC_DONE(debug, DDCA_TRC_DDCIO, "Restored %d records.", restored->len); return restored; } #ifdef OUT GPtrArray * ddc_deserialize_displays(const char * jstring) { DBGMSG("jstring: |%s|", jstring); return ddc_deserialize_displays_or_buses(jstring, serialize_mode_display); } GPtrArray * ddc_deserialize_buses(const char * jstring) { DBGMSG("jstring: |%s|", jstring); return ddc_deserialize_displays_or_buses(jstring, serialize_mode_bus); } #endif /** Returns the name of the file that stores persistent display information * * \return name of file, normally $HOME/.cache/ddcutil/displays */ /* caller is responsible for freeing returned value */ char * ddc_displays_cache_file_name() { return xdg_cache_home_file("ddcutil", DISPLAYS_CACHE_FILENAME); } bool ddc_store_displays_cache() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDCIO, "Starting"); bool ok = false; if (ddc_displays_already_detected()) { char * json_text = ddc_serialize_displays_and_buses(); char * fn = ddc_displays_cache_file_name(); if (!fn) { SEVEREMSG("Unable to determine cisplay cache file name"); SYSLOG2(DDCA_SYSLOG_ERROR, "Unable to determine display cache file name"); } else { FILE * fp = NULL; fopen_mkdir(fn, "w", ferr(), &fp ); if (!fp) { SEVEREMSG("Error opening file %s:%s", fn, strerror(errno)); SYSLOG2(DDCA_SYSLOG_ERROR, "Error opening file %s:%s", fn, strerror(errno)); } else { size_t bytes_written = fwrite(json_text, strlen(json_text), 1, fp); if (bytes_written < strlen(json_text)) { SEVEREMSG("Error writing file %s:%s", fn, strerror(errno)); SYSLOG2(DDCA_SYSLOG_ERROR, "Error writing file %s:%s", fn, strerror(errno)); } else { ok = true; } fclose(fp); } free(json_text); free(fn); } } DBGTRC_RET_BOOL(debug, DDCA_TRC_DDCIO, ok, ""); return ok; } void ddc_restore_displays_cache() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDCIO, ""); char * fn = ddc_displays_cache_file_name(); if (fn && regular_file_exists(fn)) { DBGMSF(debug, "Found file: %s", fn); char * buf = read_file_single_string(fn, debug); // DBGMSF(debug, "buf: |%s|", buf); deserialized_displays = ddc_deserialize_displays_or_buses(buf, serialize_mode_display); #ifdef CACHE_BUS_INFO deserialized_buses = ddc_deserialize_displays_or_buses(buf, serialize_mode_bus); #endif free(buf); } else { DBGMSF(debug, "File not found: %s", fn); #ifdef CACHE_BUS_INFO deserialized_buses = g_ptr_array_new(); #endif deserialized_displays = g_ptr_array_new(); } free(fn); #ifdef CACHE_BUS_INFO DBGTRC_DONE(debug, DDCA_TRC_DDCIO, "Restored %d Display_Ref records, %d I2C_Bus_Info records", deserialized_displays->len, deserialized_buses->len); #else DBGTRC_DONE(debug, DDCA_TRC_DDCIO, "Restored %d Display_Ref records", deserialized_displays->len); if ( IS_DBGTRC(debug, DDCA_TRC_DDCIO)) { for (int ndx = 0; ndx < deserialized_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(deserialized_displays, ndx); DBGMSG(" Display_Ref: %s", dref_repr_t(dref)); } } #endif } void ddc_erase_displays_cache() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDCIO, ""); bool found = false; char * fn = ddc_displays_cache_file_name(); if (!fn) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Failed to obtain cache file name"); } else { found = regular_file_exists(fn); if (found) { int rc = remove(fn); if (rc < 0) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Error removing file %s: %s", fn, strerror(errno)); } } } DBGTRC_DONE(debug, DDCA_TRC_DDCIO, "%s: %s", (found) ? "Removed file" : "File not found", fn); free(fn); } void init_ddc_serialize() { RTTI_ADD_FUNC(ddc_deserialize_displays_or_buses); RTTI_ADD_FUNC(ddc_serialize_displays_and_buses); RTTI_ADD_FUNC(ddc_erase_displays_cache); RTTI_ADD_FUNC(ddc_restore_displays_cache); RTTI_ADD_FUNC(ddc_store_displays_cache); RTTI_ADD_FUNC(deserialize_one_display); RTTI_ADD_FUNC(deserialize_parsed_edid); RTTI_ADD_FUNC(serialize_one_display); RTTI_ADD_FUNC(ddc_find_deserialized_display); } void terminate_ddc_serialize() { bool debug = false; DBGMSF(debug, "Starting"); if (deserialized_buses) { g_ptr_array_set_free_func(deserialized_buses, (GDestroyNotify) i2c_free_bus_info); g_ptr_array_free(deserialized_buses, true); deserialized_buses = NULL; } if (deserialized_displays) { g_ptr_array_set_free_func(deserialized_displays, (GDestroyNotify) free_display_ref); g_ptr_array_free(deserialized_displays, true); deserialized_displays = NULL; } DBGMSF(debug, "Done"); } ddcutil-2.2.0/src/ddc/ddc_services.c0000644000175000001440000001552214754153540012757 /** @file ddc_services.c * * ddc layer initialization and configuration, statistics management */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include "util/report_util.h" /** \endcond */ #include "base/base_services.h" #include "base/display_lock.h" #include "base/display_retry_data.h" #include "base/dsa2.h" #include "base/feature_metadata.h" #include "base/parms.h" #include "base/per_thread_data.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/tuned_sleep.h" #include "vcp/parse_capabilities.h" #include "vcp/persistent_capabilities.h" #include "vcp/vcp_feature_codes.h" #include "dynvcp/vcp_feature_set.h" #include "dynvcp/dyn_feature_codes.h" #include "dynvcp/dyn_feature_set.h" #include "dynvcp/dyn_feature_files.h" #include "dynvcp/dyn_parsed_capabilities.h" #include "sysfs/sysfs_services.h" #include "i2c/i2c_services.h" #ifdef ENABLE_USB #include "usb/usb_services.h" #endif #include "ddc/ddc_common_init.h" #include "ddc/ddc_display_selection.h" #include "ddc/ddc_display_ref_reports.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_dumpload.h" #include "ddc/ddc_initial_checks.h" #include "ddc/ddc_multi_part_io.h" #include "ddc/ddc_output.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_phantom_displays.h" #include "ddc/ddc_read_capabilities.h" #include "ddc/ddc_serialize.h" #include "ddc/ddc_save_current_settings.h" #include "ddc/ddc_try_data.h" #include "ddc/ddc_vcp.h" #include "ddc/ddc_vcp_version.h" #include "dw/dw_status_events.h" #ifdef BUILD_SHARED_LIB #include "dw/dw_dref.h" #include "dw/dw_xevent.h" #include "dw/dw_udev.h" #include "dw/dw_poll.h" #include "dw/dw_main.h" #include "dw/dw_common.h" #endif #include "ddc/ddc_services.h" // // Statistics // // /** Resets all DDC level statistics */ // void ddc_reset_ddc_stats() { // try_data_reset2_all(); // } /** Resets all statistics */ void ddc_reset_stats_main() { // ddc_reset_ddc_stats(); try_data_reset2_all(); reset_execution_stats(); ptd_profile_reset_all_stats(); } /** Master function for reporting statistics. * * \param stats bitflags indicating which statistics to report * \param show_per_display include per display execution stats * \param include_dsa_internal include internal dsa info in per display elapsed stats * \param depth logical indentation depth */ void ddc_report_stats_main(DDCA_Stats_Type stats, bool show_per_display_stats, bool include_dsa_internal, bool stats_to_syslog_only, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_DDC, "stats: 0x%02x, show_per_thread_stats: %s, include_dsa_internal: %s", stats, sbool(show_per_display_stats), sbool(include_dsa_internal)); bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); if (stats_to_syslog_only) { start_capture(DDCA_CAPTURE_STDERR); } rpt_nl(); rpt_label(depth, "EXECUTION STATISTICS"); rpt_nl(); if (stats & DDCA_STATS_TRIES) { ddc_report_ddc_stats(depth); rpt_nl(); } if (stats & DDCA_STATS_ERRORS) { report_all_status_counts(depth); // error code counts rpt_nl(); } if (stats & DDCA_STATS_CALLS) { report_execution_stats(depth); rpt_nl(); #ifdef OLD if (dsa_is_enabled()) { // for now just report current thread dsa_report_stats(depth); rpt_nl(); } #endif report_io_call_stats(depth); rpt_nl(); report_sleep_stats(depth); rpt_nl(); report_elapsed_stats(depth); rpt_nl(); } if (stats & (DDCA_STATS_ELAPSED)) { report_elapsed_summary(depth); rpt_nl(); } if (show_per_display_stats) { rpt_label(depth, "PER-DISPLAY EXECUTION STATISTICS"); rpt_nl(); if (stats & DDCA_STATS_TRIES) { drd_report_all_display_retry_data(depth); } if (stats & DDCA_STATS_ERRORS) { pdd_report_all_per_display_error_counts(depth); } if (stats & DDCA_STATS_CALLS) { pdd_report_all_per_display_call_stats(depth); } if (stats & (DDCA_STATS_ELAPSED)) { // need a report_all_thread_elapsed_summary() pdd_report_all_per_display_elapsed_stats(include_dsa_internal, depth); } // Reports locks held by per_thread_data() to confirm that locking has // trivial affect on performance. //dbgrpt_per_thread_data_locks(depth+1); } if (ptd_api_profiling_enabled) { ptd_profile_report_all_threads(0); ptd_profile_report_stats_summary(0); } if (stats_to_syslog_only) { Null_Terminated_String_Array lines = end_capture_as_ntsa(); int len = ntsa_length(lines); for (int ndx=0; ndx // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include /** \endcond */ #include "ddc/ddc_strategy.h" // keep in sync w DDC_IO_Mode DDC_Strategy ddc_strategies[] = { {DDCA_IO_I2C, NULL, NULL }, {DDCA_IO_USB, NULL, NULL } }; void validate_ddc_strategies() { assert( ddc_strategies[DDCA_IO_I2C].io_mode == DDCA_IO_I2C); assert( ddc_strategies[DDCA_IO_USB].io_mode == DDCA_IO_USB); } DDC_Raw_Writer ddc_raw_writer(Display_Handle * dh) { assert(dh && dh->dref); return ddc_strategies[dh->dref->io_path.io_mode].writer; } DDC_Raw_Reader ddc_raw_reader(Display_Handle * dh) { assert(dh && dh->dref); return ddc_strategies[dh->dref->io_path.io_mode].reader; } void init_ddc_strategies() { validate_ddc_strategies(); } ddcutil-2.2.0/src/ddc/ddc_vcp.c0000644000175000001440000007116114754153540011725 /** @file ddc_vcp.c * Virtual Control Panel access * Basic functions to get and set single values and save current settings. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include "util/error_info.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/utilrpt.h" /** \endcond */ #include "base/ddc_errno.h" #include "base/ddc_packets.h" #include "base/displays.h" #include "base/parms.h" #include "base/rtti.h" #include "base/status_code_mgt.h" #include "i2c/i2c_bus_core.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #include "usb/usb_vcp.h" #endif #include "vcp/vcp_feature_codes.h" #include #include "ddc/ddc_multi_part_io.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_DDC; // // Globals // int max_setvcp_verify_tries = 1; bool setvcp_verify_default = DEFAULT_SETVCP_VERIFY; bool enable_mock_data = false; // // Maintain thread-specific vcp settings // typedef struct { bool verify_setvcp; } Thread_Vcp_Settings; static Thread_Vcp_Settings * get_thread_vcp_settings() { static GPrivate per_thread_key = G_PRIVATE_INIT(g_free); Thread_Vcp_Settings *settings = g_private_get(&per_thread_key); // GThread * this_thread = g_thread_self(); // printf("(%s) this_thread=%p, settings=%p\n", __func__, this_thread, settings); if (!settings) { settings = g_new0(Thread_Vcp_Settings, 1); settings->verify_setvcp = setvcp_verify_default; g_private_set(&per_thread_key, settings); } // printf("(%s) Returning: %p\n", __func__, settings); return settings; } // // Mock getvcp values // static Parsed_Nontable_Vcp_Response * create_all_zero_response(Byte feature_code) { Parsed_Nontable_Vcp_Response * resp = calloc(1, sizeof(Parsed_Nontable_Vcp_Response)); resp->vcp_code = feature_code; resp->valid_response = true; resp->supported_opcode = true; resp->mh = 0; resp->ml = 0; resp->sh = 0; resp->sl = 0; return resp; } /** Possibly returns a mock value for a non-table feature * * @param feature_code VCP Feature Code * @param resp_loc where to return pointer to pseudo-response, * NULL if no pseudo-response * @return pseudo error information, if simulating a failure * * @remark * If return NULL and *resp_loc == NULL, then no pseudo response was generated */ Error_Info * mock_get_nontable_vcp_value( DDCA_Vcp_Feature_Code feature_code, Parsed_Nontable_Vcp_Response** resp_loc) { bool debug = false; DBGMSF(debug, "Starting. feature_code = 0x%02x, resp_loc = %p", feature_code, resp_loc); Error_Info * pseudo_errinfo = NULL; *resp_loc = NULL; if (enable_mock_data) { #ifdef TEST_X72 if (feature_code == 0x72) { Parsed_Nontable_Vcp_Response * resp = calloc(1, sizeof(Parsed_Nontable_Vcp_Response)); resp->vcp_code = feature_code; resp->valid_response = true; resp->supported_opcode = true; resp->mh = 0; resp->ml = 0; resp->sh = 0x78; resp->sl = 0x00; resp->max_value = resp->mh << 8 | resp->ml; resp->cur_value = resp->sh << 8 | resp->sl; *resp_loc = resp; } #endif #ifdef TEST_EIO if (feature_code == 0x45) { pseudo_errinfo = ERRINFO_NEW(-EIO, "Pseudo EIO error"); } #endif if (feature_code == 0x00) { // pseudo_errinfo = ERRINFO_NEW(DDCRC_NULL_RESPONSE, "Pseudo Null Response for feature 0x00"); Parsed_Nontable_Vcp_Response * resp = create_all_zero_response(feature_code); *resp_loc = resp; } if (feature_code == 0x10) { pseudo_errinfo = ERRINFO_NEW(DDCRC_INTERNAL_ERROR, "Pseudo Null Response for feature 0x10"); } if (feature_code == 0x41) { // *resp_loc = create_all_zero_response(feature_code); pseudo_errinfo = ERRINFO_NEW(DDCRC_INTERNAL_ERROR, "Pseudo Null Response for feature 0x41"); } if (debug) { DBGMSG("Feature 0x%02x, *resp_loc = %p, returning: %s", feature_code, *resp_loc, errinfo_summary(pseudo_errinfo) ); if (*resp_loc) dbgrpt_interpreted_nontable_vcp_response(*resp_loc, 2); } } return pseudo_errinfo; } // // Get VCP values // /** Gets the value for a non-table feature. * * @param dh handle for open display * @param feature_code VCP feature code * @param parsed_response_loc where to return parsed response * @return NULL if success, pointer to #Error_Info if failure * * It is the responsibility of the caller to free the parsed response. * * The value pointed to by parsed_response_loc is non-null iff the returned value is null. */ Error_Info * ddc_get_nontable_vcp_value( Display_Handle * dh, DDCA_Vcp_Feature_Code feature_code, Parsed_Nontable_Vcp_Response** parsed_response_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, Reading feature 0x%02x", dh_repr(dh), feature_code); // DBGTRC_NOPREFIX(debug, TRACE_GROUP, // "communication flags: %s", interpret_dref_flags_t(dh->dref->flags)); Error_Info * excp = NULL; Parsed_Nontable_Vcp_Response * parsed_response = NULL; I2C_Bus_Info * businfo = dh->dref->detail; *parsed_response_loc = NULL; if (enable_mock_data) { Error_Info * mock_errinfo = mock_get_nontable_vcp_value(feature_code, parsed_response_loc); if (mock_errinfo || *parsed_response_loc) { DBGMSF(debug, "Returning mock response for feature 0x%02x", feature_code); return mock_errinfo; } } DDC_Packet * response_packet_ptr = NULL; DDC_Packet * request_packet_ptr = create_ddc_getvcp_request_packet( feature_code, "ddc_get_nontable_vcp_value:request packet"); // dump_packet(request_packet_ptr); Byte expected_response_type = DDC_PACKET_TYPE_QUERY_VCP_RESPONSE; Byte expected_subtype = feature_code; int max_read_bytes = MAX_DDC_PACKET_SIZE; // DBGTRC_NOPREFIX(debug, TRACE_GROUP, // "before ddc_write_read_with_retry(): communication flags: %s", // interpret_dref_flags_t(dh->dref->flags)); excp = ddc_write_read_with_retry( dh, request_packet_ptr, max_read_bytes, expected_response_type, expected_subtype, Write_Read_Flags_None, &response_packet_ptr ); ASSERT_IFF(excp, !response_packet_ptr); if ( IS_DBGTRC(debug, TRACE_GROUP)) { if (excp) DBGTRC_NOPREFIX(debug, TRACE_GROUP, "ddc_write_read_with_retry() returned %s, response_packet_ptr=%p", psc_desc(ERRINFO_STATUS(excp)), response_packet_ptr); } if (excp) { if (!(businfo->flags & I2C_BUS_HAS_EDID)) { dh->dref->flags &= ~(DREF_DDC_IS_MONITOR|DREF_DDC_COMMUNICATION_CHECKED); } if (!(businfo->flags & I2C_BUS_ADDR_X37)) { dh->dref->flags &= ~(DREF_DDC_COMMUNICATION_WORKING); } } if (!excp) { assert(response_packet_ptr); // dump_packet(response_packet_ptr); Public_Status_Code psc = get_interpreted_vcp_code(response_packet_ptr, true /* make_copy */, &parsed_response); // ??? if (psc == 0) { #ifdef NO_LONGER_NEEDED if (parsed_response->vcp_code != feature_code) { DBGMSG("!!! WTF! requested feature_code = 0x%02x, but code in response is 0x%02x", feature_code, parsed_response->vcp_code); call_tuned_sleep_i2c(SE_POST_READ); goto retry; } #endif if (!parsed_response->valid_response) { excp = ERRINFO_NEW(DDCRC_DDC_DATA, "Invalid getvcp response"); // was DDCRC_INVALID_DATA } else if (!parsed_response->supported_opcode) { excp = ERRINFO_NEW(DDCRC_REPORTED_UNSUPPORTED, "Unsupported feature"); if (!value_bytes_zero(parsed_response)) { // for exploring DBGMSG("supported_opcode == false, but not all value bytes 0"); } } else if (value_bytes_zero(parsed_response) && (dh->dref->flags & DREF_DDC_USES_MH_ML_SH_SL_ZERO_FOR_UNSUPPORTED) ) { // just a message for now DBGMSG("all value bytes 0, supported_opcode == true," " setting DDCRC_DETERMINED_UNSUPPORTED)"); excp = ERRINFO_NEW(DDCRC_DETERMINED_UNSUPPORTED, "MH=ML=SH=SL=0"); } if (excp) { free(parsed_response); parsed_response = NULL; } } else { excp = ERRINFO_NEW(psc, NULL); } } free_ddc_packet(request_packet_ptr); if (response_packet_ptr) free_ddc_packet(response_packet_ptr); ASSERT_IFF(excp, !parsed_response); // needed to avoid clang warning if (!excp) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Success reading feature x%02x. *ppinterpreted_code=%p", feature_code, parsed_response); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x, max value=%d, cur value=%d", parsed_response->mh, parsed_response->ml, parsed_response->sh, parsed_response->sl, (parsed_response->mh<<8) | parsed_response->ml, (parsed_response->sh<<8) | parsed_response->sl); } *parsed_response_loc = parsed_response; DBGTRC_RET_ERRINFO2(debug, TRACE_GROUP, excp, *parsed_response_loc, ""); ASSERT_IFF(!excp, *parsed_response_loc); return excp; } /** Gets the value of a table feature in a newly allocated Buffer struct. * It is the responsibility of the caller to free the Buffer. * * @param dh display handle * @param feature_code VCP feature code * @param table_bytes_loc location at which to save address of newly allocated Buffer * @return NULL if success, pointer to #Error_Info if failure */ Error_Info * ddc_get_table_vcp_value( Display_Handle * dh, Byte feature_code, Buffer** table_bytes_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Reading feature 0x%02x", feature_code); Error_Info * ddc_excp = NULL; DDCA_Output_Level output_level = get_output_level(); Buffer * paccumulator = NULL; ddc_excp = multi_part_read_with_retry( dh, DDC_PACKET_TYPE_TABLE_READ_REQUEST, feature_code, Write_Read_Flag_All_Zero_Response_Ok | Write_Read_Flag_Table_Read, &paccumulator); if (debug || ddc_excp) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "multi_part_read_with_retry() returned %s", psc_desc(ddc_excp->status_code)); } if (!ddc_excp) { *table_bytes_loc = paccumulator; if (output_level >= DDCA_OL_VERBOSE) { DBGMSG("Bytes returned on table read:"); dbgrpt_buffer(paccumulator, 1); } } // lowest level at which this check can be done, multi_part_read_with_retry() doesn't // know it's being called for table value else if (ddc_excp->status_code == DDCRC_NULL_RESPONSE || ddc_excp->status_code == DDCRC_ALL_RESPONSES_NULL) { Error_Info * wrapped_exception = ddc_excp; ddc_excp = errinfo_new_with_cause( DDCRC_DETERMINED_UNSUPPORTED, wrapped_exception, __func__, "DDC NULL Message"); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, "*table_bytes_loc=%p", *table_bytes_loc); return ddc_excp; } /** Gets the value of a VCP feature. * * @param dh handle for open display * @param feature_code feature code id * @param call_type indicates whether table or non-table * @param valrec_loc location where to return newly allocated #Single_Vcp_Value * @return NULL if success, pointer to #Error_Info if failure * * The value pointed to by pvalrec is non-null iff the return value is null * * The caller is responsible for freeing the value returned at **valrec_loc**. */ Error_Info * ddc_get_vcp_value( Display_Handle * dh, Byte feature_code, DDCA_Vcp_Value_Type call_type, DDCA_Any_Vcp_Value ** valrec_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Reading feature 0x%02x, dh=%s, dh->fd=%d", feature_code, dh_repr(dh), dh->fd); // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "communication flags: %s", interpret_dref_flags_t(dh->dref->flags)); Error_Info * ddc_excp = NULL; Buffer * buffer = NULL; Parsed_Nontable_Vcp_Response * parsed_nontable_response = NULL; // vs interpreted .. DDCA_Any_Vcp_Value * valrec = NULL; // why are we coming here for USB? if (dh->dref->io_path.io_mode == DDCA_IO_USB) { #ifdef ENABLE_USB DBGMSF(debug, "USB case"); Public_Status_Code psc = 0; switch (call_type) { case (DDCA_NON_TABLE_VCP_VALUE): psc = usb_get_nontable_vcp_value( dh, feature_code, &parsed_nontable_response); // if (psc == 0) { valrec = create_nontable_vcp_value( feature_code, parsed_nontable_response->mh, parsed_nontable_response->ml, parsed_nontable_response->sh, parsed_nontable_response->sl); free(parsed_nontable_response); } else ddc_excp = ERRINFO_NEW(psc, NULL); break; case (DDCA_TABLE_VCP_VALUE): ddc_excp = ERRINFO_NEW(DDCRC_UNIMPLEMENTED, "Table features not supported for USB connection"); break; } #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif } else { switch (call_type) { case (DDCA_NON_TABLE_VCP_VALUE): ddc_excp = ddc_get_nontable_vcp_value( dh, feature_code, &parsed_nontable_response); if (!ddc_excp) { valrec = create_nontable_vcp_value( feature_code, parsed_nontable_response->mh, parsed_nontable_response->ml, parsed_nontable_response->sh, parsed_nontable_response->sl); free(parsed_nontable_response); } break; case (DDCA_TABLE_VCP_VALUE): ddc_excp = ddc_get_table_vcp_value( dh, feature_code, &buffer); if (!ddc_excp) { valrec = create_table_vcp_value_by_buffer(feature_code, buffer); buffer_free(buffer, __func__); } break; } } // non USB *valrec_loc = valrec; ASSERT_IFF(!ddc_excp,*valrec_loc); DBGTRC_RET_ERRINFO_STRUCT(debug, TRACE_GROUP, ddc_excp, valrec_loc, dbgrpt_single_vcp_value); return ddc_excp; } // // Setvcp Verification // /** Sets the setvcp verification setting for the current thread. * * If enabled, setvcp will read the feature value from the monitor after * writing it, to ensure the monitor has actually changed the feature value. * * @param onoff **true** for enabled, **false** for disabled. * @return prior setting */ bool ddc_set_verify_setvcp(bool onoff) { // bool debug = false; // DBGMSF(debug, "Setting verify_setvcp = %s", sbool(onoff)); Thread_Vcp_Settings * settings = get_thread_vcp_settings(); bool old_value = settings->verify_setvcp; settings->verify_setvcp = onoff; return old_value; } /** Gets the current setvcp verification setting for the current thread. * * @return **true** if setvcp verification enabled\n * **false** if not */ bool ddc_get_verify_setvcp() { Thread_Vcp_Settings * settings = get_thread_vcp_settings(); return settings->verify_setvcp; } /** Checks whether it is meaningful to read a feature value for verification * after it has been written. * * It is invalid if either: * - the feature is not readable * - the feature is one for which it is not meaningful to read the value after writing * * @param dh display handle * @param opcode VCP feature code * @return **true** if feature can be usefully reread\n * **false** if not */ STATIC bool is_rereadable_feature( Display_Handle * dh, DDCA_Vcp_Feature_Code opcode) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "opcode = 0x%02x", opcode); // readable features that should not be read after write DDCA_Vcp_Feature_Code unrereadable_features[] = { 0x02, // new control value 0x03, // soft controls 0x60, // input source - for some monitors it is meaningful to read the new // value, others won't respond if set to a different input }; bool result = true; for (int ndx = 0; ndx < ARRAY_SIZE(unrereadable_features); ndx++) { if ( unrereadable_features[ndx] == opcode ) { result = false; DBGMSF(debug, "Unreadable opcode 0x%02x", opcode); break; } } if (result) { Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dh(opcode, dh, /*check_udf=*/ true, /*with_default*/false); // if not found, assume readable ?? if (dfm) { result = dfm->version_feature_flags & DDCA_READABLE; dfm_free(dfm); } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, ""); return result; } /** Checks for specific NC feature values that cannot be read after they have been set * * @param opcode VCP feature code * @param sl_value feature value that cannot be verified * @return **true** if feature should not be read, **false** if ok */ STATIC bool is_unreadable_sl_value( DDCA_Vcp_Feature_Code opcode, Byte sl_value) { bool debug = false; DBGMSF(debug, "opcode=0x%02x, sl_value=0x%02x", opcode, sl_value); bool result = false; switch(opcode) { case 0xd6: if (sl_value == 5) // turn off display, trying to read from it will fail result = true; break; default: break; } DBGMSF(debug, "Done. Returning: %s", sbool(result)); return result; } STATIC bool single_vcp_value_equal( DDCA_Any_Vcp_Value * vrec1, DDCA_Any_Vcp_Value * vrec2) { assert(vrec1 && vrec2); // no implementation for degenerate cases bool debug = false; bool result = false; if (vrec1->opcode == vrec2->opcode && vrec1->value_type == vrec2->value_type) { switch(vrec1->value_type) { case(DDCA_NON_TABLE_VCP_VALUE): // N.B. not handling SH byte which would be set for NC feature // or for a C feature using the upper byte // only check SL byte which would be set for any VCP, monitor result = (vrec1->val.c_nc.sl == vrec2->val.c_nc.sl); break; case(DDCA_TABLE_VCP_VALUE): result = (vrec1->val.t.bytect == vrec2->val.t.bytect) && (memcmp(vrec1->val.t.bytes, vrec2->val.t.bytes, vrec1->val.t.bytect) == 0 ); } } DBGMSF(debug, "Returning: %s", sbool(result)); return result; } // // Set VCP feature values // /** Sets a non-table VCP feature value. * * @param dh display handle for open display * @param feature_code VCP feature code * @param new_value new value * @return NULL if success, * pointer to #Error_Info from #ddc_write_only_with_retry() if failure */ Error_Info * ddc_set_nontable_vcp_value( Display_Handle * dh, Byte feature_code, int new_value) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Writing feature 0x%02x , new value = %d, dh=%s", feature_code, new_value, dh_repr(dh) ); Public_Status_Code psc = 0; Error_Info * ddc_excp = NULL; if (dh->dref->io_path.io_mode == DDCA_IO_USB) { #ifdef ENABLE_USB psc = usb_set_nontable_vcp_value(dh, feature_code, new_value); #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif } else { DDC_Packet * request_packet_ptr = create_ddc_setvcp_request_packet(feature_code, new_value, "set_vcp:request packet"); // DBGMSG("create_ddc_getvcp_request_packet returned packet_ptr=%p", request_packet_ptr); // dump_packet(request_packet_ptr); ddc_excp = ddc_write_only_with_retry(dh, request_packet_ptr); psc = (ddc_excp) ? ddc_excp->status_code : 0; free_ddc_packet(request_packet_ptr); } if ( psc==DDCRC_RETRIES ) DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Try errors: %s", errinfo_causes_string(ddc_excp)); // needed? DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } /** Sets a table VCP feature value. * * @param dh display handle for open display * @param feature_code VCP feature code * @param bytes pointer to table bytes * @param bytect number of bytes * @return NULL if success * DDCRC_UNIMPLEMENTED if io mode is USB * #Error_Info from #multi_part_write_with_retry() otherwise */ static Error_Info * set_table_vcp_value( Display_Handle * dh, Byte feature_code, Byte * bytes, int bytect) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Writing feature 0x%02x , bytect = %d", feature_code, bytect); Public_Status_Code psc = 0; Error_Info * ddc_excp = NULL; if (dh->dref->io_path.io_mode == DDCA_IO_USB) { #ifdef ENABLE_USB psc = DDCRC_UNIMPLEMENTED; #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); psc = DDCRC_INTERNAL_ERROR; #endif ddc_excp = ERRINFO_NEW(psc, "Error setting feature value"); } else { // TODO: clean up function signatures // pointless wrapping in a Buffer just to unwrap Buffer * new_value = buffer_new_with_value(bytes, bytect, __func__); ddc_excp = multi_part_write_with_retry(dh, feature_code, new_value); psc = (ddc_excp) ? ddc_excp->status_code : 0; buffer_free(new_value, __func__); } if ( psc == DDCRC_RETRIES ) DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Try errors: %s", errinfo_causes_string(ddc_excp)); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } // TODO: Consider wrapping set_vcp_value() in set_vcp_value_with_retry(), which would // retry in case verification fails (work in progress) /** Sets a VCP feature value. * * @param dh display handle for open display * @param vrec pointer to value record * @param newval_loc if non-null, address at which to return verified value * @return NULL if success, pointer to #Error_Info if failure * * If write verification is turned on, reads the feature value after writing it * to ensure the display has actually changed the value. * * The caller is responsible for freeing the value returned at **newval_loc**. * @remark * If verbose messages are in effect, writes detailed messages to the current * stdout device. */ Error_Info * ddc_set_vcp_value( Display_Handle * dh, DDCA_Any_Vcp_Value * vrec, DDCA_Any_Vcp_Value ** newval_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); FILE * verbose_msg_dest = fout(); if ( get_output_level() < DDCA_OL_VERBOSE && !debug ) verbose_msg_dest = NULL; Error_Info * ddc_excp = NULL; if (newval_loc) *newval_loc = NULL; if (vrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { ddc_excp = ddc_set_nontable_vcp_value(dh, vrec->opcode, VALREC_CUR_VAL(vrec)); } else { assert(vrec->value_type == DDCA_TABLE_VCP_VALUE); ddc_excp = set_table_vcp_value(dh, vrec->opcode, vrec->val.t.bytes, vrec->val.t.bytect); } if (!ddc_excp && ddc_get_verify_setvcp()) { Public_Status_Code psc = 0; if ( is_rereadable_feature(dh, vrec->opcode) && ( vrec->value_type != DDCA_NON_TABLE_VCP_VALUE || !is_unreadable_sl_value(vrec->opcode, vrec->val.c_nc.sl) ) ) { f0printf(verbose_msg_dest, "Verifying that value of feature 0x%02x successfully set...\n", vrec->opcode); DDCA_Any_Vcp_Value * newval = NULL; ddc_excp = ddc_get_vcp_value( dh, vrec->opcode, vrec->value_type, &newval); psc = (ddc_excp) ? ddc_excp->status_code : 0; if (ddc_excp) { f0printf(verbose_msg_dest, "(%s) Read after write failed. get_vcp_value() returned: %s\n", __func__, psc_desc(psc)); if (psc == DDCRC_RETRIES) f0printf(verbose_msg_dest, "(%s) Try errors: %s\n", __func__, errinfo_causes_string(ddc_excp)); // psc = DDCRC_VERIFY; } else { assert(vrec && newval); // silence clang complaint // dbgrpt_ddca_single_vcp_value(vrec, 2); // dbgrpt_ddca_single_vcp_value(newval, 3); if (! single_vcp_value_equal(vrec,newval)) { ddc_excp = ERRINFO_NEW(DDCRC_VERIFY, "Current value does not match value set"); f0printf(verbose_msg_dest, "Current value does not match value set.\n"); } else { f0printf(verbose_msg_dest, "Verification succeeded\n"); } if (newval_loc) *newval_loc = newval; else free_single_vcp_value(newval); } } else { if (!is_rereadable_feature(dh, vrec->opcode) ) f0printf(verbose_msg_dest, "" "Feature 0x%02x does not support verification\n", vrec->opcode); else f0printf(verbose_msg_dest, "Feature 0x%02x, value 0x%02x does not support verification\n", vrec->opcode, vrec->val.c_nc.sl); } } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, ddc_excp, ""); return ddc_excp; } Error_Info * ddc_set_verified_vcp_value_with_retry( Display_Handle * dh, DDCA_Any_Vcp_Value * vrec, DDCA_Any_Vcp_Value ** newval_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, newval_loc=%p, max_setvcp_verify_tries=%d", dh_repr(dh), newval_loc, max_setvcp_verify_tries); Error_Info * erec = NULL; if (newval_loc) *newval_loc = NULL; bool verification_enabled = ddc_get_verify_setvcp(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "verification_enabled = %s", sbool(verification_enabled)); if (vrec->value_type == DDCA_NON_TABLE_VCP_VALUE && verification_enabled && is_rereadable_feature(dh, vrec->opcode) && !is_unreadable_sl_value(vrec->opcode, vrec->val.c_nc.sl) ) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Retry loop"); GPtrArray * verification_failures = g_ptr_array_new(); for (int try_ctr = 0; try_ctr < max_setvcp_verify_tries; try_ctr++) { erec = ddc_set_nontable_vcp_value(dh, vrec->opcode, VALREC_CUR_VAL(vrec)); if (!erec || ERRINFO_STATUS(erec) != DDCRC_VERIFY) break; g_ptr_array_add(verification_failures, erec); } if (erec && ERRINFO_STATUS(erec) == DDCRC_VERIFY) { erec = errinfo_new_with_causes_gptr(DDCRC_VERIFY, verification_failures, __func__, "Maximum setvcp verification failures (%d)", max_setvcp_verify_tries); } g_ptr_array_set_free_func(verification_failures, (GDestroyNotify) errinfo_free); g_ptr_array_free(verification_failures, true); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Non-loop call of ddc_set_vcp_value"); erec = ddc_set_vcp_value(dh, vrec, newval_loc); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, erec, ""); return erec; } void init_ddc_vcp() { RTTI_ADD_FUNC(ddc_get_nontable_vcp_value); RTTI_ADD_FUNC(ddc_get_table_vcp_value); RTTI_ADD_FUNC(ddc_get_vcp_value); RTTI_ADD_FUNC(ddc_set_nontable_vcp_value); RTTI_ADD_FUNC(ddc_set_vcp_value); RTTI_ADD_FUNC(ddc_set_verified_vcp_value_with_retry); RTTI_ADD_FUNC(is_rereadable_feature); RTTI_ADD_FUNC(set_table_vcp_value); } ddcutil-2.2.0/src/ddc/ddc_vcp_version.c0000644000175000001440000002506714754153540013476 /** @file ddc_vcp_version.c * * Functions to obtain the VCP (MCCS) version for a display. * These functions are in a separate source file to simplify * the acyclic graph of #includes within the ddc source directory. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include /** \cond */ #include #include #include "util/error_info.h" #include "util/traced_function_stack.h" /** \endcond */ #include "util/debug_util.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/displays.h" #include "base/rtti.h" #include "base/status_code_mgt.h" #ifdef ENABLE_USB #include "usb/usb_vcp.h" #endif #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp.h" #include "ddc/ddc_vcp_version.h" // // Functions for VCP (MCCS) version // DDCA_MCCS_Version_Spec set_vcp_version_xdf_by_dh(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dh=%s", dh_repr(dh)); dh->dref->vcp_version_xdf = DDCA_VSPEC_UNKNOWN; if (dh->dref->io_path.io_mode == DDCA_IO_USB) { #ifdef ENABLE_USB // DBGMSG("Trying to get VESA version..."); __s32 vesa_ver = usb_get_vesa_version(dh->fd); DBGMSF(debug, "VESA version from usb_get_vesa_version(): 0x%08x", vesa_ver); if (vesa_ver) { DBGMSF(debug, "VESA version from usb_get_vesa_version(): 0x%08x", vesa_ver); dh->dref->vcp_version_xdf.major = (vesa_ver >> 8) & 0xff; dh->dref->vcp_version_xdf.minor = vesa_ver & 0xff; } else { DBGMSF(debug, "Error detecting VESA version using usb_get_vesa_version()"); } #else PROGRAM_LOGIC_ERROR("ddcutil not built with USB support"); #endif } else { // normal case, not USB #ifdef REF Parsed_Nontable_Vcp_Response * parsed_response_loc = NULL; rpt_vstring(1, "Getting value of feature 0x%02x", feature_code);; Error_Info * ddc_excp = ddc_get_nontable_vcp_value(dh, feature_code, &parsed_response_loc); ASSERT_IFF(!ddc_excp, parsed_response_loc); if (ddc_excp) { rpt_vstring(2, "ddc_get_nontable_vcp_value() for feature 0x%02x returned: %s", feature_code, errinfo_summary(ddc_excp)); free(ddc_excp); } else { if (!parsed_response_loc->valid_response) rpt_vstring(2, "Invalid Response"); else if (!parsed_response_loc->supported_opcode) rpt_vstring(2, "Unsupported feature code"); else { rpt_vstring(2, "getvcp 0x%02x succeeded", feature_code); rpt_vstring(2, "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", parsed_response_loc->mh, parsed_response_loc->ml, parsed_response_loc->sh, parsed_response_loc->sl); } free(parsed_response_loc); } #endif Parsed_Nontable_Vcp_Response * parsed_response_loc = NULL; // verbose output is distracting since this function is called when // querying for other things DDCA_Output_Level olev = get_output_level(); if (olev == DDCA_OL_VERBOSE) set_output_level(DDCA_OL_NORMAL); Error_Info * ddc_excp = ddc_get_nontable_vcp_value(dh, 0xdf, &parsed_response_loc); ASSERT_IFF(!ddc_excp, parsed_response_loc); if (olev == DDCA_OL_VERBOSE) set_output_level(olev); const char * e1 = "Error detecting VCP version using VCP feature xDF:"; if (ddc_excp) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "%s %s", e1, errinfo_summary(ddc_excp)); ERRINFO_FREE(ddc_excp); } else { if (!parsed_response_loc->valid_response) MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "%s Invalid response", e1); else if (!parsed_response_loc->supported_opcode) { // happens for pre MCCS v2 monitors MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "%s Unsupported feature code", e1); } else { dh->dref->vcp_version_xdf.major = parsed_response_loc->sh; // pvalrec->val.c_nc.sh; dh->dref->vcp_version_xdf.minor = parsed_response_loc->sl; // pvalrec->val.c_nc.sl; DBGMSF(debug, "Set dh->dref->vcp_version_xdf to %d.%d, %s", dh->dref->vcp_version_xdf.major, dh->dref->vcp_version_xdf.minor, format_vspec(dh->dref->vcp_version_xdf) ); } free(parsed_response_loc); } } // not USB assert( !vcp_version_eq(dh->dref->vcp_version_xdf, DDCA_VSPEC_UNQUERIED) ); DBGTRC_DONE(debug, DDCA_TRC_NONE, "dh=%s, Returning newly set dh->dref->vcp_version_xdf = %s", dh_repr(dh), format_vspec(dh->dref->vcp_version_xdf)); return dh->dref->vcp_version_xdf; } DDCA_MCCS_Version_Spec get_overriding_vcp_version( Display_Ref * dref) { bool debug = false; // TMI if (debug) { DBGMSG(" dh->dref->vcp_version_cmdline = %s", format_vspec_verbose(dref->vcp_version_cmdline)); if (dref->dfr) DBGMSG(" dh->dref->dfr->vspec = %s", format_vspec_verbose(dref->dfr->vspec)); else DBGMSG(" dh->dref->dfr == NULL"); } DDCA_MCCS_Version_Spec result = DDCA_VSPEC_UNQUERIED; if (vcp_version_is_valid(dref->vcp_version_cmdline, false)) { result = dref->vcp_version_cmdline; DBGMSF(debug, "Using dref->vcp_version_cmdline = %s", format_vspec(result)); } else if (dref->dfr && vcp_version_is_valid(dref->dfr->vspec, /* allow_unknown */ false)) { result = dref->dfr->vspec; DBGMSF(debug, "Using dref->dfr->vspec = %s", format_vspec_verbose(result)); } return result; } DDCA_MCCS_Version_Spec get_saved_vcp_version( Display_Ref * dref) { bool debug = false; DDCA_MCCS_Version_Spec result = DDCA_VSPEC_UNKNOWN; result = get_overriding_vcp_version(dref); if (vcp_version_eq(result, DDCA_VSPEC_UNQUERIED)) { result = dref->vcp_version_xdf; DBGMSF(debug, "Using dref->vcp_version_xdf = %s", format_vspec_verbose(result)); } DBGMSF(debug, "dref=%s, Returning: %s", dref_repr_t(dref), format_vspec_verbose(result)); return result; } /** Gets the VCP version. * * Because the VCP version is used repeatedly for interpreting other * VCP feature values, it is cached. * * \param dh display handle * \return #Version_Spec struct containing version, contains 0.0 if version * could not be retrieved (pre MCCS v2) */ DDCA_MCCS_Version_Spec get_vcp_version_by_dh(Display_Handle * dh) { assert(dh); bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dh=%s, dref=%s", dh_repr(dh), dref_repr_t(dh->dref)); DDCA_MCCS_Version_Spec result = DDCA_VSPEC_UNKNOWN; result = get_saved_vcp_version(dh->dref); if (vcp_version_eq(result, DDCA_VSPEC_UNQUERIED)) { result = set_vcp_version_xdf_by_dh(dh); assert( !vcp_version_eq(dh->dref->vcp_version_xdf, DDCA_VSPEC_UNQUERIED) ); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: %s", format_vspec_verbose(result)); return result; } /** Gets the VCP version. * * Because the VCP version is used repeatedly for interpreting other * VCP feature values, it is cached. * * \param dref display reference * \return #Version_Spec struct containing version, contains 0.0 if version * could not be retrieved (pre MCCS v2) * * Precedence of VCP versions: * - version specified on the command line * - version in a dynamic feature record for the display * - version returned by feature xDF */ DDCA_MCCS_Version_Spec get_vcp_version_by_dref(Display_Ref * dref) { assert(dref); bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE,"dref=%s", dref_repr_t(dref)); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE,"dref->vcp_version_cmdline = %s", format_vspec_verbose(dref->vcp_version_cmdline)); if (dref->dfr) DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "dref->dfr->vspec = ", format_vspec_verbose(dref->dfr->vspec)); else DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "dref->dfr is null"); DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "dref->vcp_version_xdf = %s", format_vspec_verbose (dref->vcp_version_xdf)); if (!(dref->flags & DREF_DDC_COMMUNICATION_WORKING)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "flags: %s", interpret_dref_flags_t(dref->flags) ); } } DDCA_MCCS_Version_Spec result = get_saved_vcp_version(dref); if (vcp_version_eq(result, DDCA_VSPEC_UNQUERIED)) { if (!(dref->flags & DREF_DDC_COMMUNICATION_WORKING)) { DBGMSG( "DREF_DDC_COMMUNICATION_WORKING not set. dref=%s", dref_repr_t(dref)); dbgrpt_display_ref(dref, true, 2); debug_current_traced_function_stack(/*reverse*/ true); SYSLOG2(DDCA_SYSLOG_ERROR, "DREF_DDC_COMMUNICATION_WORKING not set. dref=%s", dref_repr_t(dref)); current_traced_function_stack_to_syslog(LOG_ERR, /* reverse */ true); backtrace_to_syslog(LOG_ERR, 0); // ASSERT_WITH_BACKTRACE(false); // ASSERT_WITH_BACKTRACE(dref->flags & DREF_DDC_COMMUNICATION_WORKING) ; result = DDCA_VSPEC_UNKNOWN; } else { Display_Handle * dh = NULL; // ddc_open_display() should not fail // 2/2020: but it can return -EBUSY // DBGMSF(debug, "Calling ddc_open_display() ..."); Error_Info * ddc_excp = ddc_open_display(dref, CALLOPT_ERR_MSG, &dh); if (!ddc_excp) { result = set_vcp_version_xdf_by_dh(dh); assert( !vcp_version_eq(dh->dref->vcp_version_xdf, DDCA_VSPEC_UNQUERIED) ); // DBGMSF(debug, "Calling ddc_close_display() ..."); ddc_close_display_wo_return(dh); } else { // DBGMSF(debug, "ddc_open_display() failed"); SYSLOG2((ddc_excp->status_code == -EBUSY) ? DDCA_SYSLOG_INFO : DDCA_SYSLOG_ERROR, "Unable to open display %s: %s", dref_repr_t(dref), psc_desc(ddc_excp->status_code)); dh->dref->vcp_version_xdf = DDCA_VSPEC_UNKNOWN; errinfo_free(ddc_excp); } } } assert( !vcp_version_eq(result, DDCA_VSPEC_UNQUERIED) ); DBGTRC_DONE(debug, DDCA_TRC_NONE, "dref=%s, Returning: %s", dref_repr_t(dref), format_vspec_verbose(result)); return result; } void init_ddc_vcp_version() { RTTI_ADD_FUNC(set_vcp_version_xdf_by_dh); RTTI_ADD_FUNC(get_vcp_version_by_dref); RTTI_ADD_FUNC(get_vcp_version_by_dh); } ddcutil-2.2.0/src/ddc/ddc_try_data.c0000644000175000001440000003222614572333721012742 /** @file ddc_try_stats.c * * Maintains statistics on DDC retries, along with maxtries settings. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include /** \endcond */ #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/display_retry_data.h" #include "base/parms.h" #include "base/rtti.h" #include "base/stats.h" // // Locking // static GMutex try_data_mutex; static GPrivate this_thread_has_lock; static bool debug_mutex = false; /** If **try_data_mutex** is not already locked by the current thread, * lock it. * * \remark * This function is necessary because the behavior if a GLib mutex is * relocked by the current thread is undefined. */ // avoids locking if this thread already owns the lock, since behavior undefined bool lock_if_unlocked() { bool debug = false; debug = debug || debug_mutex; bool lock_performed = false; bool thread_has_lock = GPOINTER_TO_INT(g_private_get(&this_thread_has_lock)); DBGMSF(debug, "Already locked: %s", sbool(thread_has_lock)); if (!thread_has_lock) { g_mutex_lock(&try_data_mutex); lock_performed = true; // should this be a depth counter rather than a boolean? g_private_set(&this_thread_has_lock, GINT_TO_POINTER(true)); if (debug) { intmax_t cur_thread_id = get_thread_id(); DBGMSG("Locked by thread %d", cur_thread_id); } } DBGMSF(debug, "Returning: %s", sbool(lock_performed) ); return lock_performed; } /** Unlocks the **try_data_mutex** set by a call to #lock_if_unlocked * * \param unlock_requested perform unlock */ void unlock_if_needed(bool unlock_requested) { bool debug = false; debug = debug || debug_mutex; DBGMSF(debug, "unlock_requested=%s", sbool(unlock_requested)); if (unlock_requested) { // is it actually locked? bool currently_locked = GPOINTER_TO_INT(g_private_get(&this_thread_has_lock)); DBGMSF(debug, "currently_locked = %s", sbool(currently_locked)); if (currently_locked) { g_private_set(&this_thread_has_lock, GINT_TO_POINTER(false)); if (debug) { intmax_t cur_thread_id = get_thread_id(); DBGMSG("Unlocked by thread %d", cur_thread_id); } g_mutex_unlock(&try_data_mutex); } } DBGMSF(debug, "Done"); } /** Requests a lock on the **try data** data structure. * A lock is not performed if the current thread already holds the lock * * \return true if a lock was actually performed */ bool try_data_lock() { return lock_if_unlocked(); } /** Requests that the currently held lock on the **try_data** data structure * be released * * \param release_requested if true, attempt to unlock */ void try_data_unlock(bool release_requested) { unlock_if_needed(release_requested); } // counters usage: // 0 number of failures because of fatal errors // 1 number of failures because retry exceeded // n>1 number of successes after n-1 tries, // e.g. if succeed after 1 try, recorded in counter 2 // 1 instance for each retry type typedef struct { Retry_Operation retry_type; Retry_Op_Value maxtries; Retry_Op_Value counters[MAX_MAX_TRIES+2]; Retry_Op_Value highest_maxtries; Retry_Op_Value lowest_maxtries; } Try_Data2; static Retry_Op_Value default_maxtries[] = { INITIAL_MAX_WRITE_ONLY_EXCHANGE_TRIES, INITIAL_MAX_WRITE_READ_EXCHANGE_TRIES, INITIAL_MAX_MULTI_EXCHANGE_TRIES, INITIAL_MAX_MULTI_EXCHANGE_TRIES }; static Try_Data2 try_data[RETRY_OP_COUNT]; /* Initializes a Try_Data data structure * * @param retry_type Retry_Operation type * #param maxtries maximum number of tries */ void try_data_init_retry_type(Retry_Operation retry_type, Retry_Op_Value maxtries) { bool debug = false; DBGTRC(debug, DDCA_TRC_NONE, "Executing. retry_type=%s, maxtries=%d", retry_type_name(retry_type), maxtries); try_data[retry_type].retry_type = retry_type; try_data[retry_type].maxtries = maxtries; try_data[retry_type].highest_maxtries = maxtries; try_data[retry_type].lowest_maxtries = maxtries; } /** Performs initialization at time of program startup. */ void init_ddc_try_data() { for (int retry_type = 0; retry_type < RETRY_OP_COUNT; retry_type++) { try_data_init_retry_type(retry_type, default_maxtries[retry_type]); } RTTI_ADD_FUNC(try_data_get_maxtries2); } // // Maxtries // /** Gets the current maximum number of tries allowed for an operation * * \param retry_type * \return maxtries value */ Retry_Op_Value try_data_get_maxtries2(Retry_Operation retry_type) { bool debug = false; int result = try_data[retry_type].maxtries; DBGTRC_EXECUTED(debug, DDCA_TRC_NONE, "retry type=%s, returning %d", retry_type_name(retry_type), result); return result; } /** Sets the maxtries value for an operation * * \param retry_type * \param new_maxtries */ void try_data_set_maxtries2(Retry_Operation retry_type, Retry_Op_Value new_maxtries) { bool debug = false; Try_Data2 * stats_rec = &try_data[retry_type]; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "stats type: %s for %s, new_maxtries: %d", retry_type_name(stats_rec->retry_type), retry_type_description(stats_rec->retry_type), new_maxtries); assert(new_maxtries >= 1 && new_maxtries <= MAX_MAX_TRIES); bool this_function_performed_lock = lock_if_unlocked(); stats_rec->maxtries = new_maxtries; if (new_maxtries < stats_rec->lowest_maxtries) stats_rec->lowest_maxtries = new_maxtries; if (new_maxtries > stats_rec->highest_maxtries) stats_rec->highest_maxtries = new_maxtries; unlock_if_needed(this_function_performed_lock); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } // // Reset counters // /** Resets the counters to 0 for the specified #Retry_Operation, and resets * the highest and lowest maxtries value seen to the current maxtries value. * * @param retry type */ void try_data_reset2(Retry_Operation retry_type) { bool debug = false; DBGMSF(debug, "Starting, retry type: %s", retry_type_name(retry_type)); bool this_function_performed_lock = lock_if_unlocked(); DBGMSF(debug, "Setting highest_maxtries, lowest_maxtries = current maxtries: %d", try_data[retry_type].maxtries); // Reset does not change the current maxtries value, but it does reset the // highest and lowest values seen to the current value. Retry_Op_Value current_maxtries = try_data[retry_type].maxtries; try_data[retry_type].highest_maxtries = current_maxtries; try_data[retry_type].lowest_maxtries = current_maxtries; for (int ndx=0; ndx < MAX_MAX_TRIES+1; ndx++) try_data[retry_type].counters[ndx] = 0; unlock_if_needed(this_function_performed_lock); DBGMSF(debug, "Done"); } /** Resets the counters for all retry types */ void try_data_reset2_all() { bool this_function_performed_lock = lock_if_unlocked(); for (int retry_type = 0; retry_type < RETRY_OP_COUNT; retry_type++) { try_data_reset2(retry_type); } unlock_if_needed(this_function_performed_lock); } /** Records the status and retry count for a retryable transaction * * @param retry_type * @param ddcrc status code * @param tryct number of tries required for success, when rc == 0 * * @remark * Also calls #trd_record_cur_thread_ties() to record the transaction status * in the per-thread data structure. */ void try_data_record_tries2(Display_Handle * dh, Retry_Operation retry_type, DDCA_Status ddcrc, int tryct) { bool debug = false; DBGMSF(debug, "retry_type = %d - %s, ddcrc=%d, tryct=%d", retry_type, retry_type_name(retry_type), ddcrc, tryct); // trd_record_cur_thread_tries(retry_type, ddcrc, tryct); Per_Display_Data * pdd = dh->dref->pdd; drd_record_display_tries(pdd, retry_type, ddcrc, tryct); Try_Data2 * stats_rec = &try_data[retry_type]; bool locked_by_this_func = lock_if_unlocked(); if (ddcrc == 0) { DBGMSF(debug, "Current stats_rec->maxtries=%d", stats_rec->maxtries); assert(0 < tryct && tryct <= stats_rec->maxtries); stats_rec->counters[tryct+1] += 1; } // fragile, but eliminates testing for max_tries: else if (ddcrc == DDCRC_RETRIES || ddcrc == DDCRC_ALL_TRIES_ZERO) { // failed for max tries exceeded stats_rec->counters[1] += 1; } else { // failed fatally stats_rec->counters[0] += 1; } unlock_if_needed(locked_by_this_func); } // // Reporting // // used to test whether there's anything to report static int try_data_get_total_attempts2(Retry_Operation retry_type) { int total_attempts = 0; int ndx; for (ndx=0; ndx <= MAX_MAX_TRIES+1; ndx++) { total_attempts += try_data[retry_type].counters[ndx]; } return total_attempts; } /** Reports try statistics for a specified #Retry_Operation * * Output is written to the current FOUT destination. * * \param retry_type * \param depth logical indentation depth * */ void try_data_report2(Retry_Operation retry_type, int depth) { // bool debug = false; int d1 = depth+1; rpt_nl(); Try_Data2 * stats_rec = &try_data[retry_type]; rpt_vstring(depth, "Retry statistics for %s", retry_type_description(retry_type)); bool this_function_performed_lock = lock_if_unlocked(); // doesn't distinguish write vs read // rpt_vstring(depth, "Retry statistics for ddc %s exchange", ddc_retry_type_description(stats_rec->retry_type)); int total_attempts = try_data_get_total_attempts2(retry_type); if (total_attempts == 0) { rpt_vstring(d1, "No tries attempted"); } else { int total_successful_attempts = 0; int max1 = stats_rec->maxtries; rpt_vstring(d1, "Max tries allowed: %d", max1); int upper_bound = MAX_MAX_TRIES+1; while (upper_bound > 1) { if (stats_rec->counters[upper_bound] != 0) break; upper_bound--; } // n upper_bound = 1 if no successful attempts char * s = (upper_bound == 1) ? " None" : ""; rpt_vstring(d1, "Successful attempts by number of tries required:%s", s); if (upper_bound > 1) { for (int ndx=2; ndx <= upper_bound; ndx++) { total_successful_attempts += stats_rec->counters[ndx]; // DBGMSG("ndx=%d", ndx); rpt_vstring(d1, " %2d: %3d", ndx-1, stats_rec->counters[ndx]); } } assert( ( (upper_bound == 1) && (total_successful_attempts == 0) ) || ( (upper_bound > 1 ) && (total_successful_attempts > 0) ) ); rpt_vstring(d1, "Total successful attempts: %3d", total_successful_attempts); rpt_vstring(d1, "Failed due to max tries exceeded: %3d", stats_rec->counters[1]); rpt_vstring(d1, "Failed due to fatal error: %3d", stats_rec->counters[0]); rpt_vstring(d1, "Total attempts: %3d", total_attempts); } unlock_if_needed(this_function_performed_lock); } #ifdef OLD void ddc_report_write_read_stats(int depth) { try_data_report2(WRITE_READ_TRIES_OP, depth); } void ddc_report_write_only_stats(int depth) { try_data_report2(WRITE_ONLY_TRIES_OP, depth); } /** Reports the statistics for multi-part reads */ void ddc_report_multi_part_read_stats(int depth) { try_data_report2(MULTI_PART_READ_OP, depth); } /** Reports the statistics for multi-part writes */ void ddc_report_multi_part_write_stats(int depth) { try_data_report2(MULTI_PART_WRITE_OP, depth); } #endif static inline void ddc_report_max_tries_for_op(Retry_Operation op, char * title, int depth) { Try_Data2 td = try_data[op]; rpt_vstring(depth, "%-32s %6d %8d %7d %7d", title, td.maxtries, INITIAL_MAX_WRITE_ONLY_EXCHANGE_TRIES, td.lowest_maxtries, td.highest_maxtries); } /** Reports the current maxtries settings. * * \param depth logical indentation depth */ void ddc_report_max_tries(int depth) { rpt_vstring(depth, "Maxtries Settings:"); rpt_vstring(depth, "Operation Type Current Default Min Max"); ddc_report_max_tries_for_op(WRITE_ONLY_TRIES_OP,"Write only exchange tries:", depth); ddc_report_max_tries_for_op(WRITE_READ_TRIES_OP,"Write read exchange tries:", depth); ddc_report_max_tries_for_op(MULTI_PART_READ_OP, "Multi-part read exchange tries:", depth); ddc_report_max_tries_for_op(MULTI_PART_WRITE_OP,"Multi-part_write exchange tries:", depth); rpt_nl(); } /** Reports all DDC level statistics * \param depth logical indentation depth */ void ddc_report_ddc_stats(int depth) { // rpt_nl(); // retry related stats ddc_report_max_tries(depth); try_data_report2(WRITE_ONLY_TRIES_OP, depth); // ddc_report_write_only_stats(depth); try_data_report2(WRITE_READ_TRIES_OP, depth); // ddc_report_write_read_stats(depth); try_data_report2(MULTI_PART_READ_OP, depth); // ddc_report_multi_part_read_stats(depth); try_data_report2(MULTI_PART_WRITE_OP, depth); // ddc_report_multi_part_write_stats(depth); } ddcutil-2.2.0/src/ddc/clang_output_nAhcNw0000644000175000001440000000043214754576332014045 ddc_displays.c:721:25: error: incompatible integer to pointer conversion assigning to 'Parsed_Edid *' from 'int' [-Wint-conversion] dref->pedid = copy_parsed_edid(businfo->edid); // needed? ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated. ddcutil-2.2.0/src/ddc/ddc_display_ref_reports.h0000644000175000001440000000125314754576332015224 /** @file ddc_display_ref_reports.h */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_DISPLAY_REF_REPORTS_H_ #define DDC_DISPLAY_REF_REPORTS_H_ #include #include #include "base/displays.h" // Display_Ref Reports void ddc_report_display_by_dref(Display_Ref * dref, int depth); int ddc_report_displays(bool include_invalid_displays, int depth); void ddc_dbgrpt_display_ref(Display_Ref * drec, int depth); void ddc_dbgrpt_drefs(char * msg, GPtrArray* ptrarray, int depth); // Initialization void init_ddc_display_ref_reports(); #endif /* DDC_DISPLAY_REF_REPORTS_H_ */ ddcutil-2.2.0/src/ddc/ddc_dumpload.h0000644000175000001440000000432014754576332012750 /** \file dumpload.h * * Load/store VCP settings from/to file. */ // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_DUMPLOAD_H_ #define DDC_DUMPLOAD_H_ /** \cond */ #include #include "util/error_info.h" /** \endcond */ #include "base/displays.h" #include "base/status_code_mgt.h" #include "vcp/vcp_feature_values.h" /** Internal form data structure used to hold data being loaded or dumped. Whatever the external form, a file or a string, loadvcp converts the data to **Dumpload_Data** and then writes the data to the monitor. */ typedef struct { time_t timestamp_millis; ///< creation timestamp Byte edidbytes[128]; ///< 128 byte EDID, char edidstr[257]; ///< 128 byte EDID as hex string (for future use) char mfg_id[4]; ///< 3 character manufacturer id (from EDID) char model[14]; ///< model string (from EDID) char serial_ascii[14]; ///< serial number string (from EDID) uint16_t product_code; ///< numeric product code (from EDID) DDCA_MCCS_Version_Spec vcp_version; ///< monitor VCP/MCCS version int vcp_value_ct; ///< number of VCP values Vcp_Value_Set vcp_values; ///< VCP values } Dumpload_Data; void dbgrpt_dumpload_data(Dumpload_Data * data, int depth); void free_dumpload_data(Dumpload_Data * pdata); char * format_timestamp(time_t time_millis, char * buf, int bufsz); Error_Info * loadvcp_by_dumpload_data( Dumpload_Data* pdata, Display_Handle * dh); Error_Info * loadvcp_by_string( char * catenated, Display_Handle * dh); Error_Info * create_dumpload_data_from_g_ptr_array( GPtrArray * garray, Dumpload_Data ** dumpload_data_loc); GPtrArray * convert_dumpload_data_to_string_array( Dumpload_Data * data); Public_Status_Code dumpvcp_as_dumpload_data( Display_Handle * dh, Dumpload_Data** dumpload_data_loc); Public_Status_Code dumpvcp_as_string( Display_Handle * dh, char** result_loc); void init_ddc_dumpload(); #endif /* DDC_DUMPLOAD_H_ */ ddcutil-2.2.0/src/ddc/ddc_strategy.h0000644000175000001440000000140114754576332013002 /** @file ddc_strategy.h */ // Copyright (C) 2017 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_STRATEGY_H_ #define DDC_STRATEGY_H_ #include "util/coredefs.h" #include "base/displays.h" #include "base/status_code_mgt.h" // For future use void init_ddc_strategies(); typedef Public_Status_Code (*DDC_Raw_Writer)(Display_Handle * dh, int bytect, Byte * bytes); typedef Public_Status_Code (*DDC_Raw_Reader)(Display_Handle * dh, int bufsize, Byte * buffer); typedef struct { DDCA_IO_Mode io_mode; DDC_Raw_Writer writer; DDC_Raw_Reader reader; } DDC_Strategy; DDC_Raw_Writer ddc_raw_writer(Display_Handle * dh); DDC_Raw_Reader ddc_raw_reader(Display_Handle * dh); #endif /* DDC_STRATEGY_H_ */ ddcutil-2.2.0/src/ddc/ddc_display_selection.h0000644000175000001440000000071514754576332014661 /** @file ddc_display_selection.h */ // Copyright (C) 2022-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_DISPLAY_SELECTION_H_ #define DDC_DISPLAY_SELECTION_H_ #include "base/core.h" #include "base/displays.h" Display_Ref* get_display_ref_for_display_identifier( Display_Identifier* pdid, Call_Options callopts); void init_ddc_display_selection(); #endif /* DDC_DISPLAY_SELECTION_H_ */ ddcutil-2.2.0/src/ddc/ddc_multi_part_io.h0000644000175000001440000000204414754576332014013 /** \file ddc_multi_part_io.h * * Capabilities read and Table feature read/write that require multiple * reads and writes for completion. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_MULTI_PART_IO_H_ #define DDC_MULTI_PART_IO_H_ /** \cond */ #include #include "util/error_info.h" #include "util/data_structures.h" /** \endcond */ #include "base/displays.h" #include "base/status_code_mgt.h" #include "ddc/ddc_packet_io.h" //temp: extern int multi_part_null_adjustment_millis; Error_Info * multi_part_read_with_retry( Display_Handle * dh, Byte request_type, Byte request_subtype, // VCP feature code for table read, ignore for capabilities DDC_Write_Read_Flags write_read_flags, Buffer** ppbuffer); Error_Info * multi_part_write_with_retry( Display_Handle * dh, Byte vcp_code, Buffer * value_to_set); void init_ddc_multi_part_io(); #endif /* DDC_MULTI_PART_IO_H_ */ ddcutil-2.2.0/src/ddc/ddc_read_capabilities.h0000644000175000001440000000101514754576332014565 /** @file ddc_read_capabilities.h */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_READ_CAPABILITIES_H_ #define DDC_READ_CAPABILITIES_H_ /** \cond */ #include "util/error_info.h" /** \endcond */ #include "base/displays.h" // Get capability string for monitor. Error_Info * ddc_get_capabilities_string( Display_Handle * dh, char** caps_loc); void init_ddc_read_capabilities(); #endif /* DDC_READ_CAPABILITIES_H_ */ ddcutil-2.2.0/src/ddc/ddc_serialize.h0000644000175000001440000000131314754576332013131 /** @file ddc_serialize.h */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_SERIALIZE_H_ #define DDC_SERIALIZE_H_ #include #include #include "base/displays.h" extern bool display_caching_enabled; void ddc_enable_displays_cache(bool onoff); char * ddc_displays_cache_file_name(); bool ddc_store_displays_cache(); void ddc_restore_displays_cache(); void ddc_erase_displays_cache(); Display_Ref * ddc_find_deserialized_display(int busno, Byte* edidbytes); void init_ddc_serialize(); void terminate_ddc_serialize(); #endif /* DDC_SERIALIZE_H_ */ ddcutil-2.2.0/src/ddc/ddc_services.h0000644000175000001440000000124514754576332012771 /** @file ddc_services.h * * ddc layer initialization and configuration, statistics management */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_SERVICES_H_ #define DDC_SERVICES_H_ #include #include #include "public/ddcutil_types.h" void init_ddc_services(); void terminate_ddc_services(); void ddc_reset_stats_main(); void ddc_report_stats_main( DDCA_Stats_Type stats, bool report_per_display, bool include_dsa_stats, bool stats_to_syslog_only, int depth); #endif /* DDC_SERVICES_H_ */ ddcutil-2.2.0/src/ddc/ddc_try_data.h0000644000175000001440000000202314754576332012750 /** @file ddc_try_stats.h * * Maintains statistics on DDC retries and also maxtries settings. * * These statistics are global, not broken out by thread. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef TRY_STATS_H_ #define TRY_STATS_H_ #include #include "ddcutil_types.h" #include "base/displays.h" #include "base/stats.h" void try_data_init_retry_type(Retry_Operation retry_type, Retry_Op_Value maxtries); void init_ddc_try_data(); bool try_data_lock(); void try_data_unlock(bool this_function_owns_lock); Retry_Op_Value try_data_get_maxtries2(Retry_Operation retry_type); void try_data_set_maxtries2(Retry_Operation retry_type, Retry_Op_Value new_maxtries); void try_data_reset2_all(); void try_data_record_tries2(Display_Handle * dh, Retry_Operation retry_type, DDCA_Status rc, int tryct); void ddc_report_max_tries(int depth); void ddc_report_ddc_stats(int depth); #endif /* TRY_STATS_H_ */ ddcutil-2.2.0/src/ddc/ddc_common_init.h0000644000175000001440000000114214754576332013455 /** @file common_init.h * Initialization that must be performed very early by both ddcutil and libddcutil */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_COMMON_INIT_H_ #define DDC_COMMON_INIT_H_ #include #include "util/error_info.h" #include "cmdline/parsed_cmd.h" void i2c_discard_caches(Cache_Types caches); Error_Info * init_tracing(Parsed_Cmd * parsed_cmd); Error_Info * submaster_initializer(Parsed_Cmd * parsed_cmd); void init_ddc_common_init(); #endif /* DDC_COMMON_INIT_H_ */ ddcutil-2.2.0/src/ddc/ddc_displays.h0000644000175000001440000000471314754576332013001 /** @file ddc_displays.h * * Access displays, whether DDC or USB */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_DISPLAYS_H_ #define DDC_DISPLAYS_H_ #include "public/ddcutil_types.h" #include "public/ddcutil_c_api.h" #include #include #include "base/ddcutil_types_internal.h" #include "base/displays.h" #include "base/i2c_bus_base.h" #ifdef ENABLE_USB #include "usb/usb_displays.h" #endif extern int dispno_max; extern bool publish_all_display_refs; extern GPtrArray * display_open_errors; // hack for moving redetect_displays to ddc_dw_main.c // Initial Checks void ddc_set_async_threshold(int threshold); // Error_Info * ddc_initial_checks_by_dref(Display_Ref * dref, bool newly_added); // Get Display Information GPtrArray * ddc_get_all_display_refs(); // returns GPtrArray of Display_Ref instances, including invalid displays void ddc_dbgrpt_display_refs(bool include_invalid_displays, bool report_businfo, int depth); void ddc_dbgrpt_display_refs_summary(bool include_invalid_displays, bool report_businfo, int depth); void ddc_dbgrpt_display_refs_terse(bool include_invalid_displays, int depth); GPtrArray * ddc_get_filtered_display_refs(bool include_invalid_displays, bool include_removed_drefs); GPtrArray * ddc_get_bus_open_errors(); int ddc_get_display_count(bool include_invalid_displays); // Display Detection GPtrArray * ddc_detect_all_displays(GPtrArray ** i2c_open_errors_loc); void ddc_ensure_displays_detected(); void ddc_discard_detected_displays(); bool ddc_displays_already_detected(); #ifdef UNUSED Display_Ref* detect_display_by_businfo(I2C_Bus_Info * businfo); #endif DDCA_Status ddc_enable_usb_display_detection(bool onoff); bool ddc_is_usb_display_detection_enabled(); void dbgrpt_bus_open_errors(GPtrArray * open_errors, int depth); typedef enum { DREF_VALIDATE_BASIC_ONLY = 0, DREF_VALIDATE_EDID = 1, DREF_VALIDATE_AWAKE = 2, DREF_VALIDATE_DDC_COMMUNICATION_FAILURE_OK = 3, } Dref_Validation_Options; #define DREF_VALIDATE_ALL (DREF_VALIDATE_EDID | DREF_VALIDATE_AWAKE) DDCA_Status ddc_validate_display_ref2(Display_Ref * dref, Dref_Validation_Options validation_options); // Initialization and termination void init_ddc_displays(); void terminate_ddc_displays(); #endif /* DDC_DISPLAYS_H_ */ ddcutil-2.2.0/src/ddc/ddc_initial_checks.h0000644000175000001440000000105714754576332014120 /** @file ddc_initial_checks.h */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_INITIAL_CHECKS_H_ #define DDC_INITIAL_CHECKS_H_ #include #include "util/error_info.h" #include "base/displays.h" extern bool skip_ddc_checks; extern bool monitor_state_tests; Error_Info * ddc_initial_checks_by_dref(Display_Ref * dref, bool newly_added); void explore_monitor_state(Display_Handle* dh); void init_ddc_initial_checks(); #endif /* DDC_INITIAL_CHECKS_H_ */ ddcutil-2.2.0/src/ddc/ddc_output.h0000644000175000001440000000361714754576332012513 /* \file ddc_output.h */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_OUTPUT_H_ #define DDC_OUTPUT_H_ #include #include #include #include "base/core.h" #include "base/displays.h" #include "base/status_code_mgt.h" #include "dynvcp/vcp_feature_set.h" #include "vcp/vcp_feature_values.h" // TODO: Should probably be in a more general location // Standard printf format strings for reporting feature codes values. extern const char* FMT_CODE_NAME_DETAIL_W_NL; extern const char* FMT_CODE_NAME_DETAIL_WO_NL; #ifdef FUTURE // not currently used Public_Status_Code check_valid_operation_by_feature_rec_and_version( VCP_Feature_Table_Entry * feature_rec, Version_Spec vcp_version, Version_Feature_Flags operation_flags); // not currently used Public_Status_Code check_valid_operation_by_feature_id_and_dh( Byte feature_id, Display_Handle * dh, Version_Feature_Flags operation_flags); #endif Public_Status_Code ddc_collect_raw_subset_values( Display_Handle * dh, VCP_Feature_Subset subset, Vcp_Value_Set vset, bool ignore_unsupported, FILE * msg_fh); Public_Status_Code ddc_get_formatted_value_for_dfm( Display_Handle * dh, Display_Feature_Metadata * dfm, bool suppress_unsupported, bool prefix_value_with_feature_code, char ** formatted_value_loc, FILE * msg_fh); Public_Status_Code ddc_show_vcp_values( Display_Handle * dh, VCP_Feature_Subset subset, GPtrArray * collector, Feature_Set_Flags flags, Bit_Set_256 * features_seen); void init_ddc_output(); #endif /* DDC_OUTPUT_H_ */ ddcutil-2.2.0/src/ddc/ddc_packet_io.h0000644000175000001440000000374314754576332013111 /** @file ddc_packet_io.h * * Functions for performing DDC packet IO, Handles I2C bus retry. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_PACKET_IO_H_ #define DDC_PACKET_IO_H_ #include #include "util/error_info.h" #include "base/core.h" #include "base/ddc_packets.h" #include "base/displays.h" extern bool DDC_Read_Bytewise; extern bool simulate_null_msg_means_unsupported; typedef enum { Write_Read_Flags_None = 0, Write_Read_Flag_All_Zero_Response_Ok = 1, Write_Read_Flag_Capabilities = 2, Write_Read_Flag_Table_Read = 4 } DDC_Write_Read_Flags ; Error_Info * ddc_open_display( Display_Ref * dref, Call_Options callopts, Display_Handle** dh_loc); Error_Info * ddc_close_display( Display_Handle * dh); void ddc_close_display_wo_return( Display_Handle * dh); void ddc_close_all_displays(); DDCA_Status ddc_validate_display_handle2(Display_Handle * dh); void ddc_dbgrpt_valid_display_handles(int depth); Error_Info * ddc_write_only( Display_Handle * dh, DDC_Packet * request_packet_ptr); Error_Info * ddc_write_only_with_retry( Display_Handle * dh, DDC_Packet * request_packet_ptr); Error_Info * ddc_write_read( Display_Handle * dh, DDC_Packet * request_packet_ptr, bool read_bytewise, int max_read_bytes, Byte expected_response_type, Byte expected_subtype, DDC_Packet ** response_packet_ptr_loc ); Error_Info * ddc_write_read_with_retry( Display_Handle * dh, DDC_Packet * request_packet_ptr, int max_read_bytes, Byte expected_response_type, Byte expected_subtype, DDC_Write_Read_Flags flags, DDC_Packet ** response_packet_ptr_loc ); void init_ddc_packet_io(); void terminate_ddc_packet_io(); #endif /* DDC_PACKET_IO_H_ */ ddcutil-2.2.0/src/ddc/ddc_phantom_displays.h0000644000175000001440000000070714754576332014526 /** @file ddc_phantom_displays.h Phantom display detection */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_PHANTOM_DISPLAYS_H_ #define DDC_PHANTOM_DISPLAYS_H_ #include #include extern bool detect_phantom_displays; bool filter_phantom_displays(GPtrArray * all_displays); void init_ddc_phantom_displays(); #endif /* DDC_PHANTOM_DISPLAYS_H_ */ ddcutil-2.2.0/src/ddc/ddc_save_current_settings.h0000644000175000001440000000075714754576332015575 /** @file ddc_save_current_settings.h * Implement DDC command Save Current Settings */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_SAVE_CURRENT_SETTINGS_H_ #define DDC_SAVE_CURRENT_SETTINGS_H_ #include "util/error_info.h" #include "base/displays.h" Error_Info * ddc_save_current_settings( Display_Handle * dh); void init_ddc_save_current_settings(); #endif /* DDC_SAVE_CURRENT_SETTINGS_H_ */ ddcutil-2.2.0/src/ddc/ddc_vcp.h0000644000175000001440000000344614754576332011743 /** \file ddc_vcp.h * Virtual Control Panel access * Basic functions to get and set single values and save current settings. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_VCP_H_ #define DDC_VCP_H_ /** \cond */ #include #include #include "util/error_info.h" /** \endcond */ #include "base/core.h" #include "base/displays.h" #include "base/status_code_mgt.h" #include "vcp/vcp_feature_codes.h" #include "vcp/vcp_feature_values.h" extern bool enable_mock_data; extern bool setvcp_verify_default; extern int max_setvcp_verify_tries; bool ddc_set_verify_setvcp( bool onoff); bool ddc_get_verify_setvcp(); Error_Info * ddc_set_nontable_vcp_value( Display_Handle * dh, Byte feature_code, int new_value); Error_Info * ddc_set_vcp_value( Display_Handle * dh, DDCA_Any_Vcp_Value * vrec, DDCA_Any_Vcp_Value ** newval_loc); Error_Info * ddc_set_verified_vcp_value_with_retry( Display_Handle * dh, DDCA_Any_Vcp_Value * vrec, DDCA_Any_Vcp_Value ** newval_loc); Error_Info * ddc_get_table_vcp_value( Display_Handle * dh, Byte feature_code, Buffer** table_bytes_loc); Error_Info * ddc_get_nontable_vcp_value( Display_Handle * dh, Byte feature_code, Parsed_Nontable_Vcp_Response** parsed_response_loc); Error_Info * ddc_get_vcp_value( Display_Handle * dh, Byte feature_code, DDCA_Vcp_Value_Type call_type, DDCA_Any_Vcp_Value ** valrec_loc); void init_ddc_vcp(); #endif /* DDC_VCP_H_ */ ddcutil-2.2.0/src/ddc/ddc_vcp_version.h0000644000175000001440000000144214754576332013502 /** @file ddc_vcp_version.h * * Functions to obtain the VCP (MCCS) version for a display. * These functions are in a separate source file to simplify * the acyclic graph of #includes within the ddc source directory. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDC_VCP_VERSION_H_ #define DDC_VCP_VERSION_H_ #include "base/displays.h" #include "base/vcp_version.h" DDCA_MCCS_Version_Spec get_overriding_vcp_version(Display_Ref * dref); DDCA_MCCS_Version_Spec set_vcp_version_xdf_by_dh(Display_Handle * dh); DDCA_MCCS_Version_Spec get_vcp_version_by_dh( Display_Handle * dh); DDCA_MCCS_Version_Spec get_vcp_version_by_dref( Display_Ref * dref); void init_ddc_vcp_version(); #endif /* DDC_VCP_VERSION_H_ */ ddcutil-2.2.0/src/dw/0000775000175000001440000000000014754576332010123 5ddcutil-2.2.0/src/dw/Makefile.am0000644000175000001440000000214114754153540012063 # src/dw/Makefile.am AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) \ $(JANSSON_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libdw.la libdw_la_SOURCES = \ dw_status_events.c if ENABLE_UDEV_COND libdw_la_SOURCES += \ dw_common.c \ dw_main.c \ dw_poll.c \ dw_dref.c \ dw_udev.c \ dw_recheck.c \ dw_services.c \ dw_xevent.c endif # Rename to "all=local" for development all-local-disabled: @echo "" @echo "(src/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" ddcutil-2.2.0/src/dw/Makefile.in0000664000175000001440000005505414754576155012124 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # src/dw/Makefile.am VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @ENABLE_UDEV_COND_TRUE@am__append_1 = \ @ENABLE_UDEV_COND_TRUE@ dw_common.c \ @ENABLE_UDEV_COND_TRUE@ dw_main.c \ @ENABLE_UDEV_COND_TRUE@ dw_poll.c \ @ENABLE_UDEV_COND_TRUE@ dw_dref.c \ @ENABLE_UDEV_COND_TRUE@ dw_udev.c \ @ENABLE_UDEV_COND_TRUE@ dw_recheck.c \ @ENABLE_UDEV_COND_TRUE@ dw_services.c \ @ENABLE_UDEV_COND_TRUE@ dw_xevent.c subdir = src/dw ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libdw_la_LIBADD = am__libdw_la_SOURCES_DIST = dw_status_events.c dw_common.c dw_main.c \ dw_poll.c dw_dref.c dw_udev.c dw_recheck.c dw_services.c \ dw_xevent.c @ENABLE_UDEV_COND_TRUE@am__objects_1 = dw_common.lo dw_main.lo \ @ENABLE_UDEV_COND_TRUE@ dw_poll.lo dw_dref.lo dw_udev.lo \ @ENABLE_UDEV_COND_TRUE@ dw_recheck.lo dw_services.lo \ @ENABLE_UDEV_COND_TRUE@ dw_xevent.lo am_libdw_la_OBJECTS = dw_status_events.lo $(am__objects_1) libdw_la_OBJECTS = $(am_libdw_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/dw_common.Plo \ ./$(DEPDIR)/dw_dref.Plo ./$(DEPDIR)/dw_main.Plo \ ./$(DEPDIR)/dw_poll.Plo ./$(DEPDIR)/dw_recheck.Plo \ ./$(DEPDIR)/dw_services.Plo ./$(DEPDIR)/dw_status_events.Plo \ ./$(DEPDIR)/dw_udev.Plo ./$(DEPDIR)/dw_xevent.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libdw_la_SOURCES) DIST_SOURCES = $(am__libdw_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) \ $(JANSSON_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libdw.la libdw_la_SOURCES = dw_status_events.c $(am__append_1) all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/dw/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/dw/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libdw.la: $(libdw_la_OBJECTS) $(libdw_la_DEPENDENCIES) $(EXTRA_libdw_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libdw_la_OBJECTS) $(libdw_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_common.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_dref.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_main.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_poll.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_recheck.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_status_events.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_udev.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dw_xevent.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/dw_common.Plo -rm -f ./$(DEPDIR)/dw_dref.Plo -rm -f ./$(DEPDIR)/dw_main.Plo -rm -f ./$(DEPDIR)/dw_poll.Plo -rm -f ./$(DEPDIR)/dw_recheck.Plo -rm -f ./$(DEPDIR)/dw_services.Plo -rm -f ./$(DEPDIR)/dw_status_events.Plo -rm -f ./$(DEPDIR)/dw_udev.Plo -rm -f ./$(DEPDIR)/dw_xevent.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/dw_common.Plo -rm -f ./$(DEPDIR)/dw_dref.Plo -rm -f ./$(DEPDIR)/dw_main.Plo -rm -f ./$(DEPDIR)/dw_poll.Plo -rm -f ./$(DEPDIR)/dw_recheck.Plo -rm -f ./$(DEPDIR)/dw_services.Plo -rm -f ./$(DEPDIR)/dw_status_events.Plo -rm -f ./$(DEPDIR)/dw_udev.Plo -rm -f ./$(DEPDIR)/dw_xevent.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Rename to "all=local" for development all-local-disabled: @echo "" @echo "(src/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " ddcutil_FLAGS: $(ddcutil_CFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/dw/dw_status_events.c0000644000175000001440000004013714754576107013613 /** @file dw_status_events.c */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include "public/ddcutil_types.h" #include "public/ddcutil_c_api.h" #include "public/ddcutil_status_codes.h" #include "config.h" #include "util/debug_util.h" #include "util/timestamp.h" #include "util/traced_function_stack.h" #include "base/core.h" #include "base/sleep.h" #include "base/rtti.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "ddc/ddc_display_ref_reports.h" #include "dw_common.h" #include "dw_status_events.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; /** Use a static_assert() to ensure that the allocated size of * DDCA_Display_Status_Event is unchanged from that in a prior * release. */ void assert_ddca_display_status_event_size_unchanged() { typedef struct { uint64_t timestamp_nanos; DDCA_Display_Event_Type event_type; DDCA_IO_Path io_path; char connector_name[32]; DDCA_Display_Ref dref; void * unused[2]; } DDCA_Display_Status_Event_2_1_4; static_assert(sizeof(DDCA_Display_Status_Event) == sizeof(DDCA_Display_Status_Event_2_1_4), "ABI compatibility"); } // // Thread that performs callbacks // GAsyncQueue * callback_queue = NULL; GMutex * callback_queue_mutex = NULL; #ifdef USE_CALLBACK_QUEUE void dw_free_callback_queue_entry(Callback_Queue_Entry * entry) { // free_display_status_event(entry->event); // ??? free(entry); } GAsyncQueue * init_callback_queue() { callback_queue = g_async_queue_new(); return callback_queue; } void dw_put_callback_queue(DDCA_Display_Status_Callback_Func func, DDCA_Display_Status_Event event) { bool debug = true; DBGTRC_STARTING(debug, DDCA_TRC_CONN, "event=%s, func=%p", display_status_event_repr_t(event), func); Callback_Queue_Entry * entry = calloc(1, sizeof(Callback_Queue_Entry)); entry->func = func; entry->event = event; // or make copy? g_async_queue_push(callback_queue, entry); DBGTRC_DONE(debug, DDCA_TRC_CONN, ""); } Callback_Queue_Entry * next_callback_queue_entry() { bool debug = true; DBGTRC_STARTING(debug, DDCA_TRC_CONN, ""); int sleep_interval_millis = 200; // temp int pop_interval_millis = 100; uint64_t pop_interval_micros = MILLIS2MICROS(pop_interval_millis); Callback_Queue_Entry* cqe = NULL; while (!cqe && !terminate_watch_thread) { cqe = g_async_queue_timeout_pop(callback_queue, pop_interval_micros); sleep_millis(sleep_interval_millis); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", cqe); return cqe; } /** Function that runs in a thread to invoke user callback functions * * @param data Callback_Displays_Data struct * @return ?? */ gpointer dw_callback_displays_func(gpointer data) { bool debug = true; traced_function_stack_enabled = false; DBGTRC_STARTING(debug, TRACE_GROUP, "data=%p", data); Callback_Displays_Data* cdd = (Callback_Displays_Data *) data; init_callback_queue(); while (true) { Callback_Queue_Entry * entry = next_callback_queue_entry(); if (!entry) break; DBGTRC_DONE(debug, TRACE_GROUP, "Invoking callback for event %s", display_status_event_repr_t(entry->event)); entry->func(entry->event); DBGTRC_DONE(debug, TRACE_GROUP, "Callback function for event %s complete", display_status_event_repr_t(entry->event)); } //clean up queue dw_free_callback_displays_data(cdd); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "terminating callback thread execution"); // g_thread_exit(NULL); // not needed return NULL; // avoid compiler warning } #endif STATIC void free_callback_queue_entry(Callback_Queue_Entry* q) { free(q); } /** Function that runs in a thread to invoke a single user callback functions * * @param data Callback_Displays_Data struct * @return ?? */ gpointer dw_execute_callback_func(gpointer data) { bool debug = false; traced_function_stack_suspended = true; DBGTRC_STARTING(debug, TRACE_GROUP, "data=%p", data); Callback_Queue_Entry * cqe = (Callback_Queue_Entry *) data; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Invoking callback for event %s in this thread", display_status_event_repr_t(cqe->event)); cqe->func(cqe->event); DBGTRC_DONE(debug, TRACE_GROUP, "Callback function for event %s complete", display_status_event_repr_t(cqe->event)); free_callback_queue_entry(cqe); traced_function_stack_suspended = false; free_current_traced_function_stack(); return NULL; // terminates thread } // // Display Status Events // GPtrArray* display_detection_callbacks = NULL; /** Registers a display status change event callback * * @param func function to register * @retval DDCRC_OK * @retval DDCRC_INVALID_OPERATION ddcutil not built with UDEV support, * or not all video devices support DRM * * The function must be of type DDDCA_Display_Detection_Callback_Func. * It is not an error if the function is already registered. */ DDCA_Status dw_register_display_status_callback(DDCA_Display_Status_Callback_Func func) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "func=%p", func); DDCA_Status result = DDCRC_INVALID_OPERATION; #ifdef ENABLE_UDEV // if (check_all_video_adapters_implement_drm()) { // unnecessary, performed in caller // uint64_t t0 = cur_realtime_nanosec(); generic_register_callback(&display_detection_callbacks, func); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "generic_register_callback() took %"PRIu64" micoseconds", // NANOS2MICROS(cur_realtime_nanosec()-t0) ); result = DDCRC_OK; // } #endif DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } /** Unregisters a detection event callback function * * @param function of type DDCA_Display_Detection_Callback_func * @retval DDCRC_OK normal return * @retval DDCRC_NOT_FOUND function not in list of registered functions * @retval DDCRC_INVALID_OPERATION ddcutil not built with UDEV support, * or not all video devices support DRM */ DDCA_Status dw_unregister_display_status_callback(DDCA_Display_Status_Callback_Func func) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "func=%p", func); DDCA_Status result = DDCRC_INVALID_OPERATION; #ifdef ENABLE_UDEV if (check_all_video_adapters_implement_drm()) { result = generic_unregister_callback(display_detection_callbacks, func); } #endif DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } const char * dw_display_event_class_name(DDCA_Display_Event_Class class) { char * result = NULL; switch(class) { case DDCA_EVENT_CLASS_NONE: result = "DDCA_EVENT_CLASS_NONE"; break; case DDCA_EVENT_CLASS_DPMS: result = "DDCA_EVENT_CLASS_DPMS"; break; case DDCA_EVENT_CLASS_DISPLAY_CONNECTION: result = "DDCA_EVENT_CLASS_DISPLAY_CONNECTION"; break; case DDCA_EVENT_CLASS_UNUSED1: result = "DDCA_EVENT_CLASS_UNUSED1"; break; } return result; } const char * dw_display_event_type_name(DDCA_Display_Event_Type event_type) { char * result = NULL; switch(event_type) { case DDCA_EVENT_DISPLAY_CONNECTED: result = "DDCA_EVENT_DISPLAY_CONNECTED"; break; case DDCA_EVENT_DISPLAY_DISCONNECTED: result = "DDCA_EVENT_DISPLAY_DISCONNECTED"; break; case DDCA_EVENT_DPMS_AWAKE: result = "DDCA_EVENT_DPMS_AWAKE"; break; case DDCA_EVENT_DPMS_ASLEEP: result = "DDCA_EVENT_DPMS_ASLEEP"; break; case DDCA_EVENT_DDC_ENABLED: result = "DDCA_EVENT_DDC_ENABLED"; break; case DDCA_EVENT_UNUSED2: result = "DDCA_EVENT_UNUSED2"; break; } return result; } char * display_status_event_repr(DDCA_Display_Status_Event evt) { char * s = g_strdup_printf( "DDCA_Display_Status_Event[%s: %s, %s, dref: %s, io_path:/dev/i2c-%d, ddc working: %s]", formatted_time_t(evt.timestamp_nanos), // will this clobber a wrapping DBGTRC? dw_display_event_type_name(evt.event_type), evt.connector_name, ddci_dref_repr_t(evt.dref), evt.io_path.path.i2c_busno, sbool(evt.flags&DDCA_DISPLAY_EVENT_DDC_WORKING)); return s; } char * display_status_event_repr_t(DDCA_Display_Status_Event evt) { static GPrivate display_status_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&display_status_repr_key, 200); char * repr = display_status_event_repr(evt); g_snprintf(buf, 200, "%s", repr); free(repr); return buf; } DDCA_Display_Status_Event dw_create_display_status_event( DDCA_Display_Event_Type event_type, const char * connector_name, Display_Ref* dref, DDCA_IO_Path io_path) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "event_type=%d, connector_name=%s, dref=%p=%s, io_path=%s", event_type, connector_name, dref, dref_reprx_t(dref), dpath_short_name_t(&io_path) ); assert(dref); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "dref->flags = %s", interpret_dref_flags_t(dref->flags)); DDCA_Display_Status_Event evt; memset(&evt, 0, sizeof(evt)); DBGMSF(debug, "sizeof(DDCA_Display_Status_Event) = %d, sizeof(evt) = %d", sizeof(DDCA_Display_Status_Event), sizeof(evt)); evt.timestamp_nanos = elapsed_time_nanosec(); evt.dref = dref_to_ddca_dref(dref); // 0 if dref == NULL evt.event_type = event_type; if (connector_name) g_snprintf(evt.connector_name, sizeof(evt.connector_name), "%s", connector_name); else memset(evt.connector_name,0,sizeof(evt.connector_name)); evt.io_path = (dref) ? dref->io_path : io_path; if (event_type == DDCA_DISPLAY_EVENT_DDC_WORKING) ASSERT_WITH_BACKTRACE(dref->flags&DREF_DDC_COMMUNICATION_WORKING); if ((event_type == DDCA_EVENT_DISPLAY_CONNECTED && (dref->flags&DREF_DDC_COMMUNICATION_WORKING)) || event_type == DDCA_DISPLAY_EVENT_DDC_WORKING) evt.flags |= DDCA_DISPLAY_EVENT_DDC_WORKING; // evt.unused[0] = 0; // evt.unused[1] = 0; DBGTRC_RET_STRING(debug, DDCA_TRC_NONE, display_status_event_repr_t(evt), ""); return evt; } /** Performs the actual work of executing the registered callbacks. * * @param evt */ void dw_emit_display_status_record( DDCA_Display_Status_Event evt) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "evt=%s", display_status_event_repr_t(evt)); SYSLOG2(DDCA_SYSLOG_NOTICE, "Emitting %s", display_status_event_repr_t(evt)); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "evet->dref -> ", dref_reprx_t(evt->dref)); Display_Ref * dref0 = dref_from_published_ddca_dref(evt.dref); // DBGMSG("dref0=%p", dref0); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "event->dref -> %s", dref_reprx_t(dref0)); // debug_current_traced_function_stack(false); // show_backtrace(0); // dbgrpt_display_ref(dref0, true, 2); #ifdef OLD if (display_detection_callbacks) { traced_function_stack_suspended = true; for (int ndx = 0; ndx < display_detection_callbacks->len; ndx++) { DDCA_Display_Status_Callback_Func func = g_ptr_array_index(display_detection_callbacks, ndx); func(evt); } traced_function_stack_suspended = false; } #endif #ifdef NEWER int callback_ct = (display_detection_callbacks) ? display_detection_callbacks->len : 0; if (display_detection_callbacks) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Putting %d event notifications on display_detection_callbacks queue", callback_ct); for (int ndx = 0; ndx < callback_ct; ndx++) { DDCA_Display_Status_Callback_Func func = g_ptr_array_index(display_detection_callbacks, ndx); dw_put_callback_queue(func, evt); } } SYSLOG2(DDCA_SYSLOG_NOTICE, "Put %d event notification callbacks on display detection callbacks queue.", callback_ct); DBGTRC_DONE(debug, TRACE_GROUP, "Put %d event notification callbacks on display detection callbacks queue", callback_ct); } #endif int callback_ct = (display_detection_callbacks) ? display_detection_callbacks->len : 0; if (callback_ct > 0) { for (int ndx = 0; ndx < callback_ct; ndx++) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling g_thread_new()..."); Callback_Queue_Entry * cqe = calloc(1, sizeof (Callback_Queue_Entry)); cqe->event = evt; cqe->func = g_ptr_array_index(display_detection_callbacks, ndx); // traced_function_stack_suspended = true; GThread * callback_thread = g_thread_new( "single_callback_worker", // optional thread name dw_execute_callback_func, cqe); // traced_function_stack_suspended = false; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Started callback_thread = %p", callback_thread); SYSLOG2(DDCA_SYSLOG_NOTICE, "libddcutil callback thread %p started", callback_thread); } } SYSLOG2(DDCA_SYSLOG_NOTICE, "Started %d event callback thread(s)", callback_ct); DBGTRC_DONE(debug, TRACE_GROUP, "Started %d event callback thread(s)", callback_ct); } GMutex emit_or_queue_mutex; /** Assembles a #DDCA_Display_Status_Event record and either calls * #ddc_emit_display_status_record to emit it immediately or adds it * to a queue of event records * * @param event_type e.g. DDCA_EVENT_CONNECTED, DDCA_EVENT_AWAKE * @param connector_name * @param dref display reference, NULL if DDCA_EVENT_BUS_ATTACHED * or DDCA_EVENT_BUS_DETACHED * @param io_path for DDCA_EVENT_BUS_ATTACHED or DDCA_EVENT_BUS_DETACHED * @param queue if non-null, append status event record */ void dw_emit_or_queue_display_status_event( DDCA_Display_Event_Type event_type, const char * connector_name, Display_Ref* dref, DDCA_IO_Path io_path, GArray* queue) { bool debug = false; if (dref) { DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%p->%s, dispno=%d, DREF_REMOVED=%s, event_type=%d=%s, connector_name=%s", dref, dref_reprx_t(dref), dref->dispno, SBOOL(dref->flags&DREF_REMOVED), event_type, dw_display_event_type_name(event_type), connector_name); #ifdef NEW DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%p->%s, event_type=%d=%s", dref, dref_reprx_t(dref), event_type, dw_display_event_type_name(event_type)); #endif } else { DBGTRC_STARTING(debug, TRACE_GROUP, "connector_name=%s, io_path=%s, event_type=%d=%s", connector_name, dpath_repr_t(&io_path), event_type, dw_display_event_type_name(event_type)); } // debug_current_traced_function_stack(false); // ** TEMP **/ DDCA_Display_Status_Event evt = dw_create_display_status_event( event_type, connector_name, dref, io_path); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "event: %s", display_status_event_repr_t(evt)); // SYSLOG2(DDCA_SYSLOG_NOTICE, "event: %s", display_status_event_repr(evt)); g_mutex_lock(&emit_or_queue_mutex); // or &emit_queue_mutex ??? if (queue) g_array_append_val(queue,evt); // TODO also need to lock where queue flushed else dw_emit_display_status_record(evt); g_mutex_unlock(&emit_or_queue_mutex); DBGTRC_DONE(debug, TRACE_GROUP, ""); // debug_current_traced_function_stack(false); // ** TEMP **/ } void init_dw_status_events() { RTTI_ADD_FUNC(dw_create_display_status_event); RTTI_ADD_FUNC(dw_emit_or_queue_display_status_event); RTTI_ADD_FUNC(dw_emit_display_status_record); RTTI_ADD_FUNC(dw_register_display_status_callback); RTTI_ADD_FUNC(dw_unregister_display_status_callback); RTTI_ADD_FUNC(dw_execute_callback_func); } ddcutil-2.2.0/src/dw/dw_common.c0000644000175000001440000005320314754153540012162 /** @file dw_common.c */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include "public/ddcutil_types.h" /** \cond */ #include #include #include #include #ifdef ENABLE_UDEV #include #endif #include #include #include #include #include #include "util/common_inlines.h" #include "util/coredefs.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/drm_common.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/glib_util.h" #include "util/i2c_util.h" #include "util/linux_util.h" #include "util/msg_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #include "util/traced_function_stack.h" #include "util/udev_util.h" #include "base/core.h" #include "base/displays.h" #include "base/ddc_errno.h" #include "base/drm_connector_state.h" #include "base/i2c_bus_base.h" #include "base/linux_errno.h" #include "base/rtti.h" #include "base/sleep.h" /** \endcond */ #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp.h" #include "dw_status_events.h" #include "dw_dref.h" #include "dw_xevent.h" #include "dw_common.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; uint16_t initial_stabilization_millisec = DEFAULT_INITIAL_STABILIZATION_MILLISEC; uint16_t stabilization_poll_millisec = DEFAULT_STABILIZATION_POLL_MILLISEC; uint16_t udev_watch_loop_millisec = DEFAULT_UDEV_WATCH_LOOP_MILLISEC; uint16_t poll_watch_loop_millisec = DEFAULT_POLL_WATCH_LOOP_MILLISEC; uint16_t xevent_watch_loop_millisec = DEFAULT_XEVENT_WATCH_LOOP_MILLISEC; bool terminate_using_x11_event = false; uint32_t dw_calc_watch_loop_millisec(DDC_Watch_Mode watch_mode) { assert(watch_mode != Watch_Mode_Dynamic); int final_answer = 0; switch (watch_mode) { case Watch_Mode_Udev: final_answer = udev_watch_loop_millisec; break; case Watch_Mode_Xevent: final_answer = xevent_watch_loop_millisec; break; case Watch_Mode_Poll: final_answer = poll_watch_loop_millisec; break; case Watch_Mode_Dynamic: PROGRAM_LOGIC_ERROR("watch_mode == Watch_Mode_Dynamic"); } return final_answer; } /** Performs a sleep in short segments so that it can be responsively terminated * when dw_stop_watch_displays() is called. Each segment is no longer than * 200 milliseconds. * * @param watch_loop_millisec intended total milliseconds to sleep * @return actual total milliseconds */ uint32_t dw_split_sleep(int watch_loop_millisec) { assert(watch_loop_millisec > 0); uint64_t max_sleep_microsec = watch_loop_millisec * (uint64_t)1000; uint64_t sleep_step_microsec = MIN(200, max_sleep_microsec); // .2 sec uint64_t slept = 0; for (; slept < max_sleep_microsec && !terminate_watch_thread; slept += sleep_step_microsec) usleep(sleep_step_microsec); return slept/1000; } void dw_terminate_if_invalid_thread_or_process(pid_t cur_pid, pid_t cur_tid) { // Doesn't work to detect client crash, main thread and process remains for some time. // 11/2020: is this even needed since terminate_watch_thread check added? // #ifdef DOESNT_WORK bool pid_found = is_valid_thread_or_process(cur_pid); if (!pid_found) { DBGMSG("Process %d not found", cur_pid); } bool tid_found = is_valid_thread_or_process(cur_tid); if (!pid_found || !tid_found) { DBGMSG("Thread %d not found", cur_tid); } if (!pid_found || !tid_found) { free_current_traced_function_stack(); g_thread_exit(GINT_TO_POINTER(-1)); } } void dw_free_watch_displays_data(Watch_Displays_Data * wdd) { if (wdd) { assert( memcmp(wdd->marker, WATCH_DISPLAYS_DATA_MARKER, 4) == 0 ); wdd->marker[3] = 'x'; free(wdd->evdata); free(wdd); } } void dw_free_recheck_displays_data(Recheck_Displays_Data * rdd) { if (rdd) { assert( memcmp(rdd->marker, RECHECK_DISPLAYS_DATA_MARKER, 4) == 0 ); rdd->marker[3] = 'x'; free(rdd); } } Callback_Displays_Data * dw_new_callback_displays_data() { Callback_Displays_Data * cdd = calloc(1, sizeof(Callback_Displays_Data)); cdd->main_process_id = PID(); return cdd; } void dw_free_callback_displays_data(Callback_Displays_Data * cdd) { if (cdd) { assert( memcmp(cdd->marker, CALLBACK_DISPLAYS_DATA_MARKER, 4) == 0 ); cdd->marker[3] = 'x'; free(cdd); } } #ifdef UNUSED void ddc_i2c_filter_sleep_events(GArray * events) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "Initial events queue length: %d", events->len); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { for (int ndx = 0; ndx < events->len; ndx++) { DDCA_Display_Status_Event evt = g_array_index(events, DDCA_Display_Status_Event, ndx); DBGMSG("%s", display_status_event_repr_t(evt)); } } assert(events); int initial_ndx = 0; while (initial_ndx < events->len) { DDCA_Display_Status_Event evt = g_array_index(events, DDCA_Display_Status_Event, initial_ndx); if (evt.event_type == DDCA_EVENT_DPMS_ASLEEP) { int asleep_ndx = initial_ndx; int awake_ndx = -1; for (int successor_ndx = initial_ndx+1; successor_ndx < events->len; successor_ndx++) { DDCA_Display_Status_Event evt2 = g_array_index(events, DDCA_Display_Status_Event, successor_ndx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "evt: %s", display_status_event_repr_t(evt)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "evt2: %s", display_status_event_repr_t(evt2)); if (evt2.event_type != DDCA_EVENT_DPMS_ASLEEP && evt2.event_type != DDCA_EVENT_DPMS_AWAKE) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Intervening non-sleep event"); // connection events intervened, can't simplify break; } if (!dpath_eq(evt2.io_path, evt.io_path)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Different bus number"); // for a different bus, ignore continue; } if (evt.event_type == DDCA_EVENT_DPMS_ASLEEP) { // multiple successive awake events, need to figure out logic // ignore for now DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Multiple DDCA_EVENT_DPMS_ASLEEP events"); break; } awake_ndx = successor_ndx; break; } if (awake_ndx > 0) { // impossible for it to be the first DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Removing events %d, %d", asleep_ndx, awake_ndx); DDCA_Display_Status_Event evt_asleep = g_array_index(events, DDCA_Display_Status_Event, asleep_ndx); DDCA_Display_Status_Event evt_awake = g_array_index(events, DDCA_Display_Status_Event, awake_ndx); SYSLOG2(DDCA_SYSLOG_NOTICE, "Filtered out sleep event: %s", display_status_event_repr_t(evt_asleep)); SYSLOG2(DDCA_SYSLOG_NOTICE, "Filtered out sleep event: %s", display_status_event_repr_t(evt_awake)); g_array_remove_index(events, awake_ndx); g_array_remove_index(events, asleep_ndx); initial_ndx = asleep_ndx - 1; } } initial_ndx++; } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Final events queue length: %d", events->len); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { for (int ndx = 0; ndx < events->len; ndx++) { DDCA_Display_Status_Event evt = g_array_index(events, DDCA_Display_Status_Event, ndx); DBGMSG("%s", display_status_event_repr_t(evt)); } } } #endif void dw_emit_deferred_events(GArray * deferred_events) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); #ifdef TEMPORARY_SIMPLIFICATION if (deferred_events->len > 1) { // FUTURE ENHANCMENT, filter out meaningless events // check for cancellation events for (int ndx = 0; ndx < deferred_events->len; ndx++) { DDCA_Display_Status_Event evt = g_array_index(deferred_events, DDCA_Display_Status_Event, ndx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Event %d in queue: %s", ndx, display_status_event_repr_t(evt)); } ddc_i2c_filter_sleep_events(deferred_events); } #endif DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Emitting %d deferred events", deferred_events->len); for (int ndx = 0; ndx < deferred_events->len; ndx++) { DDCA_Display_Status_Event evt = g_array_index(deferred_events, DDCA_Display_Status_Event, ndx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Emitting deferred event %s", display_status_event_repr_t(evt)); dw_emit_display_status_record(evt); } g_array_remove_range(deferred_events,0, deferred_events->len); DBGTRC_DONE(debug, TRACE_GROUP, ""); } #ifdef WATCH_ASLEEP /** Compares the set of buses currently asleep with the previous list. * If differences exist, either emit events directly or place them on * the deferred events queue. * * @param bs_active_bueses bit set of all buses having edid * @param bs_sleepy_buses bit set of buses currently asleep * @param events_queue if null, emit events directly * if non-null, put events on the queue * @return updated set of buses currently asleep */ Bit_Set_256 ddc_i2c_check_bus_asleep( Bit_Set_256 bs_active_buses, Bit_Set_256 bs_sleepy_buses, GArray* events_queue) // array of DDCA_Display_Status_Event { bool debug = false; // two lines so bs256_to_descimal_t() calls don't clobber private thread specific buffer DBGTRC_STARTING(debug, DDCA_TRC_NONE, "bs_active_buses: %s", BS256_REPR(bs_active_buses)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_sleepy_buses: %s", BS256_REPR(bs_sleepy_buses)); // #ifdef TEMP // remove from the sleepy_connectors array any connector that is not currently active // so that it will not be marked asleep when it becomes active // i.e. turn off is asleep if connector no longer has a monitor bs_sleepy_buses = bs256_and(bs_sleepy_buses, bs_active_buses); if (bs256_count(bs_sleepy_buses) > 0) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_sleepy_buses after removing inactive buses: %s", BS256_REPR(bs_sleepy_buses)); Bit_Set_256_Iterator iter = bs256_iter_new(bs_active_buses); int busno = bs256_iter_next(iter); while (busno >= 0) { I2C_Bus_Info * businfo = i2c_find_bus_info_in_gptrarray_by_busno(all_i2c_buses, busno); if (!businfo->drm_connector_name) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Unable to find connector for bus /dev/i2c-%d", busno); SEVEREMSG("Unable to find connector for bus /dev/i2c-%d", busno); } else { bool is_dpms_asleep = dpms_check_drm_asleep_by_businfo(businfo); bool last_checked_dpms_asleep = bs256_contains(bs_sleepy_buses, busno); if (is_dpms_asleep != last_checked_dpms_asleep) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno = %d, last_checked_dpms_asleep=%s, is_dpms_asleep=%s", busno, sbool (last_checked_dpms_asleep), sbool(is_dpms_asleep)); Display_Ref * dref = DDC_GET_DREF_BY_BUSNO(busno, /* ignore_invalid */ true); DDCA_IO_Path iopath; iopath.io_mode = DDCA_IO_I2C; iopath.path.i2c_busno = busno; DDCA_Display_Status_Event evt = ddc_create_display_status_event( (is_dpms_asleep) ? DDCA_EVENT_DPMS_ASLEEP : DDCA_EVENT_DPMS_AWAKE, businfo->drm_connector_name, dref, iopath); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Queueing %s", display_status_event_repr_t(evt)); g_array_append_val(events_queue,evt); if (is_dpms_asleep) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding bus %d to sleepy_connectors", busno); bs_sleepy_buses = bs256_insert(bs_sleepy_buses, busno); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Removing bus %d from sleepy_connectors", busno); bs_sleepy_buses = bs256_remove(bs_sleepy_buses, busno); } } } // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bottom of loop 2, active_connectors->len = %d, sleepy_connectors->len=%d", // bs256_count(bs_active_buses), bs256_count(*p_bs_sleepy_buses)); busno = bs256_iter_next(iter); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning: bs_sleepy_buses: %s", BS256_REPR(bs_sleepy_buses)); return bs_sleepy_buses; } #endif /** Updates persistent data structures for bus changes and * either emits change events or queues them for later processing. * * For buses with edid removed, marks the display ref as removed * For buses with edid added, create a new display ref. * * @param bs_buses_w_edid_removed * @param bs_buses_w_edid_added * @param events_queue if non-null, put events on the queue, * otherwise, emit them directly * @return true if an event was emitted or placed on the queue, * false if not */ bool dw_hotplug_change_handler( Bit_Set_256 bs_buses_w_edid_removed, Bit_Set_256 bs_buses_w_edid_added, GArray * events_queue, GPtrArray* drefs_to_recheck) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "bs_buses_w_edid_removed: %s", BS256_REPR(bs_buses_w_edid_removed)); if (IS_DBGTRC(debug, TRACE_GROUP)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "bs_buses_w_edid_added: %s", BS256_REPR(bs_buses_w_edid_added)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "events_queue=%p", events_queue); } // debug_current_traced_function_stack(false); // ** TEMP **/ bool event_emitted = true; if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { // i2c_dbgrpt_buses(false, false, 1); DBGMSG("buses before event processed:"); i2c_dbgrpt_buses_summary(1); DBGMSG("display references before event processed:"); // ddc_dbgrpt_display_refs_summary(true, // include_invalid_displays // false, // report_businfo // 1); // depth ddc_dbgrpt_display_refs_terse(true, 1); rpt_nl(); } Bit_Set_256_Iterator iter = bs256_iter_new(bs_buses_w_edid_removed); while(true) { int busno = bs256_iter_next(iter); if (busno < 0) break; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Removing bus %d", busno); I2C_Bus_Info * businfo = i2c_find_bus_info_by_busno(busno); Display_Ref* dref = dw_remove_display_by_businfo(businfo); if (dref) { dw_emit_or_queue_display_status_event(DDCA_EVENT_DISPLAY_DISCONNECTED, dref->drm_connector, dref, dref->io_path, events_queue); event_emitted = true; } if (i2c_device_exists(busno)) { // i2c_reset_bus_info(businfo); // already done in ddc_remove_display_by_businfo2() } else { // is this possible? DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Device /dev/i2c-%d no longer exists.", busno); i2c_remove_bus_by_busno(busno); } } bs256_iter_free(iter); iter = bs256_iter_new(bs_buses_w_edid_added); while (true) { int busno = bs256_iter_next(iter); if (busno < 0) break; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding display ref for bus: %d", busno); // need to protect ? I2C_Bus_Info * businfo = i2c_get_and_check_bus_info(busno); char buf[100]; g_snprintf(buf, 100, "Adding connected display with bus %d", busno); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE,"%s", buf); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", buf); DDCA_IO_Path path; path.io_mode = DDCA_IO_I2C; path.path.i2c_busno = busno; Display_Ref* dref = dw_add_display_by_businfo(businfo); if (dref && !(dref->flags& DREF_TRANSIENT)) { add_published_dref_id_by_dref(dref); if (!(dref->flags & DREF_DDC_COMMUNICATION_WORKING) && drefs_to_recheck) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding %s to drefs_to_recheck", dref_reprx_t(dref)); g_ptr_array_add(drefs_to_recheck, dref); } dw_emit_or_queue_display_status_event( DDCA_EVENT_DISPLAY_CONNECTED, businfo->drm_connector_name, dref, path, events_queue); event_emitted = true; } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Newly detected display has disappeared!!!"); event_emitted = false; } } bs256_iter_free(iter); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { rpt_nl(); rpt_label(0,"After buses added or removed:"); // i2c_dbgrpt_buses(false, false, 1); i2c_dbgrpt_buses_summary(1); rpt_label(0,"After display refs added or marked disconnected:"); // ddc_dbgrpt_display_refs_summary(true, // include_invalid_displays // false, // report_businfo // 1); // depth ddc_dbgrpt_display_refs_terse(true, 1); } DBGTRC_RET_BOOL(debug, TRACE_GROUP,event_emitted, ""); // debug_current_traced_function_stack(false); // ** TEMP **/ return event_emitted; } #ifdef OLD /** Repeatedly calls i2c_detect_buses0() until the value read equals the prior value. * * @oaram prior initial array of I2C_Bus_Info for connected buses * @param some_displays_disconnected if true, add delay to avoid bogus disconnect/connect sequence * @return stabilized array of Bus_Info for connected buses */ GPtrArray * ddc_i2c_stabilized_buses(GPtrArray* prior, bool some_displays_disconnected) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "prior =%p, some_displays_disconnected=%s", prior, SBOOL(some_displays_disconnected)); Bit_Set_256 bs_prior = buses_bitset_from_businfo_array(prior, /* only_connected */ true); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_prior:", BS256_REPR(bs_prior)); // Special handling for case of apparently disconnected displays. // It has been observed that in some cases (Samsung U32H750) a disconnect is followed a // few seconds later by a connect. Wait a few seconds to avoid triggering events // in this case. if (some_displays_disconnected) { if (initial_stabilization_millisec > 0) { char * s = g_strdup_printf( "Delaying %d milliseconds to avoid a false disconnect/connect sequence...", initial_stabilization_millisec); DBGTRC(debug, TRACE_GROUP, "%s", s); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", s); free(s); usleep(initial_stabilization_millisec * 1000); } } int stablect = 0; bool stable = false; while (!stable) { // DBGMSG("SLEEPING"); usleep(1000*stabilization_poll_millisec); GPtrArray* latest = i2c_detect_buses0(); Bit_Set_256 bs_latest = buses_bitset_from_businfo_array(latest, /* only_connected */ true); if (bs256_eq(bs_latest, bs_prior)) stable = true; i2c_discard_buses0(prior); prior = latest; stablect++; } if (stablect > 1) { DBGTRC(debug || true, TRACE_GROUP, "Required %d extra calls to i2c_get_buses0()", stablect+1); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s required %d extra calls to i2c_get_buses0()", __func__, stablect-1); } DBGTRC_RET_STRING(debug, DDCA_TRC_NONE, BS256_REPR(bs_prior),""); return prior; } #endif Bit_Set_256 dw_stabilized_buses_bs(Bit_Set_256 bs_prior, bool some_displays_disconnected) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "prior =%s, some_displays_disconnected=%s, extra_stabilization_millisec=%d", BS256_REPR(bs_prior), SBOOL(some_displays_disconnected), initial_stabilization_millisec); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_prior:", BS256_REPR(bs_prior)); // Special handling for case of apparently disconnected displays. // It has been observed that in some cases (Samsung U32H750) a disconnect is followed a // few seconds later by a connect. Wait a few seconds to avoid triggering events // in this case. if (some_displays_disconnected) { if (initial_stabilization_millisec > 0) { char * s = g_strdup_printf( "Delaying %d milliseconds to avoid a false disconnect/connect sequence...", initial_stabilization_millisec); DBGTRC(debug, TRACE_GROUP, "%s", s); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", s); free(s); DW_SLEEP_MILLIS(initial_stabilization_millisec, "Initial stabilization delay"); } } int stablect = 0; bool stable = false; while (!stable) { // DW_SLEEP_MILLIS(stabilization_poll_millisec, "Loop until stable"); // TMI sleep_millis(stabilization_poll_millisec); BS256 bs_latest = i2c_buses_w_edid_as_bitset(); if (bs256_eq(bs_latest, bs_prior)) stable = true; bs_prior = bs_latest; stablect++; } if (stablect > 1) { char buf[100]; g_snprintf(buf, 100, "Required %d extra %d millisecond calls to i2c_buses_w_edid_as_bitset()", stablect+1, stabilization_poll_millisec); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s", buf); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", buf); } DBGTRC_RET_STRING(debug, TRACE_GROUP, BS256_REPR(bs_prior),""); return bs_prior; } void init_dw_common() { #ifdef WATCH_ASLEEP RTTI_ADD_FUNC(ddc_i2c_check_bus_asleep); #endif RTTI_ADD_FUNC(dw_stabilized_buses_bs); RTTI_ADD_FUNC(dw_emit_deferred_events); RTTI_ADD_FUNC(dw_hotplug_change_handler); } ddcutil-2.2.0/src/dw/dw_main.c0000644000175000001440000004020214754153540011611 /** @file dw_main.c */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include "public/ddcutil_types.h" #include "public/ddcutil_status_codes.h" #include "util/common_inlines.h" #include "util/coredefs.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #include "base/core.h" #include "base/displays.h" #include "base/ddcutil_types_internal.h" #include "base/dsa2.h" #include "base/drm_connector_state.h" #include "base/i2c_bus_base.h" #include "base/parms.h" #include "base/rtti.h" #include "base/sleep.h" /** \endcond */ #include "sysfs/sysfs_base.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_display_ref_reports.h" #include "dw_status_events.h" #include "dw_common.h" #include "dw_udev.h" #include "dw_recheck.h" #include "dw_poll.h" #include "dw_xevent.h" #include "dw_main.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; DDC_Watch_Mode watch_displays_mode = DEFAULT_WATCH_MODE; bool enable_watch_displays = true; static GThread * watch_thread = NULL; static GThread * recheck_thread = NULL; // static GThread * callback_thread; static GMutex watch_thread_mutex; static DDCA_Display_Event_Class active_watch_displays_classes = DDCA_EVENT_CLASS_NONE; static Watch_Displays_Data * global_wdd; // needed to pass to dw_stop_watch_displays() /** Determines the actual watch mode to be used * * @param initial_mode mode requested * @param xev_data_loc address at which to set the address of a newly allocated * XEvent_Data struct, if the resolved mode is Watch_Mode_Xevent * @return actual watch mode to be used */ STATIC DDC_Watch_Mode resolve_watch_mode(DDC_Watch_Mode initial_mode, XEvent_Data ** xev_data_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "initial_mode=%s xev_data_loc=%p", watch_mode_name(initial_mode), xev_data_loc); DDC_Watch_Mode resolved_watch_mode = Watch_Mode_Poll; XEvent_Data * xevdata = NULL; *xev_data_loc = NULL; #ifndef ENABLE_UDEV if (initial_mode == Watch_Mode_Udev) initial_mode = Watch_Mode_Poll; #endif if (initial_mode == Watch_Mode_Dynamic) { resolved_watch_mode = Watch_Mode_Poll; // always works, may be slow char * xdg_session_type = getenv("XDG_SESSION_TYPE"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "XDG_SESSION_TYPE=|%s|", xdg_session_type); if (xdg_session_type && // can xdg_session_type ever not be set (streq(xdg_session_type, "x11") || streq(xdg_session_type,"wayland"))) { resolved_watch_mode = Watch_Mode_Xevent; } else { // assert xdg_session_type == "tty" ? char * display = getenv("DISPLAY"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "xdg_session_type=|%s|, display=|%s|", xdg_session_type, display); // possibility of coming in on ssh with a x11 proxy running // see https://stackoverflow.com/questions/45536141/how-i-can-find-out-if-a-linux-system-uses-wayland-or-x11 if (display) { resolved_watch_mode = Watch_Mode_Xevent; } } // dw_watch_mode = Watch_Mode_Udev; // sysfs_fully_reliable = is_sysfs_reliable(); // if (!sysfs_fully_reliable) // dw_watch_mode = Watch_Mode_Poll; } else { resolved_watch_mode = initial_mode; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "initially resolved watch mode = %s", watch_mode_name(resolved_watch_mode)); #ifdef NO if (resolved_watch_mode == Watch_Mode_Udev) { if (!sysfs_fully_reliable) // ??? resolved_watch_mode = Watch_Mode_Poll; } #endif if (resolved_watch_mode == Watch_Mode_Xevent) { xevdata = dw_init_xevent_screen_change_notification(); // *xev_data_loc = ddc_init_xevent_screen_change_notification(); if (!xevdata) { resolved_watch_mode = Watch_Mode_Poll; MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "X11 RANDR api unavailable. Switching to Watch_Mode_Poll"); } } // DBG( "xevdata=%p, watch_mode = %s", xevdata, dw_watch_mode_name(resolved_watch_mode)); *xev_data_loc = xevdata; // ASSERT_IFF(resolved_watch_mode == Watch_Mode_Xevent, xevdata); ASSERT_IFF(resolved_watch_mode == Watch_Mode_Xevent, *xev_data_loc); if (*xev_data_loc && IS_DBGTRC(debug, DDCA_TRC_NONE)) { dw_dbgrpt_xevent_data(*xev_data_loc, 0); } DBGTRC_DONE(debug, TRACE_GROUP, "resolved_watch_mode: %s. *xev_data_loc: %p", watch_mode_name(resolved_watch_mode), *xev_data_loc); return resolved_watch_mode; } /** Starts thread that watches for changes in display connection status. * * @param event_classes types of events to watch for * @return Error_Info struct if error, possible status codes: * - DDCRC_INVALID_OPERATION e.g. watch thread already started, watching disabled * - DDCRC_ARG event_classes == DDCA_EVENT_CLASS_NONE */ Error_Info * dw_start_watch_displays(DDCA_Display_Event_Class event_classes) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dw_watch_mode = %s, watch_thread=%p, event_clases=0x%02x, all_video_adapters_implement_drm=%s", watch_mode_name(watch_displays_mode), watch_thread, event_classes, SBOOL(all_video_adapters_implement_drm)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "thread_id = %d, traced_function_stack=%p", TID(), traced_function_stack); Error_Info * err = NULL; XEvent_Data * xev_data = NULL; if (!all_video_adapters_implement_drm) { err = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "Requires DRM video drivers"); goto bye; } if (!enable_watch_displays) { err = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "Watching for display changes disabled"); goto bye; } DDC_Watch_Mode resolved_watch_mode = resolve_watch_mode(watch_displays_mode, &xev_data); ASSERT_IFF(resolved_watch_mode == Watch_Mode_Xevent, xev_data); int calculated_watch_loop_millisec = dw_calc_watch_loop_millisec(resolved_watch_mode); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "calc_watch_loop_millisec() returned %d", calculated_watch_loop_millisec); MSG_W_SYSLOG(DDCA_SYSLOG_NOTICE, "Watching for display connection changes, resolved watch mode = %s, poll loop interval = %d millisec", watch_mode_name(resolved_watch_mode), calculated_watch_loop_millisec); MSG_W_SYSLOG(DDCA_SYSLOG_NOTICE, " extra_stabilization_millisec: %d, stabilization_poll_millisec: %d", initial_stabilization_millisec, stabilization_poll_millisec); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "use_sysfs_connector_id: %s", SBOOL(use_sysfs_connector_id)); // watch udev only g_mutex_lock(&watch_thread_mutex); if (!(event_classes & (DDCA_EVENT_CLASS_DPMS|DDCA_EVENT_CLASS_DISPLAY_CONNECTION))) { err = ERRINFO_NEW(DDCRC_ARG, "Invalid event classes"); } else if (watch_thread) { err = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "Watch thread already running"); } else { terminate_watch_thread = false; // Start recheck thread Recheck_Displays_Data * rdd = calloc(1, sizeof(Recheck_Displays_Data)); memcpy(rdd->marker, RECHECK_DISPLAYS_DATA_MARKER,4); recheck_thread = g_thread_new("display_recheck_thread", // optional thread name dw_recheck_displays_func, rdd); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Started recheck_thread = %p", watch_thread); SYSLOG2(DDCA_SYSLOG_NOTICE, "libddcutil recheck thread %p started", watch_thread); // Start watch thread Watch_Displays_Data * wdd = calloc(1, sizeof(Watch_Displays_Data)); memcpy(wdd->marker, WATCH_DISPLAYS_DATA_MARKER, 4); wdd->main_process_id = pid(); // getpid(); wdd->main_thread_id = tid(); get_thread_id(); // alt = syscall(SYS_gettid); // event_classes &= ~DDCA_EVENT_CLASS_DPMS; // *** TEMP *** wdd->event_classes = event_classes; wdd->watch_mode = resolved_watch_mode; wdd->watch_loop_millisec = calculated_watch_loop_millisec; if (xev_data) wdd->evdata = xev_data; global_wdd = wdd; #ifdef CALLBACK_DISPLAYS_THREAD DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling g_thread_new()..."); Callback_Displays_Data * cdd = dw_new_callback_displays_data(); callback_thread = g_thread_new( "callback_displays_thread", // optional thread name dw_callback_displays_func, cdd); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Started callback_thread = %p", callback_thread); SYSLOG2(DDCA_SYSLOG_NOTICE, "libddcutil callback thread %p started", callback_thread); #endif GThreadFunc watch_thread_func = (resolved_watch_mode == Watch_Mode_Poll || resolved_watch_mode == Watch_Mode_Xevent) ? dw_watch_display_connections : dw_watch_displays_udev; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling g_thread_new()..."); watch_thread = g_thread_new( "watch_displays", // optional thread name watch_thread_func, wdd); active_watch_displays_classes = event_classes; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Started watch_thread = %p", watch_thread); SYSLOG2(DDCA_SYSLOG_NOTICE, "libddcutil watch thread %p started", watch_thread); } g_mutex_unlock(&watch_thread_mutex); bye: DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, "watch_thread=%p", watch_thread); return err; } /** Halts thread that watches for changes in display connection status. * * @param wait if true, does not return until the watch thread exits, * if false, returns immediately * @param enabled_clases_loc location at which to return watch classes that were active * @retval DDCRC_OK * @retval DDCRC_INVALID_OPERATION watch thread not executing */ DDCA_Status dw_stop_watch_displays(bool wait, DDCA_Display_Event_Class* enabled_classes_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "wait=%s, watch_thread=%p", SBOOL(wait), watch_thread ); DDCA_Status ddcrc = DDCRC_OK; #ifdef ENABLE_UDEV if (enabled_classes_loc) *enabled_classes_loc = DDCA_EVENT_CLASS_NONE; g_mutex_lock(&watch_thread_mutex); if (watch_thread) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "resolved_watch_mode = %s", watch_mode_name(global_wdd->watch_mode)); if (global_wdd->watch_mode == Watch_Mode_Xevent) { if (terminate_using_x11_event) { // for testing, does not currently work dw_send_x11_termination_message(global_wdd->evdata); DW_SLEEP_MILLIS(2*1000, "After ddc_send_x11_termination_message()"); } else { terminate_watch_thread = true; } } else { terminate_watch_thread = true; // signal watch thread to terminate } // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Waiting %d millisec for watch thread to terminate...", 4000); // usleep(4000*1000); // greater than the sleep in watch_displays_using_poll() if (wait) { g_thread_join(watch_thread); g_thread_join(recheck_thread); } else { g_thread_unref(watch_thread); g_thread_unref(recheck_thread); } watch_thread = NULL; if (enabled_classes_loc) *enabled_classes_loc = active_watch_displays_classes; SYSLOG2(DDCA_SYSLOG_NOTICE, "Watch thread terminated."); } else { ddcrc = DDCRC_INVALID_OPERATION; } g_mutex_unlock(&watch_thread_mutex); #endif DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, "watch_thread=%p", watch_thread); return ddcrc; } bool dw_is_watch_displays_executing() { return watch_thread; } /** If the watch thread is currently executing, returns the * currently active display event classes as a bit flag. * * @param classes_loc where to return bit flag * @retval DDCRC_OK * @retval DDCRC_INVALID_OPERATION watch thread not executing */ DDCA_Status dw_get_active_watch_classes(DDCA_Display_Event_Class * classes_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "classes_loc = %p", classes_loc); DDCA_Status ddcrc = DDCRC_INVALID_OPERATION; *classes_loc = DDCA_EVENT_CLASS_NONE; g_mutex_lock(&watch_thread_mutex); if (watch_thread) { *classes_loc = active_watch_displays_classes; ddcrc = DDCRC_OK; } g_mutex_unlock(&watch_thread_mutex); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, "*classes_loc=0x%02x", *classes_loc); return ddcrc; } /** Called to completely redetect displays */ void dw_redetect_displays() { bool debug = false || debug_locks; DBGTRC_STARTING(debug, TRACE_GROUP, "all_displays=%p", all_display_refs); SYSLOG2(DDCA_SYSLOG_NOTICE, "Display redetection starting."); DDCA_Display_Event_Class enabled_classes = DDCA_EVENT_CLASS_NONE; DDCA_Status active_rc = dw_get_active_watch_classes(&enabled_classes); if (active_rc == DDCRC_OK) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling ddc_stop_watch_displays()"); DDCA_Status rc = dw_stop_watch_displays(/*wait*/ true, &enabled_classes); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Called ddc_stop_watch_displays()"); assert(rc == DDCRC_OK); } ddc_discard_detected_displays(); if (dsa2_is_enabled()) dsa2_save_persistent_stats(); // free_sysfs_drm_connector_names(); if (use_drm_connector_states) redetect_drm_connector_states(); // init_sysfs_drm_connector_names(); // get_sys_drm_connectors(/*rescan=*/true); if (dsa2_is_enabled()) { Error_Info * erec = dsa2_restore_persistent_stats(); if (erec) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Unexpected error from dsa2_restore_persistent_stats(): %s", errinfo_summary(erec)); free(erec); } } i2c_detect_buses(); g_mutex_lock(&all_display_refs_mutex); all_display_refs = ddc_detect_all_displays(&display_open_errors); g_mutex_unlock(&all_display_refs_mutex); if (debug) { ddc_dbgrpt_drefs("all_displays:", all_display_refs, 1); } if (active_rc == DDCRC_OK) { Error_Info * err = dw_start_watch_displays(enabled_classes); assert(!err); // should never fail since restarting with same enabled classes } SYSLOG2(DDCA_SYSLOG_NOTICE, "Display redetection finished."); DBGTRC_DONE(debug, TRACE_GROUP, "all_displays=%p, all_displays->len = %d", all_display_refs, all_display_refs->len); } void dw_get_display_watch_settings(DDCA_DW_Settings * settings) { assert(settings); // settings->watch_mode = dw_watch_mode; // settings->udev_watch_interval_millisec = udev_watch_loop_millisec; settings->poll_watch_interval_millisec = poll_watch_loop_millisec; settings->xevent_watch_interval_millisec = xevent_watch_loop_millisec; settings->initial_stabilization_millisec = initial_stabilization_millisec; settings->stabilization_poll_millisec = stabilization_poll_millisec; settings->watch_retry_interval_millisec = retry_thread_sleep_factor_millisec; } DDCA_Status dw_set_display_watch_settings(DDCA_DW_Settings * settings) { assert(settings); // udev_watch_loop_millisec = settings->udev_watch_udev_interval_millisec; poll_watch_loop_millisec = settings->poll_watch_interval_millisec; xevent_watch_loop_millisec = settings->xevent_watch_interval_millisec; initial_stabilization_millisec = settings->initial_stabilization_millisec; stabilization_poll_millisec = settings->stabilization_poll_millisec; retry_thread_sleep_factor_millisec = settings->watch_retry_interval_millisec; return DDCRC_OK; } void init_dw_main() { RTTI_ADD_FUNC(dw_start_watch_displays); RTTI_ADD_FUNC(dw_stop_watch_displays); RTTI_ADD_FUNC(dw_get_active_watch_classes); RTTI_ADD_FUNC(resolve_watch_mode); RTTI_ADD_FUNC(dw_redetect_displays); } ddcutil-2.2.0/src/dw/dw_poll.c0000644000175000001440000003544514754153540011650 /** @file dw_poll.c * * Watch for display changes without using UDEV */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include "public/ddcutil_types.h" /** \cond */ #include #include #include #include #ifdef ENABLE_UDEV #include #endif #include #include #include #include #include #include "util/common_inlines.h" #include "util/coredefs.h" #include "util/data_structures.h" #include "util/drm_common.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/glib_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/traced_function_stack.h" #include "util/udev_util.h" #include "base/core.h" #include "base/displays.h" #include "base/ddc_errno.h" #include "base/drm_connector_state.h" #include "base/i2c_bus_base.h" #include "base/linux_errno.h" #include "base/rtti.h" #include "base/sleep.h" /** \endcond */ #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp.h" #include "dw_common.h" #include "dw_dref.h" #include "dw_recheck.h" #include "dw_status_events.h" #include "dw_xevent.h" #include "dw_poll.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; int nonudev_poll_loop_millisec = DEFAULT_UDEV_WATCH_LOOP_MILLISEC; // 2000; int retry_thread_sleep_factor_millisec = WATCH_RETRY_THREAD_SLEEP_FACTOR_MILLISEC; bool stabilize_added_buses_w_edid; // if set, stabilize when displays added as well as removed bool recheck_thread_active = false; GMutex process_event_mutex; STATIC void process_screen_change_event( BS256* p_bs_attached_buses, BS256* p_bs_buses_w_edid, GArray * deferred_events, GPtrArray * displays_to_recheck ) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_CONN, "*p_bs_old_attached_buses -> %s", bs256_to_string_decimal_t(*p_bs_attached_buses, "", ",")); DBGTRC_NOPREFIX(debug, DDCA_TRC_CONN, "*p_bs_buses_w_edid -> %s", bs256_to_string_decimal_t(*p_bs_buses_w_edid, "", ",")) ; BS256 bs_old_attached_buses = *p_bs_attached_buses; BS256 bs_old_buses_w_edid = *p_bs_buses_w_edid; Bit_Set_256 bs_new_attached_buses = i2c_detect_attached_buses_as_bitset(); Bit_Set_256 bs_new_buses_w_edid = i2c_filter_buses_w_edid_as_bitset(bs_new_attached_buses); Bit_Set_256 bs_added_buses_w_edid = bs256_and_not(bs_new_buses_w_edid, bs_old_buses_w_edid); Bit_Set_256 bs_removed_buses_w_edid = bs256_and_not(bs_old_buses_w_edid, bs_new_buses_w_edid); Bit_Set_256 bs_added_attached_buses = bs256_and_not(bs_new_attached_buses, bs_old_attached_buses); Bit_Set_256 bs_removed_attached_buses = bs256_and_not(bs_old_attached_buses, bs_new_attached_buses); #ifdef TMI DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_old_buses_w_edid(0): %s", bs256_to_string_decimal_t(bs_old_buses_w_edid, "", ",")); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_new_buses_edid(0): %s", bs256_to_string_decimal_t(bs_new_buses_w_edid, "", ",")); #endif if ( bs256_count(bs_removed_buses_w_edid) > 0 || (stabilize_added_buses_w_edid && bs256_count(bs_added_buses_w_edid) > 0)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_old_attached_buses: %s", BS256_REPR(bs_old_attached_buses)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_new_attached_buses: %s", BS256_REPR(bs_new_attached_buses)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_old_buses_w_edid: %s", BS256_REPR(bs_old_buses_w_edid)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_new_buses_edid: %s", BS256_REPR(bs_new_buses_w_edid)); bs_new_buses_w_edid = dw_stabilized_buses_bs(bs_new_buses_w_edid, bs256_count(bs_removed_buses_w_edid)); BS256 bs_added_buses_w_edid = bs256_and_not(bs_new_buses_w_edid, bs_old_buses_w_edid); bs_removed_buses_w_edid = bs256_and_not(bs_old_buses_w_edid, bs_new_buses_w_edid); bs_added_attached_buses = bs256_and_not(bs_new_attached_buses, bs_old_attached_buses); bs_removed_attached_buses = bs256_and_not(bs_old_attached_buses, bs_new_attached_buses); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "After stabilization:"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_old_attached_buses: %s", BS256_REPR(bs_old_attached_buses)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_new_attached_buses: %s", BS256_REPR(bs_new_attached_buses)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_old_buses_w_edid: %s", BS256_REPR(bs_old_buses_w_edid)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_new_buses_edid: %s", BS256_REPR(bs_new_buses_w_edid)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_added_attached_buses: %s", BS256_REPR(bs_added_attached_buses)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_removed_attached_buses: %s", BS256_REPR(bs_removed_attached_buses)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_added_buses_w_edid: %s", BS256_REPR(bs_added_buses_w_edid)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_removed_buses_w_edid: %s", BS256_REPR(bs_removed_buses_w_edid)); } bs_old_buses_w_edid = bs_new_buses_w_edid; bs_old_attached_buses = bs_new_attached_buses; bool hotplug_change_handler_emitted = false; bool connected_buses_w_edid_changed = bs256_count(bs_removed_buses_w_edid) > 0 || bs256_count(bs_added_buses_w_edid) > 0; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "connected_buses_changed = %s", SBOOL(connected_buses_w_edid_changed)); if (connected_buses_w_edid_changed) { hotplug_change_handler_emitted = dw_hotplug_change_handler( bs_removed_buses_w_edid, bs_added_buses_w_edid, deferred_events, displays_to_recheck); } if (hotplug_change_handler_emitted) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "hotplug_change_handler_emitted = %s", sbool (hotplug_change_handler_emitted)); #ifdef WATCH_ASLEEP if (watch_dpms) { // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Before ddc_check_bus_asleep(), bs_sleepy_buses: %s", // BS256_REPR(bs_sleepy_buses)); // emits dpms events directly or places them on deferred_events queue bs_sleepy_buses = ddc_i2c_check_bus_asleep( bs_old_buses_w_edid, bs_sleepy_buses, deferred_events); // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "After ddc_check_bus_asleep(), bs_sleepy_buses: %s", // BS256_REPR(bs_sleepy_buses)); } #endif #ifdef ALT if (watch_dpms) { for (int ndx = 0; ndx < all_i2c_buses->len; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(all_i2c_buses, ndx); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ndx=%d, businfo=%p", ndx, businfo); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bus=%d", businfo->busno); if (businfo->flags & I2C_BUS_ADDR_0X50) { // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bus=%d, I2C_BUS_ADDR_0X50 set", businfo->busno); bool is_dpms_asleep = dpms_check_drm_asleep_by_businfo(businfo); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, is_dpms_asleep=%s, last_checked_dpms_asleep=%s", businfo->busno, sbool(is_dpms_asleep), sbool(businfo->last_checked_dpms_asleep)); if (is_dpms_asleep != businfo->last_checked_dpms_asleep) { Display_Ref * dref = ddc_get_dref_by_busno_or_connector(businfo->busno, NULL, /*ignore_invalid*/ true); assert(dref); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "sleep change event for dref=%p->%s", dref, dref_repr_t(dref)); DDCA_Display_Event_Type event_type = (is_dpms_asleep) ? DDCA_EVENT_DPMS_ASLEEP : DDCA_EVENT_DPMS_AWAKE; dw_emit_or_queue_display_status_event(event_type, dref->drm_connector, dref, dref->io_path, NULL); businfo->last_checked_dpms_asleep = is_dpms_asleep; } } } } #endif *p_bs_attached_buses = bs_old_attached_buses; *p_bs_buses_w_edid = bs_old_buses_w_edid;; DBGTRC_DONE(debug, DDCA_TRC_CONN, "*p_bs_old_attached_buses -> %s", bs256_to_string_decimal_t(*p_bs_attached_buses, "", ",")); DBGTRC_NOPREFIX(debug, DDCA_TRC_CONN, "*p_bs_buses_w_edid -> %s", bs256_to_string_decimal_t(*p_bs_buses_w_edid, "", ",")); } /** Function that executes in the display watch thread. * * @param data pointer to a #Watch_Display_Data struct */ gpointer dw_watch_display_connections(gpointer data) { bool debug = false; bool use_deferred_event_queue = false; Watch_Displays_Data * wdd = data; assert(wdd && memcmp(wdd->marker, WATCH_DISPLAYS_DATA_MARKER, 4) == 0); assert(wdd->watch_mode == Watch_Mode_Xevent || wdd->watch_mode == Watch_Mode_Poll); if (wdd->watch_mode == Watch_Mode_Xevent) assert(wdd->evdata); GPtrArray * displays_to_recheck = g_ptr_array_new(); DBGTRC_STARTING(debug, TRACE_GROUP, "Caller process id: %d, caller thread id: %d, our thread id: %d, event_classes=0x%02x, terminate_using_x11_event=%s", wdd->main_process_id, wdd->main_thread_id, tid(), wdd->event_classes, sbool(terminate_using_x11_event)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Watching for display connection events: %s", sbool(wdd->event_classes & DDCA_EVENT_CLASS_DISPLAY_CONNECTION)); #ifdef WATCH_DPMS DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Watching for dpms events: %s", sbool(wdd->event_classes & DDCA_EVENT_CLASS_DPMS)); #endif // may need to wait on startup while (!all_i2c_buses) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Waiting 1 sec for all_i2c_buses"); SYSLOG2(DDCA_SYSLOG_NOTICE, "Waiting 1 sec for all_i2c_buses"); sleep_millis(500); } pid_t cur_pid = getpid(); pid_t cur_tid = get_thread_id(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Our process id: %d, our thread id: %d", cur_pid, cur_tid); #ifdef WATCH_DPMS bool watch_dpms = wdd->event_classes & DDCA_EVENT_CLASS_DPMS; BS256 bs_sleepy_buses = EMPTY_BIT_SET_256; #endif BS256 bs_old_attached_buses = buses_bitset_from_businfo_array(all_i2c_buses, false); BS256 bs_old_buses_w_edid = buses_bitset_from_businfo_array(all_i2c_buses, true); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Initial i2c buses with edids: %s", BS256_REPR(bs_old_buses_w_edid)); if (IS_DBGTRC(debug, DDCA_TRC_NONE) && false) { rpt_vstring(0, "Initial I2C buses:"); i2c_dbgrpt_buses_summary(1); rpt_vstring(0, "Initial Display Refs:"); ddc_dbgrpt_display_refs_summary(true, // include_invalid_displays false, // report_businfo 1); // depth if (use_drm_connector_states) { rpt_vstring(0, "Initial DRM connector states"); report_drm_connector_states_basic(/*refresh*/ true, 1); } } GArray * deferred_events = NULL; if (use_deferred_event_queue) { deferred_events = g_array_new(false, // zero_terminated false, // clear sizeof(DDCA_Display_Status_Event)); } bool skip_next_sleep = false; int slept = 0; // will contain length of final sleep while (!terminate_watch_thread) { if (deferred_events && deferred_events->len > 0) { dw_emit_deferred_events(deferred_events); } else { // skip polling loop sleep if deferred events were output if (!skip_next_sleep && wdd->watch_mode == Watch_Mode_Poll) { slept = dw_split_sleep(wdd->watch_loop_millisec); } } skip_next_sleep = false; if (terminate_watch_thread) continue; dw_terminate_if_invalid_thread_or_process(cur_pid, cur_tid); if (wdd->watch_mode == Watch_Mode_Xevent) { if (terminate_using_x11_event) { bool event_found = dw_next_X11_event_of_interest(wdd->evdata); // either display changed or terminate signaled DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "event_found=%s", sbool(event_found)); if (!event_found) { terminate_watch_thread = true; continue; } } else { bool event_found = dw_detect_xevent_screen_change(wdd->evdata, wdd->watch_loop_millisec); if (event_found) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Screen change event occurred"); else continue; } } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "locking process_event_mutex"); g_mutex_lock(&process_event_mutex); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Processing screen change event"); process_screen_change_event(&bs_old_attached_buses, &bs_old_buses_w_edid, deferred_events, displays_to_recheck); if (displays_to_recheck->len > 0) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "handling displays_to_recheck"); int len = displays_to_recheck->len; for (int ndx = len-1; ndx >= 0; ndx--) { dw_put_recheck_queue(g_ptr_array_index(displays_to_recheck, ndx)); g_ptr_array_remove_index(displays_to_recheck, ndx); } #ifdef OLD Recheck_Displays_Data * rdd = calloc(1, sizeof(Recheck_Displays_Data)); rdd->displays_to_recheck = displays_to_recheck; rdd->deferred_event_queue = deferred_events; g_thread_new("display_recheck_thread", // optional thread name ddc_recheck_displays_func, rdd); displays_to_recheck = g_ptr_array_new(); #endif } g_mutex_unlock(&process_event_mutex); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "unlocked process_event_mutex"); } // while() // n. slept == 0 if no sleep was performed DBGTRC_DONE(debug, TRACE_GROUP, "Terminating thread. Final polling sleep was %d millisec.", slept/1000); g_ptr_array_free(displays_to_recheck, true); dw_free_watch_displays_data(wdd); if (deferred_events) g_array_free(deferred_events, true); #ifdef WATCH_DPMS if (watch_dpms) g_ptr_array_free(sleepy_connectors, true); #endif free_current_traced_function_stack(); g_thread_exit(0); assert(false); // avoid clang warning re wdd use after free return NULL; // satisfy compiler check that value returned } void init_dw_poll() { RTTI_ADD_FUNC(dw_watch_display_connections); RTTI_ADD_FUNC(process_screen_change_event); } ddcutil-2.2.0/src/dw/dw_dref.c0000644000175000001440000001701314754153540011611 /** @file dw_dref.c * Functions that modify persistent Display_Ref related data structures * when display connection and disconnection are detected. */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include "config.h" #include "util/backtrace.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/edid.h" #include "util/error_info.h" #include "util/report_util.h" #include "util/string_util.h" /** \endcond */ #include "public/ddcutil_types.h" #include "base/core.h" #include "base/displays.h" #include "base/i2c_bus_base.h" #include "base/monitor_model_key.h" #include "base/parms.h" #include "base/rtti.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_initial_checks.h" #include "dw_dref.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; /** Adds a Display_Ref to the array of all Display_Refs * in a thread safe manner. * * @param dref pointer to Display_Ref to add. */ void dw_add_display_ref(Display_Ref * dref) { bool debug = false ; debug = debug || debug_locks; DBGTRC_STARTING(debug, DDCA_TRC_CONN, "dref=%s", dref_repr_t(dref)); g_mutex_lock(&all_display_refs_mutex); g_ptr_array_add(all_display_refs, dref); g_mutex_unlock(&all_display_refs_mutex); DBGTRC_DONE(debug, DDCA_TRC_CONN, "dref=%s", dref_repr_t(dref)); } /** Marks a Display_Ref as removed, in a thread safe manner. * * @param dref pointer to Display_Ref to mark removed. */ void dw_mark_display_ref_removed(Display_Ref* dref) { bool debug = false; debug = debug || debug_locks; DBGTRC_STARTING(debug, DDCA_TRC_CONN, "dref=%s", dref_repr_t(dref)); g_mutex_lock(&all_display_refs_mutex); if (IS_DBGTRC(debug, debug)) { show_backtrace(2); backtrace_to_syslog(LOG_NOTICE, 0); } dref->flags |= DREF_REMOVED; g_mutex_unlock(&all_display_refs_mutex); DBGTRC_DONE(debug, DDCA_TRC_CONN, "dref=%s", dref_repr_t(dref)); } /** If a display is present on a specified bus, adds a Display_Ref * for that display. * * @param businfo I2C_Bus_Info record for the bus * @return true Display_Ref added, false if not. * * @remark * Called only when ddc_watch_displays_common.c handling display change */ Display_Ref * dw_add_display_by_businfo(I2C_Bus_Info * businfo) { bool debug = false; assert(businfo); DBGTRC_STARTING(debug, DDCA_TRC_CONN, "businfo=%p, busno=%d", businfo, businfo->busno); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { i2c_dbgrpt_bus_info(businfo, /* include sysinfo*/ true, 4); // ddc_dbgrpt_display_refs_summary(/* include_invalid_displays*/ true, /* report_businfo */ false, 2 ); } // bool ok = false; Display_Ref * dref = NULL; Error_Info * err = NULL; // Sys_Drm_Connector * conrec = find_sys_drm_connector(-1, NULL, drm_connector_name); // unused assert(businfo->flags & I2C_BUS_PROBED); // businfo->flags &= ~I2C_BUS_PROBED; // unnecessary, already done by i2c_get_and_check_bus_info() call in our only caller, ddc_i2c_hotplug_change_handler() // i2c_check_bus2(businfo); // if display on bus was previously removed, info in businfo, particuarly EDID, will be stale if (!businfo->edid) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "No display detected on bus %d", businfo->busno); } else { dref = create_bus_display_ref(businfo->busno); // dref->dispno = DISPNO_INVALID; // -1, guilty until proven innocent // dref->dispno = ++dispno_max; // dispno not used in libddcutil except to indicate invalid dref->pedid = copy_parsed_edid(businfo->edid); dref->mmid = mmk_new( dref->pedid->mfg_id, dref->pedid->model_name, dref->pedid->product_code); // drec->detail.bus_detail = businfo; dref->detail = businfo; dref->flags |= DREF_DDC_IS_MONITOR_CHECKED; dref->flags |= DREF_DDC_IS_MONITOR; dref->drm_connector = g_strdup(businfo->drm_connector_name); dref->drm_connector_id = businfo->drm_connector_id; dref_lock(dref); err = ddc_initial_checks_by_dref(dref, true); dref_unlock(dref); if (err) { DBGMSG("ddc_initial_checks_by_dref() returned error:"); errinfo_report(err, 2); } if (err && err->status_code == DDCRC_DISCONNECTED) { assert(dref->flags & DREF_REMOVED); DBGTRC_NOPREFIX(true, DDCA_TRC_CONN, "pathological case, dref=%s", dref_reprx_t(dref)); // pathological case, monitor went away dref->flags |= DREF_TRANSIENT; // allow free_display_ref() to free // free_display_ref(dref); // dref = NULL; } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Display %s found on bus %d", dref_repr_t(dref), businfo->busno); if (!(dref->flags & DREF_DDC_COMMUNICATION_WORKING)) dref->dispno = DISPNO_INVALID; else dref->dispno = ++dispno_max; dw_add_display_ref(dref); } errinfo_free(err); } // edid exists // ddc_dbgrpt_display_refs_summary(/* include_invalid_displays*/ true, /* report_businfo */ true, 2 ); DBGTRC_DONE(debug, DDCA_TRC_CONN, "Returning dref %s", dref_reprx_t(dref), dref); if (IS_DBGTRC(debug, DDCA_TRC_NONE) && dref) dbgrpt_display_ref_summary(dref, /* include_businfo*/ false, 2); return dref; } /** Given a #I2C_Bus_Info instance, checks if there is a currently active #Display_Ref * for that bus (i.e. one with the DREF_REMOVED flag not set). * If found, sets the DREF_REMOVED flag. * * @param businfo * @return Display_Ref */ Display_Ref * dw_remove_display_by_businfo(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "businfo=%p, busno=%d", businfo, businfo->busno); i2c_reset_bus_info(businfo); int busno = businfo->busno; Display_Ref * dref = GET_DREF_BY_BUSNO(businfo->busno, /*ignore_invalid*/ true); char buf[100]; g_snprintf(buf, 100, "Removing connected display on bus %d", businfo->busno); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE,"%s", buf); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", buf); // *** TEMP *** if (dref) { assert(!(dref->flags & DREF_REMOVED)); dw_mark_display_ref_removed(dref); dref->detail = NULL; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Updated flags: %s", interpret_dref_flags_t(dref->flags)); } else { char s[80]; g_snprintf(s, 80, "No Display_Ref found for i2c bus: %d", busno); DBGTRC_NOPREFIX(debug, TRACE_GROUP,"%s", s); SYSLOG2(DDCA_SYSLOG_ERROR, "(%s) %s", __func__, s); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning dref=%p=%s", dref, dref_reprx_t(dref)); return dref; } Error_Info * dw_recheck_dref(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dref=%s", dref_reprx_t(dref)); Error_Info * err = NULL; dref_lock(dref); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Obtained lock on %s:", dref_reprx_t(dref)); dref->flags = 0; err = ddc_initial_checks_by_dref(dref, false); dref_unlock(dref); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Released lock on %s:", dref_reprx_t(dref)); DBGTRC_RET_ERRINFO(debug, DDCA_TRC_NONE, err, ""); return err; } void init_dw_dref() { RTTI_ADD_FUNC(dw_add_display_by_businfo); RTTI_ADD_FUNC(dw_add_display_ref); RTTI_ADD_FUNC(dw_mark_display_ref_removed); RTTI_ADD_FUNC(dw_recheck_dref); RTTI_ADD_FUNC(dw_remove_display_by_businfo); } ddcutil-2.2.0/src/dw/dw_udev.c0000644000175000001440000007617114754153540011646 /** @file dw_udev.c * * Watch for monitor addition and removal using UDEV */ // Copyright (C) 2021-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include "public/ddcutil_types.h" /** \cond */ #include #include #include #include #ifdef ENABLE_UDEV #include #endif #include #include #include #include #include #include "util/coredefs.h" #include "util/data_structures.h" #include "util/debug_util.h" #include "util/drm_common.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/glib_util.h" #include "util/i2c_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_util.h" #include "util/traced_function_stack.h" #include "util/udev_util.h" #include "base/core.h" #include "base/displays.h" #include "base/ddc_errno.h" #include "base/drm_connector_state.h" #include "base/i2c_bus_base.h" #include "base/linux_errno.h" #include "base/rtti.h" #include "base/sleep.h" /** \endcond */ #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_dpms.h" #include "i2c/i2c_bus_core.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp.h" #include "dw_common.h" #include "dw_status_events.h" #include "dw/dw_udev.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; // globals bool use_sysfs_connector_id = true; bool report_udev_events = false; void dbgrpt_udev_device(struct udev_device * dev, bool verbose, int depth) { rpt_structure_loc("udev_device", dev, depth); int d1 = depth+1; // printf(" Node: %s\n", udev_device_get_devnode(dev)); // /dev/dri/card0 // printf(" Subsystem: %s\n", udev_device_get_subsystem(dev)); // drm // printf(" Devtype: %s\n", udev_device_get_devtype(dev)); // drm_minor rpt_vstring(d1, "Action: %s", udev_device_get_action( dev)); // "change" rpt_vstring(d1, "devpath: %s", udev_device_get_devpath( dev)); rpt_vstring(d1, "subsystem: %s", udev_device_get_subsystem(dev)); // drm rpt_vstring(d1, "devtype: %s", udev_device_get_devtype( dev)); // drm_minor rpt_vstring(d1, "syspath: %s", udev_device_get_syspath( dev)); rpt_vstring(d1, "sysname: %s", udev_device_get_sysname( dev)); rpt_vstring(d1, "sysnum: %s", udev_device_get_sysnum( dev)); rpt_vstring(d1, "devnode: %s", udev_device_get_devnode( dev)); // /dev/dri/card0 rpt_vstring(d1, "initialized: %d", udev_device_get_is_initialized( dev)); rpt_vstring(d1, "driver: %s", udev_device_get_driver( dev)); if (verbose) { struct udev_list_entry * entries = NULL; #ifdef NOT_USEFUL // see udevadm -p entries = udev_device_get_devlinks_list_entry(dev); show_udev_list_entries(entries, "devlinks"); entries = udev_device_get_tags_list_entry(dev); show_udev_list_entries(entries, "tags"); #endif entries = udev_device_get_properties_list_entry(dev); show_udev_list_entries(entries, "properties"); entries = udev_device_get_sysattr_list_entry(dev); //show_udev_list_entries(entries, "sysattrs"); show_sysattr_list_entries(dev,entries); } } #ifdef ENABLE_UDEV // // Variant using udev // /** Repeatedly reads the edid attibute from the sysfs drm connector dir * whose name has the specfied value. The value is repeatedly read * until the current value equals the prior value. * * @param drm_connector_name name of connector to check * @param prior_has_edid value prior to recent sysfs drm change * @return true if edid attribute has value, false if not */ bool dw_i2c_stabilized_single_bus_by_connector_name(char * drm_connector_name, bool prior_has_edid) { bool debug = false; // int debug_depth = (debug) ? 1 : -1; DBGTRC_STARTING(debug, TRACE_GROUP, "drm_connector_name=%s, prior_has_edid =%s", drm_connector_name, SBOOL(prior_has_edid)); assert(drm_connector_name); // Special handling for case of apparently disconnected displays. // It has been observed that in some cases (Samsung U32H750) a disconnect is followed a // few seconds later by a connect. Wait a few seconds to avoid triggering events // in this case. if (prior_has_edid) { if (initial_stabilization_millisec > 0) { char * s = g_strdup_printf( "Delaying %d milliseconds to avoid a false disconnect/connect sequence...", initial_stabilization_millisec); DBGTRC(debug, TRACE_GROUP, "%s", s); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", s); free(s); DW_SLEEP_MILLIS(initial_stabilization_millisec, "Initial sleep"); } } int stablect = 0; bool stable = false; while (!stable) { // usleep(1000*stabilization_poll_millisec); DW_SLEEP_MILLIS(stabilization_poll_millisec, "Stabilization loop"); char * s = g_strdup_printf("/sys/class/drm/%s/edid", drm_connector_name); // DBGF(debug, "reading: %s", s); GByteArray* bytes = read_binary_file(s, 2048, true); // DBGF(debug, "bytes read: %d", bytes->len); bool cur_has_edid = (bytes && bytes->len > 0); g_byte_array_free(bytes, true); free(s); // when MST hub powered on or off, failure in assemble_sysfs_path2() // bool cur_has_edid = rpt_attr_edid(debug_depth, NULL, "/sys/class/drm", drm_connector_name, "edid"); if (cur_has_edid == prior_has_edid) stable = true; else prior_has_edid = cur_has_edid; stablect++; } if (stablect > 1) { SYSLOG2(DDCA_SYSLOG_NOTICE, "%s required %d extra calls to rpt_attr_edid()", __func__, stablect-1); } DBGTRC_RET_BOOL(debug, TRACE_GROUP, prior_has_edid, "Required %d extra calls to rpt_attr_edid()", stablect-1); return prior_has_edid; } /** Repeatedly reads the edid attibute from the sysfs drm connector dir * whose connector_id has the specfied value. The value is repeatedly read * until the current value equals the prior value. * * @param connector_id DRM id number of connector to check * @param prior_has_edid value prior to recent sysfs drm change * @return true if sysfs connnector dir attribute edid has value, false if not */ bool dw_i2c_stabilized_bus_by_connector_id(int connector_id, bool prior_has_edid) { bool debug = false; // int debug_depth = (debug) ? 1 : -1; DBGTRC_STARTING(debug, TRACE_GROUP, "connector_id=%d, prior_has_edid =%s", connector_id, SBOOL(prior_has_edid)); char * drm_connector_name = get_sys_drm_connector_name_by_connector_id(connector_id); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "drm_connector_name = |%s|", drm_connector_name); assert(drm_connector_name); prior_has_edid = dw_i2c_stabilized_single_bus_by_connector_name( drm_connector_name, prior_has_edid); free(drm_connector_name); DBGTRC_RET_BOOL(debug, TRACE_GROUP, prior_has_edid, ""); return prior_has_edid; } /** Identifies the current list of buses having an edid and compares the * current list with the previous one. If differences exist, either emit * events directly or place them on the deferred events queue. * * @param bs_prev_buses_w_edid previous set of buses have edid * @param events_queue if null, emit events directly * if non-null, put events on the queue * @return updated set of buses having edid */ Bit_Set_256 dw_i2c_check_bus_changes( Bit_Set_256 bs_prev_buses_w_edid, GArray * events_queue) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "bs_prev_buses_w_edid: %s", BS256_REPR(bs_prev_buses_w_edid)); #ifdef OLD GPtrArray * new_buses = i2c_detect_buses0(); Bit_Set_256 bs_new_buses_w_edid = buses_bitset_from_businfo_array(new_buses, /* only_connected */ true); #endif Bit_Set_256 bs_new_buses_w_edid = i2c_buses_w_edid_as_bitset(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_new_buses_w_edid: %s", BS256_REPR(bs_new_buses_w_edid)); if (!bs256_eq(bs_prev_buses_w_edid, bs_new_buses_w_edid)) { // Detect need for special handling for case of display disconnected. Bit_Set_256 bs_removed = bs256_and_not(bs_prev_buses_w_edid,bs_new_buses_w_edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_removed: %s", BS256_REPR(bs_removed)); bool detected_displays_removed_flag = bs256_count(bs_removed); if (detected_displays_removed_flag) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling ddc_i2c_stabilized_buses()"); #ifdef OLD GPtrArray * stabilized_buses = ddc_i2c_stabilized_buses(new_buses, detected_displays_removed_flag); BS256 bs_stabilized_buses_w_edid = buses_bitset_from_businfo_array(stabilized_buses, /*only_connected*/ true); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_stabilized_buses_w_edid: %s", BS256_REPR(bs_stabilized_buses_w_edid)); // new_buses = stabilized_buses; // unused bs_new_buses_w_edid = bs_stabilized_buses_w_edid; #endif BS256 bs_new_buses_w_edid = dw_stabilized_buses_bs(bs_new_buses_w_edid, detected_displays_removed_flag); } } bool hotplug_change_handler_emitted = false; bool connected_buses_changed = !bs256_eq( bs_prev_buses_w_edid, bs_new_buses_w_edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "connected_buses_changed = %s", SBOOL(connected_buses_changed)); if (connected_buses_changed) { BS256 bs_buses_w_edid_removed = bs256_and_not(bs_prev_buses_w_edid, bs_new_buses_w_edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_buses_w_edid_removed: %s", BS256_REPR(bs_buses_w_edid_removed)); BS256 bs_buses_w_edid_added = bs256_and_not(bs_new_buses_w_edid, bs_prev_buses_w_edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "bs_buses_w_edid_added: %s", BS256_REPR(bs_buses_w_edid_added)); hotplug_change_handler_emitted = dw_hotplug_change_handler( bs_buses_w_edid_removed, bs_buses_w_edid_added, events_queue, NULL); } if (hotplug_change_handler_emitted) DBGTRC_NOPREFIX(debug, TRACE_GROUP, "hotplug_change_handler_emitted = %s", sbool (hotplug_change_handler_emitted)); DBGTRC_DONE(debug, TRACE_GROUP, "Returning Bit_Set_256: %s", BS256_REPR(bs_new_buses_w_edid)); return bs_new_buses_w_edid; } /** Simpler alternative to #ddc_i2c_check_bus_changes() for the common case where * all displays have a sysfs connector record with an accurate edid attribute. * * Checks whether the edid attribute in the card-connector directory exists, * and determines whether the list of buses with edid in * **bs_prev_buses_w_edid** has changed. * * If differences exist, either emit events directly or place them on the * deferred events queue. * * @param connector_number drm connector number * @param connector_name name of card-connector directory * @param bs_prev_buses_w_edid previous set of buses have edid * @param events_queue if null, emit events directly * if non-null, put events on the queue * @return updated set of buses having edid */ Bit_Set_256 dw_i2c_check_bus_changes_for_connector( int connector_number, char * connector_name, Bit_Set_256 bs_prev_buses_w_edid, GArray * events_queue) { bool debug = false; // int debug_depth = (debug) ? 1 : -1; DBGTRC_STARTING(debug, TRACE_GROUP, "connector_number=%d, connector_name=%s, bs_prev_buses_w_edid: %s", connector_number, connector_name, BS256_REPR(bs_prev_buses_w_edid)); Bit_Set_256 bs_new_buses_w_edid = bs_prev_buses_w_edid; int busno = search_all_businfo_records_by_connector_name(connector_name); // busno -1 possible for added hub devices, only the one w attached monitor will have busno if (busno < 0) goto bye; bool prior_has_edid = bs256_contains(bs_prev_buses_w_edid, busno); bool stabilized_bus_has_edid = // ddc_i2c_stabilized_bus_by_connector_id(connector_number, prior_has_edid); dw_i2c_stabilized_single_bus_by_connector_name(connector_name, prior_has_edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ddc_i2c_stabilized_bus_by_connector_id() returned %s", SBOOL(stabilized_bus_has_edid)); if (stabilized_bus_has_edid != prior_has_edid) { if (stabilized_bus_has_edid) { bs_new_buses_w_edid = bs256_insert(bs_new_buses_w_edid, busno); } else { bs_new_buses_w_edid = bs256_remove(bs_new_buses_w_edid, busno); } } bool hotplug_change_handler_emitted = false; bool connected_buses_changed = !bs256_eq( bs_prev_buses_w_edid, bs_new_buses_w_edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "connected_buses_changed = %s", SBOOL(connected_buses_changed)); if (connected_buses_changed) { BS256 bs_buses_w_edid_removed = bs256_and_not(bs_prev_buses_w_edid, bs_new_buses_w_edid); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "bs_buses_w_edid_removed: %s", BS256_REPR(bs_buses_w_edid_removed)); BS256 bs_buses_w_edid_added = bs256_and_not(bs_new_buses_w_edid, bs_prev_buses_w_edid); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "bs_buses_w_edid_added: %s", BS256_REPR(bs_buses_w_edid_added)); hotplug_change_handler_emitted = dw_hotplug_change_handler( bs_buses_w_edid_removed, bs_buses_w_edid_added, events_queue, NULL); } if (hotplug_change_handler_emitted) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "hotplug_change_handler_emitted = %s", sbool (hotplug_change_handler_emitted)); bye: DBGTRC_DONE(debug, TRACE_GROUP, "Returning Bit_Set_256: %s", BS256_REPR(bs_new_buses_w_edid)); return bs_new_buses_w_edid; } #ifdef BAD Bit_Set_256 dw_i2c_check_bus_changes_for_connector( int connector_number, char * connector_name, Bit_Set_256 bs_prev_buses_w_edid, GArray * events_queue) { bool debug = false; int debug_depth = (debug) ? 1 : -1; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "connector_number=%d, connector_name=%s, bs_prev_buses_w_edid: %s", connector_number, connector_name, BS256_REPR(bs_prev_buses_w_edid)); Sys_Drm_Connector * conn = get_drm_connector(connector_name, debug_depth); // can fail! int busno = conn->i2c_busno; free(conn); return ddc_i2c_check_bus_changes_for_busno(busno, bs_prev_buses_w_edid, events_queue); } #endif typedef struct { const char * prop_subsystem; const char * prop_action; const char * prop_connector; const char * prop_devname; const char * prop_hotplug; const char * sysname; const char * attr_name; } Udev_Event_Detail; Udev_Event_Detail* collect_udev_event_detail(struct udev_device * dev) { Udev_Event_Detail * cd = calloc(1, sizeof(Udev_Event_Detail)); cd->prop_subsystem = udev_device_get_property_value(dev, "SUBSYSTEM"); cd->prop_action = udev_device_get_property_value(dev, "ACTION"); // always "changed" cd->prop_connector = udev_device_get_property_value(dev, "CONNECTOR"); // drm connector number cd->prop_devname = udev_device_get_property_value(dev, "DEVNAME"); // e.g. /dev/dri/card0 cd->prop_hotplug = udev_device_get_property_value(dev, "HOTPLUG"); // always 1 cd->sysname = udev_device_get_sysname(dev); // e.g. card0, i2c-27 cd-> attr_name = udev_device_get_sysattr_value(dev, "name"); return cd; } void free_udev_event_detail(Udev_Event_Detail * detail) { free(detail); } void dbgrpt_udev_event_detail(Udev_Event_Detail * detail, int depth) { assert(detail); rpt_structure_loc("Udev_Event_Detail", detail, depth); int d1 = depth + 1; rpt_vstring(d1, "prop_subsystem: %s", detail->prop_subsystem); rpt_vstring(d1, "prop_action: %s", detail->prop_action); rpt_vstring(d1, "prop_connector: %s", detail->prop_connector); rpt_vstring(d1, "prop_devname: %s", detail->prop_devname); rpt_vstring(d1, "prop_hotplug: %s", detail->prop_hotplug); rpt_vstring(d1, "sysname: %s", detail->sysname); rpt_vstring(d1, "attr_name: %s", detail->attr_name); } void debug_watch_state(int connector_number, char * cname) { // NB needs validity checks for production bool debug = false; if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { Sys_Drm_Connector * cur = get_drm_connector(cname, 2); free_sys_drm_connector(cur); } get_sys_drm_connectors(true); rpt_vstring(1, "drm connectors"); report_sys_drm_connectors(true, 1); Sys_Drm_Connector * conn = find_sys_drm_connector_by_connector_id(connector_number); rpt_vstring(1, "connector_number=%d, busno=%d, has_edid=%s", connector_number, conn->i2c_busno, sbool(conn->edid_bytes != NULL)); rpt_label(0, "/sys/class/drm state after hotplug event:"); dbgrpt_sysfs_basic_connector_attributes(1); if (use_drm_connector_states) { rpt_vstring(0, "DRM connector states after hotplug event:"); report_drm_connector_states_basic(/*refresh*/ true, 1); } } /** Main loop watching for display changes. Runs as thread. * * @param data #Watch_Displays_Data passed from creator thread */ gpointer dw_watch_displays_udev(gpointer data) { bool debug = false; bool debug_sysfs_state = false; bool use_deferred_event_queue = false; Watch_Displays_Data * wdd = data; assert(wdd && memcmp(wdd->marker, WATCH_DISPLAYS_DATA_MARKER, 4) == 0 ); DBGTRC_STARTING(debug, TRACE_GROUP, "Caller process id: %d, caller thread id: %d, event_classes=0x%02x", wdd->main_process_id, wdd->main_thread_id, wdd->event_classes); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Watching for display connection events: %s", sbool(wdd->event_classes & DDCA_EVENT_CLASS_DISPLAY_CONNECTION)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Watching for dpms events: %s", sbool(wdd->event_classes & DDCA_EVENT_CLASS_DPMS)); bool watch_dpms = wdd->event_classes & DDCA_EVENT_CLASS_DPMS; pid_t cur_pid = getpid(); pid_t cur_tid = get_thread_id(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Our process id: %d, our thread id: %d", cur_pid, cur_tid); #ifdef NEVER_USED GPtrArray * sleepy_connectors = NULL; if (watch_dpms) sleepy_connectors = g_ptr_array_new_with_free_func(g_free); #endif BS256 bs_sleepy_buses = EMPTY_BIT_SET_256; struct udev* udev = udev_new(); struct udev_monitor* mon = udev_monitor_new_from_netlink(udev, "udev"); // Alternative subsystem devtype values that did not detect changes: // drm_dp_aux_dev, kernel, i2c-dev, i2c, hidraw udev_monitor_filter_add_match_subsystem_devtype(mon, "drm", NULL); // detects // testing for hub changes // #ifdef UDEV_I2C_DEV // i2c-dev report i2c device number, i2c does not, but still not useful udev_monitor_filter_add_match_subsystem_devtype(mon, "i2c-dev", NULL); // #endif // udev_monitor_filter_add_match_subsystem_devtype(mon, "i2c", NULL); udev_monitor_enable_receiving(mon); // make udev_monitor_receive_device() blocking // int fd = udev_monitor_get_fd(mon); // set_fd_blocking(fd); // Sysfs_Connector_Names current_connector_names = get_sysfs_drm_connector_names(); Bit_Set_256 bs_cur_buses_w_edid = buses_bitset_from_businfo_array(all_i2c_buses, /*only_connected=*/ true); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Initial i2c buses with edids: %s", BS256_REPR(bs_cur_buses_w_edid)); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { rpt_vstring(0, "Initial I2C buses:"); i2c_dbgrpt_buses_summary(1); rpt_vstring(0, "Initial Display Refs:"); ddc_dbgrpt_display_refs_summary(true, // include_invalid_displays false, // report_businfo 1); // depth if (use_drm_connector_states) { rpt_vstring(0, "Initial DRM connector states"); report_drm_connector_states_basic(/*refresh*/ true, 1); } } GArray * deferred_events = NULL; if (use_deferred_event_queue) deferred_events = g_array_new( false, // zero_terminated false, // clear sizeof(DDCA_Display_Status_Event)); if (debug_sysfs_state) { rpt_label(0, "Initial sysfs state:"); dbgrpt_sysfs_basic_connector_attributes(1); } ASSERT_IFF(deferred_events, use_deferred_event_queue); struct udev_device * dev = NULL; time_t last_drm_change_timestamp = 0; bool skip_next_sleep = false; while (true) { if (wdd->event_classes & DDCA_EVENT_CLASS_DISPLAY_CONNECTION) { dev = udev_monitor_receive_device(mon); } if (dev) { DBGTRC(debug || report_udev_events, DDCA_TRC_NONE, "Udev event received"); } while (!dev) { uint32_t slept = 0; // will contain length of final sleep if (deferred_events && deferred_events->len > 0) { dw_emit_deferred_events(deferred_events); } else { // skip polling loop sleep if deferred events were output if (!skip_next_sleep) { slept = dw_split_sleep(wdd->watch_loop_millisec); } } skip_next_sleep = false; if (terminate_watch_thread) { // n. slept == 0 if no sleep was performed DBGTRC_DONE(debug, TRACE_GROUP, "Terminating thread. Final polling sleep was %d millisec.", slept); dw_free_watch_displays_data(wdd); // int rc = udev_monitor_filter_remove(mon); udev_monitor_unref(mon); udev_unref(udev); #ifdef WATCH_DPMS if (watch_dpms) g_ptr_array_free(sleepy_connectors, true); #endif free_current_traced_function_stack(); g_thread_exit(0); assert(false); // avoid clang warning re wdd use after free } #ifdef WATCH_DPMS if (watch_dpms) { // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Before ddc_check_bus_asleep(), bs_sleepy_buses: %s", // BS256_REPR(bs_sleepy_buses)); // emits dpms events directly or places them on deferred_events queue bs_sleepy_buses = ddc_i2c_check_bus_asleep( bs_cur_buses_w_edid, bs_sleepy_buses, deferred_events); // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "After ddc_check_bus_asleep(), bs_sleepy_buses: %s", // BS256_REPR(bs_sleepy_buses)); } #endif dw_terminate_if_invalid_thread_or_process(cur_pid, cur_tid); if (wdd->event_classes & DDCA_EVENT_CLASS_DISPLAY_CONNECTION) { dev = udev_monitor_receive_device(mon); } if (dev) { DBGTRC(debug || report_udev_events, DDCA_TRC_NONE, "Udev event received"); } } // end of udev_monitor_receive_dev() polling loop DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "==> udev_event received"); assert(dev); #ifdef DEBUGGING // WHICH REPORT TO USE? if (true) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Got Device\n"); dbgrpt_udev_device(dev, /*verbose=*/false, 2); } report_udev_device(dev, 3 ); #endif skip_next_sleep = true; Udev_Event_Detail * cd = collect_udev_event_detail(dev); assert(cd); // mollify coverity scan if (IS_DBGTRC(debug || report_udev_events, DDCA_TRC_NONE)) dbgrpt_udev_event_detail(cd, 2); // xxx("Event received"); if (!streq(cd->prop_subsystem, "i2c-dev") && !streq(cd->prop_subsystem, "drm")) { DBGMSG("Unexpected subsystem: %s", cd->prop_subsystem); } else if ( streq(cd->prop_subsystem, "i2c-dev") && streq(cd->prop_action, "add") ) { // const char * sysname = cd->sysname; // e.g i2c-27 // const char * attr_name = cd->attr_name; int busno = i2c_name_to_busno(cd->sysname); if (busno < 0) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "sysname is not i2c-n"); } else { I2C_Bus_Info * businfo = i2c_find_bus_info_in_gptrarray_by_busno(all_i2c_buses, busno); if (businfo) { DBGMSG("Unexpected businfo record %p already exists for bus %d", businfo, busno); // TO DO: check for use in non-removed drefs i2c_reset_bus_info(businfo); } else { businfo = i2c_get_and_check_bus_info(busno); } // Error_Info * err = i2c_check_bus2(businfo); // ERRINFO_FREE_WITH_REPORT(err, debug || IS_TRACING() || report_freed_exceptions); i2c_dbgrpt_bus_info(businfo, /*include_sysinfo*/ true, 0); } } else if ( streq(cd->prop_subsystem, "drm") && streq(cd->prop_action, "add") ) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Processing subsystem drm, action add"); Bit_Set_256 bs_udev_buses = i2c_detect_attached_buses_as_bitset(); Bit_Set_256 bs_known_buses = EMPTY_BIT_SET_256; for (int ndx = 0; ndx < all_i2c_buses->len; ndx++) { I2C_Bus_Info * cur = g_ptr_array_index(all_i2c_buses, ndx); // need to check if valid? bs_known_buses = bs256_insert(bs_known_buses, cur->busno); } DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "udev buses: %s", BS256_REPR(bs_udev_buses)); DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "known_buses: %s", BS256_REPR(bs_known_buses)); BS256 buses_added = bs256_minus(bs_udev_buses, bs_known_buses); DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Buses added: %s", BS256_REPR(buses_added)); if (bs256_count(buses_added) > 0) { Bit_Set_256_Iterator iter = bs256_iter_new(buses_added); while (true) { int busno = bs256_iter_next(iter); if (busno < 0) break; I2C_Bus_Info * businfo = i2c_get_and_check_bus_info(busno); // I2C_Bus_Info * businfo = i2c_add_bus(busno); // i2c_check_bus2(businfo); i2c_dbgrpt_bus_info(businfo, /* include_sysinfo */ true, 2); DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Adding businfo record for /dev/"I2C"-%d", busno); } } } else if ( streq(cd->prop_subsystem, "drm") && streq(cd->prop_action, "change") ) { // xxx("drm change"); bool processed = false; time_t prev_change_timestamp = last_drm_change_timestamp; last_drm_change_timestamp = cur_realtime_nanosec(); time_t delta_time = last_drm_change_timestamp - prev_change_timestamp; DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "nanosec since prev drm/change event: %jd", delta_time); if (use_sysfs_connector_id) { char * cname = NULL; int connector_number = -1; if (cd && streq(cd->prop_action, "change") && cd->prop_connector) { // seen null when MST hub added bool valid_number = str_to_int(cd->prop_connector, &connector_number, 10); assert(valid_number); cname = get_sys_drm_connector_name_by_connector_id(connector_number); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "get_sys_drm_connector_name_by_connector_id() returned: %s", cname); if (debug_sysfs_state) { // move debug statements out of mainline debug_watch_state(connector_number, cname); } // debug_sysfs_state if (cname) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "1) Using connector id %d, name =%s", connector_number, cname); bs_cur_buses_w_edid = dw_i2c_check_bus_changes_for_connector( connector_number, cname, bs_cur_buses_w_edid, deferred_events); // xxx("drm change case1"); processed = true; } #ifdef UDEV_I2C_DEV if (!processed) { if (drm_udev_detail && (streq(drm_udev_detail->prop_action,"add")||streq(drm_udev_detail->prop_action, "remove") ) && drm_udev_detail->sysname) { int busno = i2c_name_to_busno(drm_udev_detail->sysname); cname = get_sys_drm_connector_name_by_busno(busno); } if (cname) { DBGTRC(true, DDCA_TRC_NONE, "2) connector name reported by get_sys_drm_connector_name_by_busno(): %s", cname); bs_cur_buses_w_edid = dw_i2c_check_bus_changes_for_connector( connector_number, cname, bs_cur_buses_w_edid, deferred_events); processed = true; } } if (!processed) { if (i2c_dev_udev_detail && i2c_dev_udev_detail->sysname && (streq(drm_udev_detail->prop_action,"add")||streq(drm_udev_detail->prop_action, "remove")) ) { int busno = i2c_name_to_busno(i2c_dev_udev_detail->sysname); cname = get_sys_drm_connector_name_by_busno(busno); } if (cname) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "3) connector name reported by get_sys_drm_connector_name_by_busno(): %s", cname); bs_cur_buses_w_edid = dw_i2c_check_bus_changes_for_connector( connector_number, cname, bs_cur_buses_w_edid, deferred_events); processed = true; } } #endif } free(cname); } if (!processed) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "4) Calling ddc_i2c_check_bus_changes"); // emits display change events or queues them bs_cur_buses_w_edid = dw_i2c_check_bus_changes(bs_cur_buses_w_edid, deferred_events); } if (watch_dpms) { // remove buses marked asleep if they no longer have a monitor so they will // not be considered asleep when reconnected bs_sleepy_buses = bs256_and(bs_sleepy_buses, bs_cur_buses_w_edid); } } // subsystem drm, action change free_udev_event_detail(cd); cd = NULL; udev_device_unref(dev); dev = NULL; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "==> udev event processed"); } // while // This is not the real function exit point. Function termination occurs // using g_thread_exit within the udev event polling loop. assert(false); return NULL; } #endif // ENABLE_UDEV void init_dw_udev() { #ifdef ENABLE_UDEV #ifdef UNUSED RTTI_ADD_FUNC(ddc_i2c_filter_sleep_events); #endif RTTI_ADD_FUNC(dw_i2c_check_bus_changes); RTTI_ADD_FUNC(dw_i2c_check_bus_changes_for_connector); RTTI_ADD_FUNC(dw_i2c_stabilized_bus_by_connector_id); RTTI_ADD_FUNC(dw_i2c_stabilized_single_bus_by_connector_name); #ifdef WATCH_DPMS RTTI_ADD_FUNC(ddc_i2c_check_bus_asleep); #endif RTTI_ADD_FUNC(dw_watch_displays_udev); #endif } ddcutil-2.2.0/src/dw/dw_recheck.c0000644000175000001440000002012514754576332012303 /** @file dw_recheck.c */ // Copyright (C) 2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include "public/ddcutil_types.h" #include "util/timestamp.h" #include "util/traced_function_stack.h" #include "base/core.h" #include "base/displays.h" #include "base/rtti.h" #include "base/sleep.h" #include "ddc/ddc_displays.h" #include "dw_common.h" #include "dw_dref.h" #include "dw_status_events.h" #include "dw_poll.h" // for process_event_mutex, todo: move #include "dw_recheck.h" static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; #ifdef UNUSED static int simple_ipow(int base, int exponent) { assert(exponent >= 0); int result = 1; for (int i = 0; i < exponent; i++) { result = result * base; } return result; } #endif void emit_recheck_debug_msg( bool debug, DDCA_Syslog_Level syslog_level, const char * format, ...) { va_list(args); va_start(args, format); char buffer[200]; vsnprintf(buffer, 200, format, args); va_end(args); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "%s", buffer); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", buffer); } typedef struct { Display_Ref* dref; uint64_t initial_ts_nanos; int sleepctr; } Recheck_Queue_Entry; void dw_free_recheck_queue_entry(Recheck_Queue_Entry * entry) { free(entry); } GAsyncQueue * recheck_queue = NULL; GMutex * recheck_queue_mutex = NULL; GAsyncQueue * init_recheck_queue() { recheck_queue = g_async_queue_new(); return recheck_queue; } void dw_put_recheck_queue(Display_Ref* dref) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_CONN, "dref=%s", dref_reprx_t(dref)); Recheck_Queue_Entry * entry = calloc(1, sizeof(Recheck_Queue_Entry)); entry->dref = dref; entry->initial_ts_nanos = cur_realtime_nanosec(); entry->sleepctr = 0; // g_mutex_lock(recheck_queue_mutex); g_async_queue_push(recheck_queue, entry); // g_mutex_unlock(recheck_queue_mutex); DBGTRC_DONE(debug, DDCA_TRC_CONN, ""); } #ifdef NO typedef struct { GArray * deferred_event_queue; GMutex * deferred_event_queue_mutex; } Recheck_Displays_Data; #endif /** Function that executes in the recheck thread thread to check if a DDC * communication has become enabled for newly added display refs for which * DDC communication was not initially detected as working. * * @param data pointer to a #Recheck_Displays_Data struct * * At increasing time intervals, each display ref is checked to see if DDC * communication is working. If so, a #DDC_Display_Status event of type * #DDCA_EVENT_DDC_ENABLED is emitted, and the display ref is removed from * from the array. * * The time intervals are calculated as follows. The intervals are numbered * from 0. The base interval is global variable #retry_thread_sleep_factor_millis. * An adjustment factor is calculated as 2**i, where i is the interval number, * i.e. 1, 2, 4, 8 etc. * * The thread terminates when either all display refs have been removed from * the array because communication has succeeded, or because the maximum of * sleep intervals have occurred, i.e. until a total of * (1+2+4+8)*retry_thread_sleep_factor_millis milliseconds have been slept. * * On termination the **displays to recheck** array is freed. Note that the * display references themselves are not; display references are persistent. */ gpointer dw_recheck_displays_func(gpointer data) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "data=%p", data); Recheck_Displays_Data* rdd = (Recheck_Displays_Data *) data; init_recheck_queue(); // recheck_thread_active = true; // GPtrArray * displays_to_recheck = g_ptr_array_new(); #ifdef DEBUG for (int ndx = 0; ndx < displays_to_recheck->len; ndx++) { Display_Ref * dref = g_ptr_array_index(displays_to_recheck, ndx); DBGMSG("dref=%s", dref_reprx_t(dref)); } #endif GQueue * to_check_again = g_queue_new(); int sleep_interval_millis = 200; // temp int max_sleep_time_millis = 3000; int pop_interval_millis = 100; while (!terminate_watch_thread) { DW_SLEEP_MILLIS(sleep_interval_millis, "Recheck interval"); // move to end of loop uint64_t cur_time_nanos = cur_realtime_nanosec(); Recheck_Queue_Entry* rqe = NULL; while (!rqe && !terminate_watch_thread) { while (g_queue_get_length(to_check_again) > 0) { rqe = g_queue_pop_head(to_check_again); g_async_queue_push_front(recheck_queue, rqe); } uint64_t pop_interval_micros = MILLIS2MICROS(pop_interval_millis); rqe = g_async_queue_timeout_pop(recheck_queue, pop_interval_micros); if (terminate_watch_thread) { continue; } } if (terminate_watch_thread) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "terminating recheck thread execution"); break; } if (cur_time_nanos > rqe->initial_ts_nanos + MILLIS2NANOS(max_sleep_time_millis)) { emit_recheck_debug_msg(debug, DDCA_SYSLOG_NOTICE, "ddc did not become enabled for %s after %d milliseconds", dref_reprx_t(rqe->dref), max_sleep_time_millis); dw_free_recheck_queue_entry(rqe); continue; } Display_Ref * dref = rqe->dref; // DBGMSG(" rechecking %s", dref_repr_t(dref)); Error_Info * err = dw_recheck_dref(dref); // <=== DBGTRC_NOPREFIX(false, DDCA_TRC_NONE, "after dw_recheck_dref(), dref->flags=%s", interpret_dref_flags_t(dref->flags)); // dbgrpt_display_ref(dref,false,2); if (!err) { emit_recheck_debug_msg(debug, DDCA_SYSLOG_NOTICE, "ddc became enabled for %s after %ld milliseconds", dref_reprx_t(dref), NANOS2MILLIS(cur_realtime_nanosec() - rqe->initial_ts_nanos)); dref->dispno = ++dispno_max; DBGTRC_NOPREFIX(false, DDCA_TRC_NONE, "locking process_event_mutex"); g_mutex_lock(&process_event_mutex); dw_emit_or_queue_display_status_event( DDCA_EVENT_DDC_ENABLED, dref->drm_connector, dref, dref->io_path, NULL); // deferred_event_queue); g_mutex_unlock(&process_event_mutex); DBGTRC_NOPREFIX(false, DDCA_TRC_NONE, "unlocked process_event_mutex"); dw_free_recheck_queue_entry(rqe); } else if (err->status_code == DDCRC_DISCONNECTED) { emit_recheck_debug_msg(debug, DDCA_SYSLOG_NOTICE, "Display %s no longer detected after %"PRIu64" milliseconds", dref_reprx_t(dref), NANOS2MILLIS(cur_time_nanos - rqe->initial_ts_nanos)); dref->dispno = DISPNO_REMOVED; dw_emit_or_queue_display_status_event( DDCA_EVENT_DISPLAY_DISCONNECTED, dref->drm_connector, dref, dref->io_path, NULL); // rdd->deferred_event_queue); dw_free_recheck_queue_entry(rqe); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ddc still not enabled for %s after %d milliseconds, retrying ...", dref_reprx_t(rqe->dref), sleep_interval_millis); g_queue_push_head(to_check_again, rqe); } } if (terminate_watch_thread) { char * s = "recheck thread terminating because watch thread terminated"; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "%s", s); SYSLOG2(DDCA_SYSLOG_NOTICE, "%s", s); // free what's left on the queue while (true) { Recheck_Queue_Entry * rqe = g_async_queue_timeout_pop(recheck_queue, 0); if (!rqe) break; emit_recheck_debug_msg(debug, DDCA_SYSLOG_ERROR, "Flushing request queue entry for %s ", dref_reprx_t(rqe->dref)); } } free(rdd); DBGTRC_DONE(debug, TRACE_GROUP, "terminating recheck thread"); free_current_traced_function_stack(); // recheck_thread_active = false; g_thread_exit(NULL); return NULL; // no effect, but avoids compiler error } void init_dw_recheck() { RTTI_ADD_FUNC(dw_recheck_displays_func); } ddcutil-2.2.0/src/dw/dw_services.c0000644000175000001440000000165514754153540012521 /** @file dw_services.c * * display watch layer initialization and configuration */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include "dw/dw_common.h" #include "dw/dw_dref.h" #include "dw/dw_main.h" #include "dw/dw_poll.h" #include "dw/dw_recheck.h" #include "dw/dw_status_events.h" #include "dw/dw_udev.h" #include "dw/dw_xevent.h" #include "dw_services.h" /** Initialize files in dw directory */ void init_dw_services() { bool debug = false; DBGMSF(debug, "Starting"); init_dw_common(); init_dw_dref(); init_dw_main(); init_dw_poll(); init_dw_recheck(); init_dw_udev(); init_dw_xevent(); DBGMSF(debug, "Done"); } /** Termination for files in dw directory */ void terminate_dw_services() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_CONN, ""); DBGTRC_DONE(debug, DDCA_TRC_CONN, ""); } ddcutil-2.2.0/src/dw/dw_xevent.c0000644000175000001440000002136514754153540012207 /** @file dw_xevent.c */ #include #include #include #include #include "util/report_util.h" #include "base/core.h" #include "base/displays.h" // for terminate_watch_thread #include "base/i2c_bus_base.h" // for DW_SLEEP() #include "base/rtti.h" #include "base/sleep.h" #include "dw_common.h" #include "dw_xevent.h" static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_CONN; // static Display* dpy; static Atom termination_atom; void dw_dbgrpt_xevent_data(XEvent_Data* evdata, int depth) { rpt_structure_loc("XEvent_Data", evdata, depth); int d1 = depth+1; rpt_vstring(d1, "dpy: %p", evdata->dpy); rpt_vstring(d1, "screen: %d", evdata->screen); rpt_vstring(d1, "w: %jd", (uintmax_t) evdata->w); rpt_vstring(d1, "rr_error_base: %d", evdata->rr_error_base); rpt_vstring(d1, "rr_event_base: %d", evdata->rr_event_base); rpt_vstring(d1, "screen_change_eventno: %d", evdata->screen_change_eventno); } void dw_free_xevent_data(XEvent_Data * evdata) { if (evdata->dpy) XCloseDisplay(evdata->dpy); free(evdata); } /** Initialization for using X11 to detect screen changes. * * @return pointer to newly allocated XEvent_Data struct, * NULL if initialization fails */ XEvent_Data * dw_init_xevent_screen_change_notification() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); bool ok = false; // check for extension XEvent_Data * evdata = calloc(1, sizeof(XEvent_Data)); Display * display = XOpenDisplay(NULL); evdata->dpy = display; // dpy = display; if (!evdata->dpy) goto bye; evdata->screen = DefaultScreen(evdata->dpy); evdata->w = RootWindow(evdata->dpy, evdata->screen); bool have_rr = XRRQueryExtension(evdata->dpy, &evdata->rr_event_base, &evdata->rr_error_base); if (have_rr) { int maj = 0; int min = 0; XRRQueryVersion(evdata->dpy, &maj, &min); int version = (maj << 8) | min; if (version < 0x0102) // is this the right version check? have_rr = false; } if (!have_rr) { DBGTRC(true, DDCA_TRC_NONE, "XRR Extension unavailable"); goto bye; } evdata->screen_change_eventno = evdata->rr_event_base + RRScreenChangeNotify; if (!terminate_using_x11_event) { XRRSelectInput(evdata->dpy, evdata->w, RRScreenChangeNotifyMask); // XSelectInput(evdata->dpy, evdata->w, RRScreenChangeNotifyMask); } else { termination_atom = XInternAtom(evdata->dpy, "TERMINATION_MSG", false); XRRSelectInput(evdata->dpy, evdata->w, 0xffffffff); } ok = true; bye: if (!ok) { dw_free_xevent_data(evdata); evdata = NULL; } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", evdata); return evdata; } // // Used for non XIfEvent() mode, i.e. terminate_using_x11_event == false // /** Waits for an X11 screen change event. Repeatedly calls XCheckTypedEvent() * in a polling loop until a screen change XEvent is received or the polling * loop is terminated by #global terminate_watch_thread being set. * * This function is used when waiting is NOT terminated by a user created * X11 event. * * @param evdata pointer to XEvent_Data struct * @param poll_interval XCheckTypedEvent() polling interval in milliseconds * @retval true screen changed event was received * @retval false no event received, termination signal received */ bool dw_detect_xevent_screen_change(XEvent_Data *evdata, int poll_interval) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "evdata=%p, poll_interval=%d millisec", evdata, poll_interval); bool found = false; int flushct = 0; XEvent event; while (true) { if (terminate_watch_thread) break; found = XCheckTypedEvent(evdata->dpy, evdata->screen_change_eventno, &event); if (found) { if (debug) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Received event type %d", event.type); XAnyEvent *e = (XAnyEvent*) &event; if (debug) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "windows change event serial %ld, synthetic %s, window %ju,", e->serial, sbool(e->send_event), (intmax_t)e->window); bool more = true; while (more) { more = XCheckTypedEvent(evdata->dpy, evdata->screen_change_eventno, &event); flushct++; } if (debug) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Flushed %d events", flushct); break; } else { // if (debug) // printf("."); sleep_millis(poll_interval); } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, found, "Flushed %d events", flushct); return found; } // // Used when checking the event queue using XIfEvent() // /** Calls XSendEvent to place a termination message into the * event queue. * * @param evdata pointer to XEvent_Data struct */ void dw_send_x11_termination_message(XEvent_Data * evdata) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "evdata->dpy=%p", evdata->dpy); Display * dpy = evdata->dpy; // Display * dpy = XOpenDisplay(NULL); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "dpy = %p", dpy); int screen = DefaultScreen(dpy); Window win = RootWindow(dpy, screen); XEvent evt; evt.xclient.type = ClientMessage; evt.xclient.serial = 0; evt.xclient.send_event = True; evt.xclient.display = evdata->dpy; evt.xclient.window = win; evt.xclient.message_type = termination_atom; evt.xclient.format = 32; evt.xclient.data.l[0] = 0; evt.xclient.data.l[1] = 0; evt.xclient.data.l[2] = 0; evt.xclient.data.l[3] = 0; evt.xclient.data.l[4] = 0; // Send the client message DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling XSendEvent() ..."); bool ok = XSendEvent(dpy, win /*DefaultRootWindow(dpy)*/, False, NoEventMask, /* SubstructureRedirectMask | SubstructureNotifyMask,*/ (XEvent *)&evt); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "XSendEvent() returned %s", SBOOL(ok)); XFlush(dpy); DW_SLEEP_MILLIS(2000, "After XSendEvent"); // needed? if (ok) DBGTRC_DONE(debug, TRACE_GROUP, "XSendEvent() succeeded"); else DBGTRC_DONE(debug, TRACE_GROUP, "XSendEvent() failed!"); } /** Predicate function used by XIfEvent() * * @param dsp X11 display * @param evt XEvent to test * @param arg pointer to Watch_Displays_Data */ Bool dw_is_ddc_event(Display * dsp, XEvent * evt, XPointer arg) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dsp=%p, evt=%p, arg=%p", dsp, evt, arg); bool result = false; XEvent_Data * evdata = (XEvent_Data*) arg; if (evt->xclient.type == ClientMessage && evt->xclient.message_type == termination_atom ) { result = true; DBGMSG("detected termination msg"); } else if (evt->xclient.type == evdata->screen_change_eventno) { result = true; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "detected screen change"); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Ignoring evnt->xclient.type == %d", evt->xclient.type); } DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, ""); return result; } /** Blocks until either a XRRScreenChangeEvent or ClientMessageEvent is returned * * #param evdata pointer to XEvent_Data * @return true received ScreenChangeNotify event * false received termination event */ bool dw_next_X11_event_of_interest(XEvent_Data * evdata) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP,"evdata=%p", evdata); bool result = false; XEvent event_return; // XNextEvent(evdata->dpy, &event_return); // temp XIfEvent(evdata->dpy, &event_return, dw_is_ddc_event, (XPointer) evdata); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "XIfEvent returned"); if (event_return.xclient.type == ClientMessage && event_return.xclient.message_type == termination_atom ) { DBGMSG("received termination msg"); result = false; } else if (event_return.xclient.type == evdata->screen_change_eventno) { DBGMSG("received screen changed event"); result = true; XEvent event; bool more = true; int flushct = 0; while (more) { more = XCheckTypedEvent(evdata->dpy, evdata->screen_change_eventno, &event); flushct++; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Flushed %d events", flushct); } DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, ""); return result; } void init_dw_xevent() { RTTI_ADD_FUNC(dw_detect_xevent_screen_change); RTTI_ADD_FUNC(dw_init_xevent_screen_change_notification); RTTI_ADD_FUNC(dw_next_X11_event_of_interest); RTTI_ADD_FUNC(dw_send_x11_termination_message); RTTI_ADD_FUNC(dw_is_ddc_event); } ddcutil-2.2.0/src/dw/dw_archived.c0000644000175000001440000003252214754576332012470 // watch_displays_archived.c // Copyright (C) 2018 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifdef DETAILED_DISPLAY_CHANGE_HANDLING // // Modify local data structures before invoking client callback functions. // Too many edge cases // /** Process a display removal event. * * The currently active Display_Ref for the specified DRM connector * name is located. It is marked removed, and the associated * I2C_Bus_Info struct is reset. * * @param drm_connector connector name, e.g. card0-DP-1 * @remark * Does not handle displays using USB for communication */ bool ddc_remove_display_by_drm_connector(const char * drm_connector) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "drm_connector = %s", drm_connector); // DBGTRC_NOPREFIX(true, TRACE_GROUP, "All existing Bus_Info recs:"); // i2c_dbgrpt_buses(/* report_all */ true, 2); bool found = false; assert(all_display_refs); for (int ndx = 0; ndx < all_display_refs->len; ndx++) { // If a display is repeatedly removed and added on a particular connector, // there will be multiple Display_Ref records. All but one should already // be flagged DDCA_DISPLAY_REMOVED, and should not have a pointer to // an I2C_Bus_Info struct. Display_Ref * dref = g_ptr_array_index(all_display_refs, ndx); assert(dref); DBGMSG("Checking dref %s", dref_repr_t(dref)); dbgrpt_display_ref(dref, 2); if (dref->io_path.io_mode == DDCA_IO_I2C) { if (dref->flags & DDCA_DISPLAY_REMOVED) { DBGMSG("DDCA_DISPLAY_REMOVED set"); continue; } I2C_Bus_Info * businfo = dref->detail; // DBGMSG("businfo = %p", businfo); assert(businfo); DBGMSG("Checking I2C_Bus_Info for %d", businfo->busno); if (!(businfo->flags & I2C_BUS_DRM_CONNECTOR_CHECKED)) i2c_check_businfo_connector(businfo); DBGMSG("drm_connector_found_by = %s (%d)", drm_connector_found_by_name(businfo->drm_connector_found_by), businfo->drm_connector_found_by); if (businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_FOUND) { DBGMSG("comparing %s", businfo->drm_connector_name); if (streq(businfo->drm_connector_name, drm_connector)) { DBGMSG("Found drm_connector %s", drm_connector); dref->flags |= DREF_REMOVED; i2c_reset_bus_info(businfo); DDCA_Display_Detection_Report report; report.operation = DDCA_DISPLAY_REMOVED; report.dref = dref; ddc_emit_display_detection_event(report); found = true; break; } } } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, found, ""); return found; } bool ddc_add_display_by_drm_connector(const char * drm_connector_name) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "drm_connector_name = %s", drm_connector_name); bool ok = false; Sys_Drm_Connector * conrec = find_sys_drm_connector(-1, NULL, drm_connector_name); if (conrec) { int busno = conrec->i2c_busno; // TODO: ensure that there's no I2c_Bus_Info record for the bus I2C_Bus_Info * businfo = i2c_find_bus_info_by_busno(busno); if (!businfo) businfo = i2c_new_bus_info(busno); if (businfo->flags&I2C_BUS_PROBED) { SEVEREMSG("Display added for I2C bus %d still marked in use", busno); i2c_reset_bus_info(businfo); } i2c_check_bus(businfo); if (businfo->flags & I2C_BUS_ADDR_0X50) { Display_Ref * old_dref = ddc_get_display_ref_by_drm_connector(drm_connector_name, /*ignore_invalid*/ false); if (old_dref) { SEVEREMSG("Active Display_Ref already exists for DRM connector %s", drm_connector_name); // how to handle? old_dref->flags |= DREF_REMOVED; } Display_Ref * dref = create_bus_display_ref(busno); dref->dispno = DISPNO_INVALID; // -1, guilty until proven innocent dref->pedid = copy_parsed_edid(businfo->edid); // needed? dref->mmid = monitor_model_key_new( dref->pedid->mfg_id, dref->pedid->model_name, dref->pedid->product_code); // drec->detail.bus_detail = businfo; dref->detail = businfo; dref->flags |= DREF_DDC_IS_MONITOR_CHECKED; dref->flags |= DREF_DDC_IS_MONITOR; g_ptr_array_add(all_display_refs, dref); DDCA_Display_Detection_Report report = {dref, DDCA_DISPLAY_ADDED}; ddc_emit_display_detection_event(report); ok = true; } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, ok, ""); return ok; } #endif #ifdef OLD_HOTPLUG_VERSION typedef enum {Changed_None = 0, Changed_Added = 1, Changed_Removed = 2, Changed_Both = 3, // n. == Changed_Added | Changed_Removed } Displays_Change_Type; const char * displays_change_type_name(Displays_Change_Type change_type); const char * displays_change_type_name(Displays_Change_Type change_type) { char * result = NULL; switch(change_type) { case Changed_None: result = "Changed_None"; break; case Changed_Added: result = "Changed_Added"; break; case Changed_Removed: result = "Changed_Removed"; break; case Changed_Both: result = "Changed_Both"; break; } return result; } #endif // How to detect main thread crash? #ifdef OLD_HOTPLUG_VERSION gpointer ddc_watch_displays_using_poll(gpointer data) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); Watch_Displays_Data * wdd = data; assert(wdd && memcmp(wdd->marker, WATCH_DISPLAYS_DATA_MARKER, 4) == 0); GPtrArray * prev_displays = get_sysfs_drm_displays(); // GPtrArray of DRM connector names DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Initial active DRM connectors: %s", join_string_g_ptr_array_t(prev_displays, ", ") ); while (!terminate_watch_thread) { prev_displays = double_check_displays(prev_displays, data); check_drefs_alive(); usleep(3000*1000); // printf("."); fflush(stdout); } DBGTRC_DONE(true, TRACE_GROUP, "Terminating"); free_watch_displays_data(wdd); g_thread_exit(0); return NULL; // satisfy compiler check that value returned } #endif #ifdef OLD_HOTPLUG_VERSION void dummy_display_change_handler( Displays_Change_Type changes, GPtrArray * removed, GPtrArray * added) { bool debug = false; // DBGTRC_STARTING(debug, TRACE_GROUP, "changes = %s", displays_change_type_name(changes)); if (removed && removed->len > 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Removed displays: %s", join_string_g_ptr_array_t(removed, ", ") ); } if (added && added->len > 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Added displays: %s", join_string_g_ptr_array_t(added, ", ") ); } // DBGTRC_DONE(debug, TRACE_GROUP, ""); } void api_display_change_handler( Displays_Change_Type changes, GPtrArray * removed, GPtrArray * added) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "changes = %s", displays_change_type_name(changes)); #ifdef DETAILED_DISPLAY_CHANGE_HANDLING if (removed && removed->len > 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Removed displays: %s", join_string_g_ptr_array_t(removed, ", ") ); if (removed) { for (int ndx = 0; ndx < removed->len; ndx++) { bool ok = ddc_remove_display_by_drm_connector(g_ptr_array_index(removed, ndx)); if (!ok) DBGMSG("Display with drm connector %s not found", g_ptr_array_index(removed,ndx)); } } } if (added && added->len > 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Added displays: %s", join_string_g_ptr_array_t(added, ", ") ); if (added) { for (int ndx = 0; ndx < added->len; ndx++) { bool ok = ddc_add_display_by_drm_connector(g_ptr_array_index(added, ndx)); if (!ok) DBGMSG("Display with drm connector %s already exists", g_ptr_array_index(added,ndx)); } } } #endif // simpler // ddc_emit_display_hotplug_event(); DBGTRC_DONE(debug, TRACE_GROUP, ""); } #endif #ifdef OLD_HOTPLUG_VERSION /** Starts thread that watches for addition or removal of displays * * \retval DDCRC_OK * \retval DDCRC_INVALID_OPERATION thread already running */ DDCA_Status ddc_start_watch_displays(bool use_udev_if_possible) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "watch_displays_enabled=%s, use_udev_if_possible=%s", SBOOL(watch_displays_enabled), SBOOL(use_udev_if_possible) ); DDCA_Status ddcrc = DDCRC_OK; watch_displays_enabled = true; // n. changing the meaning of watch_displays_enabled if (watch_displays_enabled) { char * class_drm_dir = #ifdef TARGET_BSD "/compat/sys/class/drm"; #else "/sys/class/drm"; #endif Bit_Set_32 drm_card_numbers = get_sysfs_drm_card_numbers(); if (bs32_count(drm_card_numbers) == 0) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "No DRM enabled video cards found in %s. Disabling detection of display hotplug events.", class_drm_dir); ddcrc = DDCRC_INVALID_OPERATION; } else { if (!all_video_devices_drm()) { MSG_W_SYSLOG(DDCA_SYSLOG_WARNING, "Not all video cards support DRM. Hotplug events are not not detected for connected monitors."); } g_mutex_lock(&watch_thread_mutex); if (watch_thread) ddcrc = DDCRC_INVALID_OPERATION; else { terminate_watch_thread = false; Watch_Displays_Data * data = calloc(1, sizeof(Watch_Displays_Data)); memcpy(data->marker, WATCH_DISPLAYS_DATA_MARKER, 4); // data->display_change_handler = api_display_change_handler; data->display_change_handler = dummy_display_change_handler; data->main_process_id = getpid(); // data->main_thread_id = syscall(SYS_gettid); data->main_thread_id = get_thread_id(); data->drm_card_numbers = drm_card_numbers; void * watch_func = ddc_watch_displays_using_poll; ddc_watching_using_udev = false; #ifdef ENABLE_UDEV if (use_udev_if_possible) { watch_func = watch_displays_using_udev; ddc_watching_using_udev = true; } #endif watch_thread = g_thread_new( "watch_displays", // optional thread name watch_func, #ifdef OLD #if ENABLE_UDEV (use_udev_if_possible) ? watch_displays_using_udev : ddc_watch_displays_using_poll, #else ddc_watch_displays_using_poll, #endif #endif data); SYSLOG2(DDCA_SYSLOG_NOTICE, "Watch thread started"); } g_mutex_unlock(&watch_thread_mutex); } } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, "watch_displays_enabled=%s. watch_thread=%p", SBOOL(watch_displays_enabled), watch_thread); return ddcrc; } // only makes sense if polling! // locks udev_monitor_receive_device() blocks /** Halts thread that watches for addition or removal of displays. * * Does not return until the watch thread exits. * * \retval DDCRC_OK * \retval DDCRC_INVALID_OPERATION no watch thread running */ DDCA_Status ddc_stop_watch_displays() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "watch_displays_enabled=%s", SBOOL(watch_displays_enabled) ); DDCA_Status ddcrc = DDCRC_OK; if (watch_displays_enabled) { g_mutex_lock(&watch_thread_mutex); // does not work if watch_displays_using_udev(), loop doesn't wake up unless there's a udev event if (watch_thread) { if (ddc_watching_using_udev) { #ifdef ENABLE_UDEV DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Waiting for watch thread to terminate..."); terminate_watch_thread = true; // signal watch thread to terminate // if using udev, thread never terminates because udev_monitor_receive_device() is blocking, // so termiate flag doesn't get checked // no big deal, ddc_stop_watch_displays() is only called at program termination to // release resources for tidyness #else PROGRAM_LOGIC_ERROR("watching_using_udev set when ENABLE_UDEV not set"); #endif } else { // watching using poll terminate_watch_thread = true; // signal watch thread to terminate DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Waiting %d millisec for watch thread to terminate...", 4000); usleep(4000*1000); // greater than the sleep in watch_displays_using_poll() g_thread_join(watch_thread); // g_thread_unref(watch_thread); } watch_thread = NULL; SYSLOG2(DDCA_SYSLOG_NOTICE, "Watch thread terminated."); } else ddcrc = DDCRC_INVALID_OPERATION; g_mutex_unlock(&watch_thread_mutex); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, "watch_thread=%p", watch_thread); return ddcrc; } #endif #include "ddc_watch_displays_extended_poll.h" ddcutil-2.2.0/src/dw/dw_common.h0000644000175000001440000000556614754576332012210 /** @file dw_common.h */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_COMMON_H_ #define DW_COMMON_H_ #include #include #include "util/data_structures.h" #include "util/linux_util.h" #include "base/displays.h" #include "dw_xevent.h" extern uint16_t initial_stabilization_millisec; extern uint16_t stabilization_poll_millisec; extern uint16_t udev_watch_loop_millisec; extern uint16_t poll_watch_loop_millisec; extern uint16_t xevent_watch_loop_millisec; extern bool terminate_using_x11_event; uint32_t dw_calc_watch_loop_millisec(DDC_Watch_Mode watch_mode); uint32_t dw_split_sleep(int watch_loop_millisec); void dw_terminate_if_invalid_thread_or_process(pid_t cur_pid, pid_t cur_tid); typedef void (*Display_Change_Handler)( GPtrArray * buses_removed, GPtrArray * buses_added, GPtrArray * connectors_removed, GPtrArray * connectors_added); #define WATCH_DISPLAYS_DATA_MARKER "WDDM" typedef struct { char marker[4]; pid_t main_process_id; pid_t main_thread_id; DDCA_Display_Event_Class event_classes; DDC_Watch_Mode watch_mode; int watch_loop_millisec; XEvent_Data * evdata; } Watch_Displays_Data; void dw_free_watch_displays_data(Watch_Displays_Data * wdd); #define RECHECK_DISPLAYS_DATA_MARKER "RDDM" typedef struct { char marker[4]; pid_t main_process_id; //? pid_t main_thread_id; //? } Recheck_Displays_Data; void dw_free_recheck_displays_data(Recheck_Displays_Data * rdd); #define CALLBACK_DISPLAYS_DATA_MARKER "CDDM" typedef struct { char marker[4]; pid_t main_process_id; //? // pid_t main_thread_id; //? } Callback_Displays_Data; Callback_Displays_Data * dw_new_callback_displays_data(); void dw_free_callback_displays_data(Callback_Displays_Data * rdd); #ifdef UNUSED typedef struct { Bit_Set_256 all_displays; Bit_Set_256 displays_w_edid; } Bit_Set_256_Pair; bool bs256_pair_eq(Bit_Set_256_Pair pair1, Bit_Set_256_Pair pair2); #endif Bit_Set_256 dw_stabilized_buses_bs(Bit_Set_256 bs_prior, bool some_displays_disconnected); #ifdef WATCH_ASLEEP Bit_Set_256 ddc_i2c_check_bus_asleep( Bit_Set_256 bs_active_buses, Bit_Set_256 bs_sleepy_buses, GArray* events_queue); #endif void dw_emit_deferred_events(GArray * deferred_events); bool dw_hotplug_change_handler( Bit_Set_256 bs_buses_w_edid_removed, Bit_Set_256 bs_buses_w_edid_added, GArray * events_queue, GPtrArray * drefs_to_recheck); void init_dw_common(); #endif /* DW_COMMON_H_ */ ddcutil-2.2.0/src/dw/dw_dref.h0000644000175000001440000000140514754576332011624 /** @file dw_dref.h * Functions that modify persistent Display_Ref related data structures when * display connection and disconnection are detected. */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include "util/error_info.h" #include "base/displays.h" #include "base/i2c_bus_base.h" #ifndef DW_DREF_H_ #define DW_DREF_H_ void dw_add_display_ref(Display_Ref * dref); void dw_mark_display_ref_removed(Display_Ref* dref); Display_Ref* dw_add_display_by_businfo(I2C_Bus_Info * businfo); Display_Ref* dw_remove_display_by_businfo(I2C_Bus_Info * businfo); Error_Info* dw_recheck_dref(Display_Ref * dref); void init_dw_dref(); #endif /* DW_DREF_H_ */ ddcutil-2.2.0/src/dw/dw_main.h0000644000175000001440000000165314754576332011635 /** @file dw_main.h */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_MAIN_H_ #define DW_MAIN_H_ /** \cond */ #include #include "public/ddcutil_types.h" #include "util/error_info.h" /** \endcond */ extern DDC_Watch_Mode watch_displays_mode; extern bool enable_watch_displays; Error_Info * dw_start_watch_displays(DDCA_Display_Event_Class event_classes); DDCA_Status dw_stop_watch_displays(bool wait, DDCA_Display_Event_Class* enabled_classes); DDCA_Status dw_get_active_watch_classes(DDCA_Display_Event_Class * classes_loc); void dw_redetect_displays(); bool dw_is_watch_displays_executing(); void dw_get_display_watch_settings(DDCA_DW_Settings * settings_buffer); DDCA_Status dw_set_display_watch_settings(DDCA_DW_Settings * settings_buffer); void init_dw_main(); #endif /* DW_MAIN_H_ */ ddcutil-2.2.0/src/dw/dw_poll.h0000644000175000001440000000101414754576332011646 /** @file dw_poll.h */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_POLL_H_ #define DW_POLL_H_ #include extern int nonudev_poll_loop_millisec; extern int retry_thread_sleep_factor_millisec; extern bool stabilize_added_buses_w_edid; extern bool recheck_thread_active; // ?? needed? extern GMutex process_event_mutex; gpointer dw_watch_display_connections(gpointer data); void init_dw_poll(); #endif /* DW_POLL_H_ */ ddcutil-2.2.0/src/dw/dw_recheck.h0000644000175000001440000000055714754576332012317 /** @file dw_recheck.h */ // Copyright (C) 2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_RECHECK_H_ #define DW_RECHECK_H_ #include void dw_put_recheck_queue(Display_Ref* dref); gpointer dw_recheck_displays_func(gpointer data); void init_dw_recheck(); #endif /* DW_RECHECK_H_ */ ddcutil-2.2.0/src/dw/dw_services.h0000644000175000001440000000064614754576332012535 /** @file dw_services.h * * dw layer initialization and configuration, statistics management */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_SERVICES_H_ #define DW_SERVICES_H_ #include #include #include "public/ddcutil_types.h" void init_dw_services(); void terminate_dw_services(); #endif /* DW_SERVICES_H_ */ ddcutil-2.2.0/src/dw/dw_status_events.h0000644000175000001440000000351714754576332013621 /** @file dw_status_events.h */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_STATUS_EVENTS_H_ #define DW_STATUS_EVENTS_H_ #include "glib-2.0/glib.h" #include "public/ddcutil_types.h" #include "base/displays.h" typedef struct { DDCA_Display_Status_Callback_Func func; DDCA_Display_Status_Event event; } Callback_Queue_Entry; gpointer dw_execute_callback_func(gpointer data); // Display Status Events DDCA_Status dw_register_display_status_callback(DDCA_Display_Status_Callback_Func func); DDCA_Status dw_unregister_display_status_callback(DDCA_Display_Status_Callback_Func func); const char * dw_display_event_class_name(DDCA_Display_Event_Class class); const char* dw_display_event_type_name(DDCA_Display_Event_Type event_type); char * display_status_event_repr(DDCA_Display_Status_Event evt); char * display_status_event_repr_t(DDCA_Display_Status_Event evt); DDCA_Display_Status_Event dw_create_display_status_event(DDCA_Display_Event_Type event_type, const char * connector_name, Display_Ref* dref, DDCA_IO_Path io_path); void dw_emit_display_status_record(DDCA_Display_Status_Event evt); void dw_emit_or_queue_display_status_event(DDCA_Display_Event_Type event_type, const char * connector_name, Display_Ref* dref, DDCA_IO_Path io_path, GArray* queue); void init_dw_status_events(); #endif /* DW_STATUS_EVENTS_H_ */ ddcutil-2.2.0/src/dw/dw_udev.h0000644000175000001440000000100714754576332011645 /** @file dw_udev.h * Watch for monitor addition and removal using UDEV */ // Copyright (C) 2019-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_UDEV_H_ #define DW_UDEV_H_ /** \cond */ #include #include #include "public/ddcutil_types.h" /** \endcond */ extern bool use_sysfs_connector_id; extern bool report_udev_events; gpointer dw_watch_displays_udev(gpointer data); void init_dw_udev(); #endif /* DW_UDEV_H_ */ ddcutil-2.2.0/src/dw/dw_xevent.h0000644000175000001440000000154714754576332012224 /** @file dw_xevent.h */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DW_XEVENT_H_ #define DW_XEVENT_H_ #include #include typedef struct { Display* dpy; int screen; Window w; int rr_event_base; int rr_error_base; int screen_change_eventno; } XEvent_Data; void dw_dbgrpt_xevent_data(XEvent_Data* evdata, int depth); void dw_free_xevent_data(XEvent_Data * evdata); XEvent_Data * dw_init_xevent_screen_change_notification(); bool dw_detect_xevent_screen_change(XEvent_Data * evdata, int poll_interval); bool dw_next_X11_event_of_interest(XEvent_Data * evdata); void dw_send_x11_termination_message(XEvent_Data * evdata); void init_dw_xevent(); #endif /* DW_XEVENT_H_ */ ddcutil-2.2.0/src/dynvcp/0000775000175000001440000000000014754576332011014 5ddcutil-2.2.0/src/dynvcp/Makefile.am0000644000175000001440000000057614754153540012766 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libdynvcp.la libdynvcp_la_SOURCES = \ vcp_feature_set.c \ dyn_feature_set.c \ dyn_parsed_capabilities.c \ dyn_feature_codes.c \ dyn_feature_files.c ddcutil-2.2.0/src/dynvcp/Makefile.in0000664000175000001440000005153514754576155013015 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/dynvcp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libdynvcp_la_LIBADD = am_libdynvcp_la_OBJECTS = vcp_feature_set.lo dyn_feature_set.lo \ dyn_parsed_capabilities.lo dyn_feature_codes.lo \ dyn_feature_files.lo libdynvcp_la_OBJECTS = $(am_libdynvcp_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/dyn_feature_codes.Plo \ ./$(DEPDIR)/dyn_feature_files.Plo \ ./$(DEPDIR)/dyn_feature_set.Plo \ ./$(DEPDIR)/dyn_parsed_capabilities.Plo \ ./$(DEPDIR)/vcp_feature_set.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libdynvcp_la_SOURCES) DIST_SOURCES = $(libdynvcp_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libdynvcp.la libdynvcp_la_SOURCES = \ vcp_feature_set.c \ dyn_feature_set.c \ dyn_parsed_capabilities.c \ dyn_feature_codes.c \ dyn_feature_files.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/dynvcp/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/dynvcp/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libdynvcp.la: $(libdynvcp_la_OBJECTS) $(libdynvcp_la_DEPENDENCIES) $(EXTRA_libdynvcp_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libdynvcp_la_OBJECTS) $(libdynvcp_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dyn_feature_codes.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dyn_feature_files.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dyn_feature_set.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dyn_parsed_capabilities.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vcp_feature_set.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/dyn_feature_codes.Plo -rm -f ./$(DEPDIR)/dyn_feature_files.Plo -rm -f ./$(DEPDIR)/dyn_feature_set.Plo -rm -f ./$(DEPDIR)/dyn_parsed_capabilities.Plo -rm -f ./$(DEPDIR)/vcp_feature_set.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/dyn_feature_codes.Plo -rm -f ./$(DEPDIR)/dyn_feature_files.Plo -rm -f ./$(DEPDIR)/dyn_feature_set.Plo -rm -f ./$(DEPDIR)/dyn_parsed_capabilities.Plo -rm -f ./$(DEPDIR)/vcp_feature_set.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/dynvcp/vcp_feature_set.c0000644000175000001440000002263014754153540014247 /** @file vcp_feature_set.c */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include "util/debug_util.h" #include "util/report_util.h" /** \endcond */ #include "base/core.h" #include "base/rtti.h" #include "dynvcp/vcp_feature_set.h" // Default trace class for this file // static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_VCP; /* Free only synthetic VCP_Feature_Table_Entrys, * not ones in the permanent data structure. */ void free_transient_vcp_entry(gpointer ptr) { // DBGMSG("Starting. ptr=%p", ptr); assert(ptr); VCP_Feature_Table_Entry * pfte = (VCP_Feature_Table_Entry *) ptr; // DBGMSG("pfte=%p, marker = %.4s %s", pfte, pfte->marker, hexstring(pfte->marker,4)); assert(memcmp(pfte->marker, VCP_FEATURE_TABLE_ENTRY_MARKER, 4) == 0); if (pfte->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { free_synthetic_vcp_entry(pfte); } } void free_vcp_feature_set(VCP_Feature_Set * pset) { if (pset) { assert( memcmp(pset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); if (pset->members) { g_ptr_array_set_free_func(pset->members, free_transient_vcp_entry); g_ptr_array_free(pset->members, true); } free(pset); } } VCP_Feature_Table_Entry * get_vcp_feature_set_entry( VCP_Feature_Set * fset, unsigned index) { assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); VCP_Feature_Table_Entry * ventry = NULL; if (index < fset->members->len) // n. index is unsigned, no need to test if >= 0 ventry = g_ptr_array_index(fset->members,index); return ventry; } int get_vcp_feature_set_size(VCP_Feature_Set * fset) { assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); return fset->members->len; } void report_vcp_feature_set(VCP_Feature_Set* fset, int depth) { assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); int ndx = 0; for (; ndx < fset->members->len; ndx++) { VCP_Feature_Table_Entry * vcp_entry = NULL; vcp_entry = g_ptr_array_index(fset->members,ndx); rpt_vstring(depth, "VCP code: %02X: %s", vcp_entry->code, get_non_version_specific_feature_name(vcp_entry) ); } } void dbgrpt_vcp_feature_set(VCP_Feature_Set* fset, int depth) { rpt_structure_loc("VCP_Feature_Set",fset,depth); int d1 = depth+1; int d2 = depth+2; assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); rpt_vstring(depth, "Subset: %d (%s)", fset->subset, feature_subset_name(fset->subset)); if (fset->members->len == 0) rpt_label(d1, "No members"); else { for (int ndx = 0; ndx < fset->members->len; ndx++) { VCP_Feature_Table_Entry * vcp_entry = g_ptr_array_index(fset->members,ndx); rpt_vstring(d1, "VCP code: %02X: %s", vcp_entry->code, get_non_version_specific_feature_name(vcp_entry) ); char buf[50]; rpt_vstring(d2, "Global feature flags: 0x%04x - %s", vcp_entry->vcp_global_flags, vcp_interpret_global_feature_flags(vcp_entry->vcp_global_flags, buf, 50) ); } } } #ifdef OLD VCP_Feature_Set * create_feature_set0( VCP_Feature_Subset subset_id, GPtrArray * members) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Starting. subset_id=%d, number of members=%d", subset_id, (members) ? members->len : -1); struct vcp_feature_set * fset = calloc(1,sizeof(struct vcp_feature_set)); memcpy(fset->marker, VCP_FEATURE_SET_MARKER, 4); fset->subset = subset_id; fset->members = members; DBGTRC(debug, TRACE_GROUP, "Returning %p", fset); return fset; } #endif #ifdef UNUSED // used only for VCPINFO VCP_Feature_Set * create_single_feature_set_by_vcp_entry(VCP_Feature_Table_Entry * vcp_entry) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "vcp_entry=%p", vcp_entry); struct vcp_feature_set * fset = calloc(1,sizeof(struct vcp_feature_set)); assert(fset); // avoid coverity "Dereference before null check" warning memcpy(fset->marker, VCP_FEATURE_SET_MARKER, 4); fset->members = g_ptr_array_sized_new(1); fset->subset = VCP_SUBSET_SINGLE_FEATURE; g_ptr_array_add(fset->members, vcp_entry); if (debug || IS_TRACING()) { DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", fset); if (fset) dbgrpt_vcp_feature_set(fset, 1); } return fset; } #endif #ifdef UNUSED /* Creates a VCP_Feature_Set for a single VCP code * * \param id feature id * \param force indicates behavior if feature id not found in vcp_feature_table, * - if true, creates a feature set using a dummy feature table entry * - if false, returns NULL * \return feature set containing a single feature, * NULL if the feature not found and force not specified * * \remark used only for VCPINFO */ VCP_Feature_Set * create_single_feature_set_by_hexid(Byte id, bool force) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "id=0x%02x, force=%s", id, sbool(force)); struct vcp_feature_set * fset = NULL; VCP_Feature_Table_Entry* vcp_entry = NULL; if (force) vcp_entry = vcp_find_feature_by_hexid_w_default(id); else vcp_entry = vcp_find_feature_by_hexid(id); if (vcp_entry) fset = create_single_feature_set_by_vcp_entry(vcp_entry); if (debug || IS_TRACING()) { DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", fset); if (fset) dbgrpt_vcp_feature_set(fset, 1); } return fset; } #endif #ifdef OLD static inline struct vcp_feature_set * unopaque_feature_set( VCP_Feature_Set feature_set) { struct vcp_feature_set * fset = (struct vcp_feature_set *) feature_set; assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); return fset; } #endif #ifdef UNUSED void free_feature_set(VCP_Feature_Set * fset) { assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); int ndx = 0; // free all generated members for (; ndx < fset->members->len; ndx++) { VCP_Feature_Table_Entry * vcp_entry = NULL; vcp_entry = g_ptr_array_index(fset->members,ndx); if (vcp_entry->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { free_synthetic_vcp_entry(vcp_entry); } } fset->marker[3] = 'x'; free(fset); } #endif #ifdef UNUSED void replace_vcp_feature_set_entry( VCP_Feature_Set * fset, unsigned index, VCP_Feature_Table_Entry * new_entry) { assert(fset); assert(new_entry); assert (index < fset->members->len); if (index < fset->members->len) { VCP_Feature_Table_Entry * old_entry = g_ptr_array_index(fset->members, index); g_ptr_array_remove_index(fset->members, index); g_ptr_array_insert(fset->members, index, new_entry); if (old_entry->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { free_synthetic_vcp_entry(old_entry); } } } #endif #ifdef UNUSED VCP_Feature_Subset get_feature_set_subset_id(VCP_Feature_Set* fset) { assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); return fset->subset; } #endif #ifdef UNUSED void filter_feature_set( VCP_Feature_Set * fset, VCP_Feature_Set_Filter_Func func) { bool debug = false; assert(fset); for (int ndx = fset->members->len -1; ndx >= 0; ndx--) { VCP_Feature_Table_Entry * vcp_entry = NULL; vcp_entry = g_ptr_array_index(fset->members,ndx); if (!func(vcp_entry)) { DBGMSF(debug, "Removing entry"); // memory leak? g_ptr_array_remove_index(fset->members, ndx); if (vcp_entry->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { free_synthetic_vcp_entry(vcp_entry); } } } } #endif #ifdef UNUSED // replaced by feature_list_from_dyn_feature_set() // or, take DDCA_Feature_List address as parm DDCA_Feature_List feature_list_from_feature_set(VCP_Feature_Set * fset) { bool debug = false; if (debug || IS_TRACING()) { DBGMSG("Starting. feature_set = %p -> %s", (void*)fset, feature_subset_name(fset->subset)); show_backtrace(2); dbgrpt_vcp_feature_set(fset, 1); } DDCA_Feature_List vcplist = {{0}}; assert( fset && memcmp(fset->marker, VCP_FEATURE_SET_MARKER, 4) == 0); int ndx = 0; for (; ndx < fset->members->len; ndx++) { VCP_Feature_Table_Entry * vcp_entry = g_ptr_array_index(fset->members,ndx); feature_list_add(&vcplist, vcp_entry->code); #ifdef OLD // DBGMSG("Setting feature: 0x%02x", vcp_entry->code); int flagndx = vcp_code >> 3; int shiftct = vcp_code & 0x07; Byte flagbit = 0x01 << shiftct; // printf("(%s) vcp_code=0x%02x, flagndx=%d, shiftct=%d, flagbit=0x%02x\n", // __func__, vcp_code, flagndx, shiftct, flagbit); vcplist.bytes[flagndx] |= flagbit; // uint8_t bval = vcplist.bytes[flagndx]; // printf("(%s) vcplist.bytes[%d] = 0x%02x\n", __func__, flagndx, bval); #endif } if (debug || IS_TRACING()) { DBGMSG("Returning: %s", feature_list_string(&vcplist, "", " ")); // rpt_hex_dump(vcplist.bytes, 32, 1); } return vcplist; } #endif void init_vcp_feature_set() { } ddcutil-2.2.0/src/dynvcp/dyn_feature_set.c0000644000175000001440000010014214754153540014244 /** @file dyn_feature_set.c */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include "util/debug_util.h" #include "util/report_util.h" #include "util/traced_function_stack.h" #include "base/displays.h" #include "base/feature_lists.h" #include "base/feature_metadata.h" #include "base/feature_set_ref.h" #include "base/rtti.h" #include "vcp/vcp_feature_codes.h" #include "dynvcp/vcp_feature_set.h" #include "dynvcp/dyn_feature_set.h" static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_UDF; void free_dyn_feature_set(Dyn_Feature_Set * fset) { if (fset) { assert( memcmp(fset->marker, DYN_FEATURE_SET_MARKER, 4) == 0); if (fset->members_dfm) { g_ptr_array_set_free_func(fset->members_dfm, (GDestroyNotify) dfm_free); g_ptr_array_free(fset->members_dfm, true); } free(fset); } } void report_dyn_feature_set(Dyn_Feature_Set * fset, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fset=%p", fset); #ifdef TMI if (IS_DBGTRC(debug, TRACE_GROUP)) { if (fset) DBGMSG("marker = |%.4s| = %s", fset->marker, hexstring_t((unsigned char *)fset->marker, 4)); show_backtrace(1); debug_current_traced_function_stack(true); } #endif assert( fset && memcmp(fset->marker, DYN_FEATURE_SET_MARKER, 4) == 0); for (int ndx=0; ndx < fset->members_dfm->len; ndx++) { Display_Feature_Metadata * dfm_entry = g_ptr_array_index(fset->members_dfm,ndx); rpt_vstring(depth, "VCP code: %02X: %s", dfm_entry->feature_code, dfm_entry->feature_name); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } void dbgrpt_dyn_feature_set( Dyn_Feature_Set * fset, bool verbose, int depth) { int d0 = depth; int d1 = depth+1; rpt_vstring(d0, "Subset: %d (%s)", fset->subset, feature_subset_name(fset->subset)); rpt_label (d0, "Members (dfm):"); for (int ndx=0; ndx < fset->members_dfm->len; ndx++) { Display_Feature_Metadata * dfm = g_ptr_array_index(fset->members_dfm,ndx); if (verbose) dbgrpt_display_feature_metadata(dfm, d1); else rpt_vstring(d1, "0x%02x - %s", dfm->feature_code, dfm->feature_name); } } char * dyn_feature_set_repr_t(Dyn_Feature_Set * fset) { static GPrivate dynfs_repr_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&dynfs_repr_key, 200); snprintf(buf, 100, "[%s,%s]", feature_subset_name(fset->subset), dref_repr_t(fset->dref)); return buf; } static Display_Feature_Metadata * dyn_create_dynamic_feature_from_dfr_metadata(Dyn_Feature_Metadata * dfr_metadata) { bool debug = false; DBGMSF(debug, "Starting. id=0x%02x", dfr_metadata->feature_code); Display_Feature_Metadata * dfm = dfm_from_dyn_feature_metadata(dfr_metadata); if (dfr_metadata->version_feature_flags & DDCA_SIMPLE_NC) { if (dfr_metadata->sl_values) dfm->nontable_formatter_sl = dyn_format_feature_detail_sl_lookup; // HACK else dfm->nontable_formatter = format_feature_detail_sl_byte; } else if (dfr_metadata->version_feature_flags & DDCA_EXTENDED_NC) { if (dfr_metadata->sl_values) dfm->nontable_formatter_sl = dyn_format_feature_detail_sl_lookup_with_sh; // HACK else dfm->nontable_formatter = format_feature_detail_sh_sl_bytes; } else if (dfr_metadata->version_feature_flags & DDCA_STD_CONT) dfm->nontable_formatter = format_feature_detail_standard_continuous; else if (dfr_metadata->version_feature_flags & DDCA_TABLE) dfm->table_formatter = default_table_feature_detail_function; else dfm->nontable_formatter = format_feature_detail_debug_bytes; // pentry->vcp_global_flags = DDCA_SYNTHETIC; // indicates caller should free // pentry->vcp_global_flags |= DDCA_USER_DEFINED; assert(dfm); if (debug || IS_TRACING()) { DBGMSF(debug, "Done. Returning: %p", dfm); dbgrpt_display_feature_metadata(dfm, 1); } return dfm; } #ifdef UNUSED static Dyn_Feature_Metadata * dyn_create_feature_metadata_from_vcp_feature_table_entry( VCP_Feature_Table_Entry * pentry, DDCA_MCCS_Version_Spec vspec) { Display_Feature_Metadata * dfm = extract_version_feature_info_from_feature_table_entry(pentry, vspec, /*version_sensitive*/ true); if (pentry->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) free_synthetic_vcp_entry(pentry); Dyn_Feature_Metadata * meta = dfm_to_ddca_feature_metadata(dfm); dfm_free(dfm); return meta; } #endif #ifdef UNUSED Display_Feature_Metadata * dyn_create_dynamic_feature_from_vcp_feature_table_entry_dfm( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vspec) { assert(vfte); bool debug = false; DBGMSF(debug, "Starting. id=0x%02x", vfte->code); // Internal_Feature_Metadata * ifm = calloc(1, sizeof(Internal_Feature_Metadata)); Dyn_Feature_Metadata * meta = dyn_create_feature_metadata_from_vcp_feature_table_entry(vfte, vspec); Display_Feature_Metadata * dfm = dfm_from_dyn_feature_metadata(meta); free_ddca_feature_metadata(meta); free(meta); if (dfm->version_feature_flags & DDCA_SIMPLE_NC) { if (dfm->sl_values) dfm->nontable_formatter_sl = dyn_format_feature_detail_sl_lookup; else dfm->nontable_formatter = format_feature_detail_sl_byte; } else if (dfm->version_feature_flags & DDCA_STD_CONT) dfm->nontable_formatter = format_feature_detail_standard_continuous; else if (dfm->version_feature_flags & DDCA_TABLE) dfm->table_formatter = default_table_feature_detail_function; else dfm->nontable_formatter = format_feature_detail_debug_bytes; // pentry->vcp_global_flags = DDCA_SYNTHETIC; // indicates caller should free // pentry->vcp_global_flags |= DDCA_USER_DEFINED; assert(dfm); if (debug || IS_TRACING()) { DBGMSF(debug, "Done. Returning: %p", dfm); dbgrpt_display_feature_metadata(dfm, 1); } return dfm; } #endif static Dyn_Feature_Set * dyn_create_feature_set0( VCP_Feature_Subset subset_id, DDCA_Display_Ref display_ref, GPtrArray * members_dfm) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "subset_id=%d, number of members=%d", subset_id, (members_dfm) ? members_dfm->len : -1); Dyn_Feature_Set * fset = calloc(1,sizeof(Dyn_Feature_Set)); memcpy(fset->marker, DYN_FEATURE_SET_MARKER, 4); fset->subset = subset_id; fset->members_dfm = members_dfm; DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", fset); return fset; } static Dyn_Feature_Set * dyn_create_feature_set1( VCP_Feature_Subset subset_id, GPtrArray * members_dfm) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "subset_id=%d, number of members=%d", subset_id, (members_dfm) ? members_dfm->len : -1); Dyn_Feature_Set * fset = calloc(1,sizeof(Dyn_Feature_Set)); memcpy(fset->marker, DYN_FEATURE_SET_MARKER, 4); fset->subset = subset_id; fset->members_dfm = members_dfm; DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", fset); return fset; } /** * Selection criteria: * @param subset_id * @param feature_set_flags * * Feature code characteristics: * @param vcp_spec_groups spec groups to which the feature belongs * @param feature_flags feature code attributes * @param vcp_subsets subsets to which the feature code belongs * * @return true/false depending on whether the feature code satisfies * the selection criteria */ bool test_show_feature( VCP_Feature_Subset subset_id, Feature_Set_Flags feature_set_flags, gushort vcp_spec_groups, DDCA_Feature_Flags feature_flags, VCP_Feature_Subset vcp_subsets) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "subset_id=%d - %s, feature_set_flags=0x%02x - %s", subset_id, feature_subset_name(subset_id), feature_set_flags, feature_set_flag_names_t(feature_set_flags)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "vcp_spec_groups=0x%04x, feature_flags=%s, vcp_subsets=%s", vcp_spec_groups, feature_flags, vcp_subsets); bool showit = true; bool exclude_table_features = feature_set_flags & FSF_NOTABLE; if ((feature_flags & DDCA_TABLE) && exclude_table_features) showit = false; else { showit = false; switch(subset_id) { case VCP_SUBSET_PRESET: showit = vcp_spec_groups & VCP_SPEC_PRESET; break; case VCP_SUBSET_TABLE: showit = feature_flags & DDCA_TABLE; break; case VCP_SUBSET_CCONT: showit = feature_flags & DDCA_COMPLEX_CONT; break; case VCP_SUBSET_SCONT: showit = feature_flags & DDCA_STD_CONT; break; case VCP_SUBSET_CONT: showit = feature_flags & DDCA_CONT; break; case VCP_SUBSET_SNC: showit = feature_flags & DDCA_SIMPLE_NC; break; case VCP_SUBSET_XNC: showit = feature_flags & DDCA_EXTENDED_NC; break; case VCP_SUBSET_CNC: showit = feature_flags & (DDCA_COMPLEX_NC); break; case VCP_SUBSET_NC_CONT: showit = feature_flags & (DDCA_NC_CONT); break; case VCP_SUBSET_NC_WO: showit = feature_flags & (DDCA_WO_NC); break; case VCP_SUBSET_NC: showit = feature_flags & DDCA_NC; break; case VCP_SUBSET_KNOWN: // case VCP_SUBSET_ALL: // case VCP_SUBSET_SUPPORTED: showit = true; break; case VCP_SUBSET_COLOR: case VCP_SUBSET_PROFILE: case VCP_SUBSET_LUT: case VCP_SUBSET_TV: case VCP_SUBSET_AUDIO: case VCP_SUBSET_WINDOW: case VCP_SUBSET_DPVL: case VCP_SUBSET_CRT: showit = vcp_subsets & subset_id; break; case VCP_SUBSET_SCAN: // will never happen, inserted to avoid compiler warning case VCP_SUBSET_MFG: // will never happen case VCP_SUBSET_UDF: // will never happen case VCP_SUBSET_SINGLE_FEATURE: case VCP_SUBSET_MULTI_FEATURES: case VCP_SUBSET_NONE: break; } // switch if ( ( feature_set_flags & (FSF_RW_ONLY | FSF_RO_ONLY | FSF_WO_ONLY) ) && subset_id != VCP_SUBSET_SINGLE_FEATURE && subset_id != VCP_SUBSET_NONE) { if (feature_set_flags &FSF_RW_ONLY) { if (! (feature_flags & DDCA_RW) ) showit = false; } else if (feature_set_flags & FSF_RO_ONLY) { if (! (feature_flags & DDCA_RO) ) showit = false; } else if (feature_set_flags & FSF_WO_ONLY) { if (! (feature_flags & DDCA_WO) ) showit = false; } } if ( feature_flags & DDCA_TABLE) { // DBGMSF(debug, "Before final check for table feature. showit=%s", bool_repr(showit)); if (exclude_table_features) showit = false; // DBGMSF(debug, "After final check for table feature. showit=%s", bool_repr(showit)); } // if (showit) { // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding feature 0x%02x", feature_code); // g_ptr_array_add(members_dfm, dfm); // } } // if ( !(feature_flags & DDCA_READABLE) ) if (feature_set_flags & FSF_READABLE_ONLY) { if ( !(feature_flags & DDCA_READABLE) ) showit = false; } DBGTRC_RET_BOOL(debug, TRACE_GROUP, showit, ""); return showit; } // #ifdef OLD /** Given a feature set id for a named feature set (i.e. other than * #VCP_Subset_Single_Feature), creates a #VCP_Feature_Set containing * the features in the set. * * @param subset_id feature subset id * @param vcp_version vcp version, for obtaining most appropriate feature information, * e.g. feature type can vary by MCCS version * @param flags flags to tailor execution * @return feature set listing the features in the set * * @remark * For #VCP_SUBSET_SCAN, whether Table type features are included is controlled * by flag FSF_NOTABLE. * @remark * For remaining subset ids, the following flags apply: * - FSF_NOTABLE - if set, ignore Table type features * (Exception: For #VCP_SUBSET_TABLE and #VCP_SUBSET_LUT, flags #FSF_TABLE is ignored.) * - FSF_RW_ONLY, FSF_RO_ONLY, FSF_WO_ONLy - filter feature ids by whether they are * RW, RO, or WO */ VCP_Feature_Set * create_vcp_feature_set( VCP_Feature_Subset subset_id, DDCA_MCCS_Version_Spec vcp_version, Feature_Set_Flags feature_setflags) { assert(subset_id); assert(subset_id != VCP_SUBSET_SINGLE_FEATURE); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "subset_id=%s(0x%04x), vcp_version=%d.%d, flags=%s", feature_subset_name(subset_id), subset_id, vcp_version.major, vcp_version.minor, feature_set_flag_names_t(feature_setflags)); // if (IS_DBGTRC(debug, TRACE_GROUP)) { // show_backtrace(2); // } bool exclude_table_features = feature_setflags & FSF_NOTABLE; struct vcp_feature_set * fset = calloc(1,sizeof(struct vcp_feature_set)); memcpy(fset->marker, VCP_FEATURE_SET_MARKER, 4); fset->subset = subset_id; fset->members = g_ptr_array_sized_new(250); if (subset_id == VCP_SUBSET_SCAN || subset_id == VCP_SUBSET_MFG) { int ndx = 1; if (subset_id == VCP_SUBSET_MFG) ndx = 0xe0; for (; ndx < 256; ndx++) { Byte id = ndx; // DBGMSF(debug, "examining id 0x%02x", id); // n. this is a pointer into permanent data structures, should not be freed: VCP_Feature_Table_Entry* vcp_entry = vcp_find_feature_by_hexid(id); // original code looks at VCP2_READABLE, output level if (vcp_entry) { bool showit = true; if ( is_table_feature_by_vcp_version(vcp_entry, vcp_version) ) { if ( /* get_output_level() < DDCA_OL_VERBOSE || */ exclude_table_features ) showit = false; } if (!is_feature_readable_by_vcp_version(vcp_entry, vcp_version)) { showit = false; } if (showit) { g_ptr_array_add(fset->members, vcp_entry); } } else { // unknown feature or manufacturer specific feature g_ptr_array_add(fset->members, vcp_create_dummy_feature_for_hexid(id)); if (ndx >= 0xe0 && (get_output_level() >= DDCA_OL_VERBOSE && !exclude_table_features) ) { // for manufacturer specific features, probe as both table and non-table // Only probe table if --verbose, output is confusing otherwise g_ptr_array_add(fset->members, vcp_create_table_dummy_feature_for_hexid(id)); } } } } else { if (subset_id == VCP_SUBSET_TABLE || subset_id == VCP_SUBSET_LUT) { exclude_table_features = false; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Reset exclude_table_features = %s", SBOOL(exclude_table_features)); } int known_feature_ct = vcp_get_feature_code_count(); int ndx = 0; for (ndx=0; ndx < known_feature_ct; ndx++) { VCP_Feature_Table_Entry * vcp_entry = vcp_get_feature_table_entry(ndx); assert(vcp_entry); DDCA_Version_Feature_Flags vflags = get_version_sensitive_feature_flags(vcp_entry, vcp_version); bool showit = test_show_feature( subset_id, feature_setflags, vcp_entry->vcp_spec_groups, vflags, vcp_entry->vcp_subsets); if (showit) { g_ptr_array_add(fset->members, vcp_entry); } } } assert(fset); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", fset); if (IS_DBGTRC(debug, TRACE_GROUP)) dbgrpt_vcp_feature_set(fset, 1); return fset; } // #endif Dyn_Feature_Set * dyn_create_feature_set( VCP_Feature_Subset subset_id, DDCA_Display_Ref display_ref, Feature_Set_Flags feature_set_flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "subset_id=%d - %s, dref=%s, feature_setflags=0x%02x - %s", subset_id, feature_subset_name(subset_id), dref_repr_t(display_ref), feature_set_flags, feature_set_flag_names_t(feature_set_flags)); Dyn_Feature_Set * result = NULL; Display_Ref * dref = NULL; if (display_ref) { dref = (Display_Ref *) display_ref; assert(memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); } else { feature_set_flags &= ~FSF_CHECK_UDF; } GPtrArray * members_dfm = g_ptr_array_new(); bool exclude_table_features = feature_set_flags & FSF_NOTABLE; if (subset_id == VCP_SUBSET_UDF) { // all user defined features DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "VCP_SUBSET_UDF path"); if ( (feature_set_flags&FSF_CHECK_UDF) && dref && dref->dfr) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE,"dref->dfr is set"); GHashTableIter iter; gpointer hash_key; gpointer hash_value; g_hash_table_iter_init(&iter, dref->dfr->features); bool found = g_hash_table_iter_next(&iter, &hash_key, &hash_value); while (found) { Dyn_Feature_Metadata * feature_metadata = hash_value; assert( memcmp(feature_metadata, DDCA_FEATURE_METADATA_MARKER, 4) == 0 ); // Test Feature_Set_Flags other than FSF_SHOW_UNSUPPORTED, // which does not apply in this context bool include = true; // Feature_Set_Flags //DDCA_Feature_Flags if ( ((feature_set_flags & FSF_NOTABLE) && (feature_metadata->version_feature_flags & DDCA_TABLE)) || ((feature_set_flags & FSF_RO_ONLY) && !(feature_metadata->version_feature_flags & DDCA_RO) ) || ((feature_set_flags & FSF_RW_ONLY) && !(feature_metadata->version_feature_flags & DDCA_RW) ) || ((feature_set_flags & FSF_WO_ONLY) && !(feature_metadata->version_feature_flags & DDCA_WO) ) ) include = false; if (include) { Display_Feature_Metadata * dfm = dyn_create_dynamic_feature_from_dfr_metadata(feature_metadata); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding feature 0x%02x", dfm->feature_code); g_ptr_array_add(members_dfm, dfm); } found = g_hash_table_iter_next(&iter, &hash_key, &hash_value); } } // if (dref->dfr) // result = dyn_create_feature_set0(subset_id, display_ref, members_dfm); result = dyn_create_feature_set1(subset_id, members_dfm); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "VCP_SUBSET_UDF complete"); } // VCP_SUBSET_DYNAMIC else if (subset_id == VCP_SUBSET_SCAN || subset_id == VCP_SUBSET_MFG) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "VSP_SUBSET_SCAN or VCP_SUBSET_MFG"); int ndx = 1; if (subset_id == VCP_SUBSET_MFG) ndx = 0xe0; for (; ndx < 256; ndx++) { Byte feature_code = ndx; // DBGMSF(debug, "examining id 0x%02x", id); // n. this is a pointer into permanent data structures, should not be freed: //VCP_Feature_Table_Entry* vcp_entry = vcp_find_feature_by_hexid(id); Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dref( feature_code, dref, feature_set_flags & FSF_CHECK_UDF, true); // with_default bool showit = true; if (!(dfm->version_feature_flags & DDCA_READABLE)) { showit = false; } #ifdef OUT if (feature_set_flags & FSF_RO_ONLY) { if ( !(dfm->version_feature_flags & DDCA_READABLE) ) showit = false; } #endif if ((dfm->version_feature_flags & DDCA_TABLE) && exclude_table_features) { //if ( /* get_output_level() < DDCA_OL_VERBOSE || */ exclude_table_features) { showit = false; } if (showit) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding feature 0x%02x", dfm->feature_code); g_ptr_array_add(members_dfm, dfm); } else dfm_free(dfm); #ifdef NO else { // unknown feature or manufacturer specific feature g_ptr_array_add(fset->members, vcp_create_dummy_feature_for_hexid(id)); if (ndx >= 0xe0 && (get_output_level() >= DDCA_OL_VERBOSE && !exclude_table_features) ) { // for manufacturer specific features, probe as both table and non-table // Only probe table if --verbose, output is confusing otherwise g_ptr_array_add(fset->members, vcp_create_table_dummy_feature_for_hexid(id)); } } #endif } // for // result = dyn_create_feature_set0(subset_id, display_ref, members_dfm); result = dyn_create_feature_set1(subset_id, members_dfm); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "VCP_SUBSET_SCAN or VCP_SUBSET_MFG complete"); } // VCP_SUBSET_SCAN else { // (subset_id != VCP_SUBSET_DYNAMIC, != VCP_SUBSET_SCAN DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "subset=id = %s", feature_subset_name(subset_id)); if (subset_id == VCP_SUBSET_TABLE || subset_id == VCP_SUBSET_LUT) { exclude_table_features = false; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Reset exclude_table_features = %s", SBOOL(exclude_table_features)); } for (int feature_code = 0; feature_code < 256; feature_code++) { Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dref( feature_code, dref, feature_set_flags & FSF_CHECK_UDF, false); // with_default if (dfm) { bool showit = test_show_feature( subset_id, feature_set_flags, dfm->vcp_spec_groups, dfm->version_feature_flags, dfm->vcp_subsets); if (showit) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Adding feature 0x%02x", dfm->feature_code); g_ptr_array_add(members_dfm, dfm); } else dfm_free(dfm); } } // result = dyn_create_feature_set0(subset_id, display_ref, members_dfm); result = dyn_create_feature_set1(subset_id, members_dfm); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", result); if (debug && result) dbgrpt_dyn_feature_set(result, false, 1); return result; } /** Creates a VCP_Feature_Set from a feature set reference. * * \param fsref external feature set reference * \param vcp_version * \param flags checks only FSF_FORCE * * \return feature set, NULL if not found * * @remark * If creating a #VCP_Feature_Set containing a single specified feature, * flag #FSF_FORCE controls whether a feature set is created for an * unrecognized feature. * @remark * If creating a named feature set, see called function #create_feature_set_ref() * for the effect of #FSF_FORCE and other flags. * @remark * Used only for VCPINFO */ Dyn_Feature_Set * create_dyn_feature_set_from_feature_set_ref( Feature_Set_Ref * fsref, DDCA_MCCS_Version_Spec vcp_version, Feature_Set_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP,"fsref=%s, vcp_version=%d.%d. flags=%s", fsref_repr_t(fsref), vcp_version.major, vcp_version.minor, feature_set_flag_names_t(flags)); Dyn_Feature_Set * fset = NULL; assert(!(flags & FSF_CHECK_UDF)); if (fsref->subset == VCP_SUBSET_SINGLE_FEATURE || fsref->subset == VCP_SUBSET_MULTI_FEATURES) { fset = calloc(1,sizeof(Dyn_Feature_Set)); assert(fset); // avoid coverity "Dereference before null check" warning memcpy(fset->marker, DYN_FEATURE_SET_MARKER, 4); fset->members_dfm = g_ptr_array_sized_new(1); fset->subset = fsref->subset; Bit_Set_256_Iterator iter = bs256_iter_new(fsref->features); int feature_code = -1; while ( (feature_code = bs256_iter_next(iter)) >= 0 ) { Byte hexid = (Byte) feature_code; // Display_Feature_Metadata * vcp_entry = vcp_find_feature_by_hexid_w_default(hexid); Display_Feature_Metadata * dfm_entry = dyn_get_feature_metadata_by_dref( hexid, NULL, flags & FSF_CHECK_UDF, false); // with_default g_ptr_array_add(fset->members_dfm, dfm_entry); } bs256_iter_free(iter); } else { fset = dyn_create_feature_set(fsref->subset, NULL, flags); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning fset %p", fset); if (IS_DBGTRC(debug, TRACE_GROUP)) dbgrpt_dyn_feature_set(fset, false, 1); return fset; } /** Creates a VCP_Feature_Set from a feature set reference. * * \param fsref external feature set reference * \param vcp_version * \param flags checks only FSF_FORCE * * \return feature set, NULL if not found * * @remark * If creating a #VCP_Feature_Set containing a single specified feature, * flag #FSF_FORCE controls whether a feature set is created for an * unrecognized feature. * @remark * If creating a named feature set, see called function #create_feature_set_ref() * for the effect of #FSF_FORCE and other flags. * @remark * Used only for VCPINFO */ VCP_Feature_Set * create_vcp_feature_set_from_feature_set_ref( Feature_Set_Ref * fsref, DDCA_MCCS_Version_Spec vcp_version, Feature_Set_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP,"fsref=%s, vcp_version=%d.%d. flags=%s", fsref_repr_t(fsref), vcp_version.major, vcp_version.minor, feature_set_flag_names_t(flags)); struct vcp_feature_set * fset = NULL; #ifdef OLD if (fsref->subset == VCP_SUBSET_SINGLE_FEATURE) { // fset = create_single_feature_set_by_hexid(fsref->specific_feature, flags & FSF_FORCE); int feature_code = bs256_first_bit_set(fsref->features); assert(feature_code >= 0); fset = create_single_feature_set_by_hexid((Byte)feature_code, flags & FSF_FORCE); } else if (fsref->subset == VCP_SUBSET_MULTI_FEATURES) { #endif if (fsref->subset == VCP_SUBSET_SINGLE_FEATURE || fsref->subset == VCP_SUBSET_MULTI_FEATURES) { fset = calloc(1,sizeof(struct vcp_feature_set)); assert(fset); // avoid coverity "Dereference before null check" warning memcpy(fset->marker, VCP_FEATURE_SET_MARKER, 4); fset->members = g_ptr_array_sized_new(1); fset->subset = fsref->subset; Bit_Set_256_Iterator iter = bs256_iter_new(fsref->features); int feature_code = -1; while ( (feature_code = bs256_iter_next(iter)) >= 0 ) { Byte hexid = (Byte) feature_code; VCP_Feature_Table_Entry* vcp_entry = vcp_find_feature_by_hexid_w_default(hexid); g_ptr_array_add(fset->members, vcp_entry); } bs256_iter_free(iter); } else { fset = create_vcp_feature_set(fsref->subset, vcp_version, flags); } DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "Vcp_Feature_Set", dbgrpt_vcp_feature_set, fset); return fset; } #ifdef UNUSED Dyn_Feature_Set * dyn_create_single_feature_set_by_hexid2( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref display_ref, bool force) { bool debug = false; DBGMSF(debug, "feature_code=0x%02x, display_ref=%s, force=%s", feature_code, dref_repr_t(display_ref), sbool(force)); Display_Ref * dref = (Display_Ref *) display_ref; assert( dref && memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); Dyn_Feature_Set * result = calloc(1, sizeof(Dyn_Feature_Set)); memcpy(result->marker, DYN_FEATURE_SET_MARKER, 4); result->dref = dref; result->subset = VCP_SUBSET_SINGLE_FEATURE; result->members_dfm = g_ptr_array_new(); Display_Feature_Metadata * dfm = NULL; if (dref->dfr) { DDCA_Featurfree_dfm_funce_Metadata * feature_metadata = get_dynamic_feature_metadata(dref->dfr, feature_code); if (feature_metadata) { dfm = dyn_create_dynamic_feature_from_dfr_metadata(feature_metadata); } } if (!dfm) { VCP_Feature_Table_Entry* vcp_entry = NULL; if (force) vcp_entry = vcp_find_feature_by_hexid_w_default(feature_code); else vcp_entry = vcp_find_feature_by_hexid(feature_code); if (vcp_entry) dfm = dyn_create_dynamic_feature_from_vcp_feature_table_entry_dfm( vcp_entry, get_vcp_version_by_dref(dref) ); // dref->vcp_version); } if (dfm) g_ptr_array_add(result->members_dfm, dfm); else { // free_dyn_feature_set(result) ?? // result = NULL ?? } DBGMSF(debug, "Done. Returning %p", result); return result; } #endif // replaces // VCP_Feature_Table_Entry * get_feature_set_entry(VCP_Feature_Set feature_set, unsigned index); Display_Feature_Metadata * dyn_get_feature_set_entry( Dyn_Feature_Set * feature_set, unsigned index) { assert(feature_set && feature_set->members_dfm); Display_Feature_Metadata * result = NULL; if (index < feature_set->members_dfm->len) result = g_ptr_array_index(feature_set->members_dfm, index); return result; } // replaces // int get_feature_set_size(VCP_Feature_Set feature_set); int dyn_get_feature_set_size( Dyn_Feature_Set * feature_set) { // show_backtrace(2); assert(feature_set); assert(feature_set->members_dfm); int result = feature_set->members_dfm->len; return result; } #ifdef UNUSED Dyn_Feature_Set * dyn_create_feature_set_from_feature_set_ref2( Feature_Set_Ref * fsref, DDCA_Display_Ref dref, Feature_Set_Flags flags) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Starting. fsref=%s, dref=%s, flags=%s", fsref_repr_t(fsref), dref_repr_t(dref), interpret_feature_flags_t(flags)); Dyn_Feature_Set* result = NULL; if (fsref->subset == VCP_SUBSET_SINGLE_FEATURE) { // iftests within function result = dyn_create_single_feature_set_by_hexid2(fsref->specific_feature, dref, flags & FSF_FORCE); } else { result = dyn_create_feature_set(fsref->subset, dref, flags); } if (debug || IS_TRACING()) { DBGMSG("Returning VCP_Feature_Set %p", result); if (result) dbgrpt_dyn_feature_set(result, true, 1); } return result; } #endif void dyn_free_feature_set( Dyn_Feature_Set * feature_set) { bool debug = false; DBGMSF(debug, "Starting. feature_set=%s", dyn_feature_set_repr_t(feature_set)); if (feature_set->members_dfm) { g_ptr_array_set_free_func(feature_set->members_dfm, (GDestroyNotify) dfm_free); g_ptr_array_free(feature_set->members_dfm,true); } free(feature_set); DBGMSF(debug, "Done"); } void init_dyn_feature_set() { RTTI_ADD_FUNC(dyn_create_feature_set0); RTTI_ADD_FUNC(dyn_create_feature_set); // RTTI_ADD_FUNC(create_vcp_feature_set); RTTI_ADD_FUNC(create_vcp_feature_set_from_feature_set_ref); RTTI_ADD_FUNC(report_dyn_feature_set); } ddcutil-2.2.0/src/dynvcp/dyn_parsed_capabilities.c0000644000175000001440000006055014754153540015735 /** @file dyn_parsed_capabilities.c * * Report parsed capabilities, taking into account dynamic feature definitions. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include "util/data_structures.h" #include "util/report_util.h" #include "util/string_util.h" /** \endcond */ #include "base/core.h" #include "base/ddc_command_codes.h" #include "base/displays.h" #include "base/rtti.h" #include "vcp/parsed_capabilities_feature.h" #include "vcp/vcp_feature_codes.h" #include "vcp/parse_capabilities.h" #include "vcp/parsed_capabilities_feature.h" #include "dynvcp/dyn_feature_codes.h" #include "dynvcp/dyn_feature_files.h" #include "dynvcp/dyn_parsed_capabilities.h" static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_VCP; /** Given a byte representing an absolute gamma value, as used in * feature x72 (gamma), format a string representation of that value. * * \param buf buffer in which to return formatted value * \param bufsz size of buffer * \param bgamma byte representing gamma * \return buf */ static char * format_absolute_gamma(char * buf, int bufsz, Byte bgamma) { int i_gamma = bgamma + 100; char sgamma1[10]; g_snprintf(sgamma1, 10, "%d", i_gamma); char * sgamma1_left = lsub(sgamma1, strlen(sgamma1)-2); char * sgamma1_right = substr(sgamma1, strlen(sgamma1)-2, 2); g_snprintf(buf, bufsz, "%s.%s", sgamma1_left, sgamma1_right); free(sgamma1_left); free(sgamma1_right); return buf; } /** Given a byte representing a relative gamma value, as used in * feature x72 (gamma), return a string representation of that value. * * \param relative_gamma byte representing gamma * \return string representation (do not free) */ static char * format_relative_gamma(Byte relative_gamma) { char * desc = NULL; switch(relative_gamma) { case 0x00: desc = "Display default gamma"; break; case 0x01: desc = "Default gamma - 0.1"; break; case 0x02: desc = "Default gamma - 0.2"; break; case 0x03: desc = "Default gamma - 0.3"; break; case 0x04: desc = "Default gamma - 0.4"; break; case 0x05: desc = "Default gamma - 0.5"; break; case 0x06: desc = "Default gamma - 0.6"; break; case 0x07: desc = "Default gamma - 0.7"; break; case 0x08: desc = "Default gamma - 0.8"; break; case 0x09: desc = "Default gamma - 0.9"; break; case 0x0a: desc = "Default gamma - 1.0"; break; case 0x11: desc = "Default gamma + 0.1"; break; case 0x12: desc = "Default gamma + 0.2"; break; case 0x13: desc = "Default gamma + 0.3"; break; case 0x14: desc = "Default gamma + 0.4"; break; case 0x15: desc = "Default gamma + 0.5"; break; case 0x16: desc = "Default gamma + 0.6"; break; case 0x17: desc = "Default gamma + 0.7"; break; case 0x18: desc = "Default gamma + 0.8"; break; case 0x19: desc = "Default gamma + 0.9"; break; case 0x1a: desc = "Default gamma + 1.0"; break; default: desc = "Invalid value"; } return desc; } /** Special handling for interpreting the "value" bytes for feature x72 (gamma). * * \param feature_value_bytes bytes to interpret * \param depth logical indentation depth * * \remark * The bytes parm needs to be Byte_Value_Arrary, not a Bit_Bytes_Flag * because the former returns the bytes in the order specified in the * capabilities string, whereas the latter effectively sorts them. */ static void report_gamma_capabilities( Byte_Value_Array feature_value_bytes, int depth) { bool debug = false; if (debug) { char * buf0 = bva_as_string(feature_value_bytes, true, " "); DBGMSG("feature_value_flags: %s", buf0); free(buf0); } int d0 = depth; Byte * bytes = bva_bytes(feature_value_bytes); int byte_ct = bva_length(feature_value_bytes); bool invalid_gamma_desc = false; bool relative_gamma = false; // meaningless default assignment to avoid subsequent -Werror=maybe-uninitialized error // when building for openSUSE_Leap_42.2 and openSUSE_Leap_42.3 under OBS // n. openSUSE_Leap_15.0 and openSUSE_Tumbleweed do not show this problem (2/2019) enum {gfull_range, glimited_range,gspecific_presets} gamma_mode = gfull_range; bool bypass_supported = false; char * absolute_tolerance_desc = "None"; Byte specific_gammas[256]; int specific_gamma_ct = 0; if (byte_ct < 3) { // rpt_vstring(d0, "Invalid gamma values descriptor"); invalid_gamma_desc = true; DBGMSF(debug, "Insufficient values, byte_ct=%d", byte_ct); goto bye; } // second value is always native gamma char s_native_gamma[10]; format_absolute_gamma(s_native_gamma, 10, bytes[1]); DBGMSF(debug, "native gamma: %s (bytes[1] = 0x%02x)", s_native_gamma, bytes[1]); // third value describes range and how many specific values follow switch( bytes[2] ) { case 0xff: case 0xfe: gamma_mode = gfull_range; bypass_supported = (bytes[2] == 0xff) ? false : true; if (byte_ct != 3) { invalid_gamma_desc = true; } break; case 0xfd: case 0xfc: gamma_mode = glimited_range; bypass_supported = (bytes[2] == 0xfd) ? false : true; if (byte_ct != 5) { invalid_gamma_desc = true; } else { specific_gammas[0] = bytes[3]; specific_gammas[1] = bytes[4]; specific_gamma_ct = 2; } break; case 0xfb: case 0xfa: gamma_mode = gspecific_presets; bypass_supported = (bytes[2] == 0xfb) ? false : true; if (byte_ct < 4) { invalid_gamma_desc = true; } else { specific_gamma_ct = byte_ct - 3; memcpy(specific_gammas, bytes+3, specific_gamma_ct); } break; default: invalid_gamma_desc = true; } // first byte indicates relative vs absolute adjustment, and // for absolute adjustment the tolerance if (bytes[0] == 0xff) { // relative adjustment DBGMSF(debug, "Relative adjustment (bytes[0] = 0x%02x)", bytes[0]); relative_gamma = true; } else { // absolute adjustment if ( bytes[0] <= 0x0a ) { switch (bytes[0]) { case 0x00: absolute_tolerance_desc = "ideal"; break; case 0x01: absolute_tolerance_desc = "+/- 1%"; break; case 0x02: absolute_tolerance_desc = "+/- 2%"; break; case 0x03: absolute_tolerance_desc = "+/- 3%"; break; case 0x04: absolute_tolerance_desc = "+/- 4%"; break; case 0x05: absolute_tolerance_desc = "+/- 5%"; break; case 0x06: absolute_tolerance_desc = "+/- 6%"; break; case 0x07: absolute_tolerance_desc = "+/- 7%"; break; case 0x08: absolute_tolerance_desc = "+/- 8%"; break; case 0x09: absolute_tolerance_desc = "+/- 9%"; break; default: assert(bytes[0] == 0x0a); absolute_tolerance_desc = ">= 10%"; break; } } else { absolute_tolerance_desc = "None specified"; } DBGMSF(debug, "absolute_tolerance: %s (bytes[0] = 0x%02x)", absolute_tolerance_desc, bytes[0]); } DBGMSF(debug, "Pre-output. invalid_gamma_desc=%s", sbool(invalid_gamma_desc)); if (invalid_gamma_desc) { goto bye; } char * range_name = NULL; switch(gamma_mode) { case gfull_range: range_name = "Full range"; break; case glimited_range: range_name = "Limited range"; break; case gspecific_presets: range_name = "Specific presets"; } rpt_vstring(d0, "%s of %s adjustment supported%s (%s0x%02x)", range_name, (relative_gamma) ? "relative" : "absolute", (bypass_supported) ? ", display has ability to bypass gamma correction" : "", (debug) ? "bytes[2]=" : "", bytes[2] ); if (!relative_gamma) { // absolute gamma rpt_vstring(d0, "Absolute tolerance: %s (%s=0x%02x)", absolute_tolerance_desc, (debug) ? "bytes[0]=" : "", bytes[0]); } rpt_vstring(d0, "Native gamma: %s (0x%02x)", s_native_gamma, bytes[1]); if (gamma_mode == glimited_range) { if (relative_gamma) { rpt_vstring(d0, "Lower: %s (0x%02x), Upper: %s (0x%02x)", format_relative_gamma(bytes[3]), bytes[3], format_relative_gamma(bytes[4]), bytes[4]); } else { // absolute gamma char sglower[10]; char sgupper[10]; rpt_vstring(d0, "Lower: %s (0x%02x), Upper: %s (0x%02x)", format_absolute_gamma(sglower, 10, bytes[3]), bytes[3], format_absolute_gamma(sgupper, 10, bytes[4]), bytes[4] ); } } else if (gamma_mode == gspecific_presets) { // process specific_gammas char * buf = g_strdup(""); char bgamma[10]; char * sgamma = NULL; for (int ndx = 0; ndx < specific_gamma_ct; ndx++) { Byte raw_gamma = specific_gammas[ndx]; if (relative_gamma) { sgamma = format_relative_gamma(raw_gamma); } else { // absolute gamma sgamma = format_absolute_gamma(bgamma, 10, raw_gamma); } char buf2[100]; g_snprintf(buf2, 100, "%s %s (0x%02x)", (ndx > 0) ? "," : "", sgamma, raw_gamma); char * bufold = buf; buf = g_strdup_printf("%s%s", bufold, buf2); free(bufold); } rpt_vstring(d0, "Specific presets: %s", buf); free(buf); } // g_specific_presets bye: if (invalid_gamma_desc) { char * buf0 = bva_as_string(feature_value_bytes, true, " "); rpt_vstring(d0, "Invalid gamma descriptor: %s", buf0); free(buf0); } } // From parsed_capabiliies_feature.c: /** Displays the contents of a #Capabilities_Feature_Record as part * of the **capabilities** command. * * Output is written to the #FOUT device. * * @param vfr pointer to #Capabilities_Feature_Record * @param dref display reference * @param vcp_version monitor VCP version, used in case feature * information is version specific, from parsed capabilities if possible * * @param depth logical indentation depth */ static void dyn_report_one_cap_feature( Capabilities_Feature_Record * vfr, Display_Ref * dref, DDCA_MCCS_Version_Spec vcp_version, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "vfr=%p, dref=%s, vcp_version=%d.%d", vfr, dref_repr_t(dref), vcp_version.major, vcp_version.minor); assert(vfr && memcmp(vfr->marker, CAPABILITIES_FEATURE_MARKER, 4) == 0); int d0 = depth; int d1 = depth+1; int d2 = depth+2; Dyn_Feature_Metadata* dfr_metadata = NULL; if (dref) { assert(dref->dfr); // will be dummy if no dfr read dfr_metadata = dyn_get_dynamic_feature_metadata(dref->dfr, vfr->feature_id); } if (dfr_metadata) { rpt_vstring(d0, "Feature: %02X (UDF:%s)", vfr->feature_id, dfr_metadata->feature_name); if ((dfr_metadata->version_feature_flags & (DDCA_SIMPLE_NC|DDCA_EXTENDED_NC)) && dfr_metadata->sl_values) { rpt_label(d1 , "UDF Values:"); DDCA_Feature_Value_Entry * cur = dfr_metadata->sl_values; while (cur->value_name) { rpt_vstring(d2, "%02x: %s", cur->value_code, cur->value_name); cur++; } } } else { rpt_vstring(d0, "Feature: %02X (%s)", vfr->feature_id, dyn_get_feature_name(vfr->feature_id, dref)); // n. handles dref == NULL // get_feature_name_by_id_and_vcp_version(vfr->feature_id, vcp_version)); DDCA_Output_Level ol = get_output_level(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "vfr->value_string=%p", vfr->value_string); if (ol >= DDCA_OL_VERBOSE && vfr->value_string) { rpt_vstring(d1, "Values (unparsed): %s", vfr->value_string); } // only BVA variant works because of feature x72 (gamma) #ifdef CFR_BVA // hex_dump((Byte*) vfr, sizeof(VCP_Feature_Record)); // if (vfr->values) // report_id_array(vfr->values, "Feature values:"); char * buf0 = NULL; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "vfr->values=%p", vfr->values); if (vfr->values) { if (vfr->feature_id == 0x72) { // special handling for feature x72 (gamma) report_gamma_capabilities(vfr->values, d1); } else { // Get the descriptions of the documented values for the feature DDCA_Feature_Value_Entry * feature_values = find_feature_values_for_capabilities(vfr->feature_id, vcp_version); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Feature values %sfound for feature 0x%02x", (feature_values) ? "" : "NOT ", vfr->feature_id); int ct = bva_length(vfr->values); if (feature_values) { // did we find descriptions for the features? if (ol >= DDCA_OL_VERBOSE) rpt_label(d1, "Values ( parsed):"); else rpt_label(d1 , "Values:"); int ndx = 0; for (; ndx < ct; ndx++) { Byte hval = bva_get(vfr->values, ndx); char * value_name = sl_value_table_lookup(feature_values, hval); if (!value_name) value_name = "Unrecognized value"; rpt_vstring(d2, "%02x: %s", hval, value_name); } } else { // no interpretation available, just show the values int required_size = 3 * ct; buf0 = malloc(required_size); char * bufend = buf0+required_size; char * pos = buf0; int ndx = 0; for (; ndx < ct; ndx++) { Byte hval = bva_get(vfr->values, ndx); snprintf(pos, bufend-pos, "%02X ", hval); pos = pos+3; } *(pos-1) = '\0'; if (ol >= DDCA_OL_VERBOSE) rpt_vstring(d1, "Values ( parsed): %s (interpretation unavailable)", buf0); else rpt_vstring(d1, "Values: %s (interpretation unavailable)", buf0); } } } // assert( streq(buf0, vfr->value_string)); if (buf0) free(buf0); #endif #ifdef CFR_BBF // WRONG: report_gamma_capabilities requires value bytes in order given in the // capabilities string, no way to get that from BitByteFlags DBGMSF(debug, "vfr->bbflags=%p", vfr->bbflags); if (vfr->bbflags) { // WRONG TEST, NOT A POINTER // Get the descriptions of the documented values for the feature DDCA_Feature_Value_Entry * feature_values = NULL; bool found_dynamic_feature = false; if (dref && dref->dfr) { DDCA_Feature_Metadata * dfr_metadata = dyn_get_dynamic_feature_metadata(dref->dfr, vfr->feature_id); if (dfr_metadata) { found_dynamic_feature = true; feature_values = dfr_metadata->sl_values; } } if (!found_dynamic_feature) { feature_values = find_feature_values_for_capabilities(vfr->feature_id, vcp_version); } DBGMSF(debug, "Feature values %sfound for feature 0x%02x", (feature_values) ? "" : "NOT ", vfr->feature_id); if (feature_values || vfr->feature_id == 0x72) { // did we find descriptions for the features? if (ol >= DDCA_OL_VERBOSE) rpt_vstring(d1, "Values ( parsed):"); else rpt_vstring(d1, "Values:"); char * dynamic_disclaimer = ""; if (found_dynamic_feature) dynamic_disclaimer = " (from user defined feature definition)"; if (vfr->feature_id == 0x72) { // special handling for gamma // WRONG: report_gamma_capabilities requires value bytes in order given in the // capabilities string, no way to get that from BitByteFlags report_gamma_capabilities(vfr->values, d2); } else { Byte_Bit_Flags iter = bbf_iter_new(vfr->bbflags); int nextval = -1; while ( (nextval = bbf_iter_next(iter)) >= 0) { assert(nextval < 256); char * value_name = sl_value_table_lookup(feature_values, nextval); if (!value_name) value_name = "Unrecognized value"; rpt_vstring(d2, "%02x: %s%s", nextval, value_name, dynamic_disclaimer); } bbf_iter_free(iter); } } else { // no interpretation available, just show the values char * buf1 = bbf_to_string(vfr->bbflags, NULL, 0); // allocate buffer if (ol >= DDCA_OL_VERBOSE) rpt_vstring(d1, "Values ( parsed): %s (interpretation unavailable)", buf1); else rpt_vstring(d1, "Values: %s (interpretation unavailable)", buf1); free(buf1); } } #endif } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // from vcp/parse_capabilities.c: // // Report parsed data structures // static void report_commands(Byte_Value_Array cmd_ids, int depth) { rpt_label(depth, "Commands:"); int ct = bva_length(cmd_ids); int ndx = 0; for (; ndx < ct; ndx++) { Byte hval = bva_get(cmd_ids, ndx); rpt_vstring(depth+1, "Op Code: %02X (%s)", hval, ddc_cmd_code_name(hval)); } } STATIC void dyn_report_cap_features( GPtrArray* features, // GPtrArray of Capabilities_Feature_Record Display_Ref * dref, DDCA_MCCS_Version_Spec vcp_version) // from parsed capabilities if possible { bool debug = false; int d0 = 0; int d1 = 1; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s, vcp_version=%s", dref_repr_t(dref), format_vspec(vcp_version)); // assert(dref); if (dref) { if (!(dref->flags & DREF_DYNAMIC_FEATURES_CHECKED)) { Monitor_Model_Key mmk = mmk_value_from_edid(dref->pedid); Error_Info * erec = dfr_load_by_mmk(mmk, &dref->dfr); if (erec) { if (erec->status_code != DDCRC_NOT_FOUND || debug) errinfo_report(erec,1); errinfo_free(erec); } dref->flags |= DREF_DYNAMIC_FEATURES_CHECKED; } } rpt_label(d0, "VCP Features:"); int ct = features->len; int ndx; for (ndx=0; ndx < ct; ndx++) { Capabilities_Feature_Record * vfr = g_ptr_array_index(features, ndx); DBGMSF(debug, "vfr = %p", vfr); dyn_report_one_cap_feature(vfr, dref, vcp_version, d1); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Reports the Parsed_Capabilities struct for human consumption. * * @param pcaps parsed capabilities * @param dh display handle, may be null * @param dref display reference, may be null * @param depth logical indentation depth * * Output is written to the current report destination. * * @remark * dh/dref alternatives are needed to avoid double open of already opened device * @remark * If **dh** is non-null, dref is set to dh->dref. */ void dyn_report_parsed_capabilities( Parsed_Capabilities * pcaps, Display_Handle * dh, Display_Ref * dref, int depth) { int d0 = depth; int d1 = depth+1; int d2 = depth+2; bool debug = false; assert(pcaps && memcmp(pcaps->marker, PARSED_CAPABILITIES_MARKER, 4) == 0); DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, dref=%s, pcaps->raw_cmds_segment_seen=%s, " "pcaps->commands=%p, pcaps->vcp_features=%p", dh_repr(dh), dref_repr_t(dref), sbool(pcaps->raw_cmds_segment_seen), pcaps->commands, pcaps->vcp_features); if (dh) dref = dh->dref; bool saved_prefix_report_output = rpt_set_ornamentation_enabled(false); bool has_error_messages = pcaps->messages && pcaps->messages->len > 0; DDCA_Output_Level output_level = get_output_level(); if (output_level >= DDCA_OL_VERBOSE || has_error_messages) { rpt_vstring(d0, "%s capabilities string: %s", (pcaps->raw_value_synthesized) ? "Synthesized unparsed" : "Unparsed", pcaps->raw_value); } if (has_error_messages) { rpt_label(d0, "Errors parsing capabilities string:"); for (int ndx = 0; ndx < pcaps->messages->len; ndx++) { rpt_label(d1, g_ptr_array_index(pcaps->messages, ndx)); } } rpt_vstring(d0, "Model: %s", (pcaps->model) ? pcaps->model : "Not specified"); bool damaged = false; assert( ( pcaps->mccs_version_string && !vcp_version_eq(pcaps->parsed_mccs_version, DDCA_VSPEC_UNQUERIED) ) || (!pcaps->mccs_version_string && vcp_version_eq(pcaps->parsed_mccs_version, DDCA_VSPEC_UNQUERIED) ) ); if (pcaps->mccs_version_string) { char * s = (vcp_version_eq(pcaps->parsed_mccs_version, DDCA_VSPEC_UNKNOWN)) ? " (invalid)" : ""; rpt_vstring(d0, "MCCS version: %s%s", pcaps->mccs_version_string, s); } else { rpt_vstring(d0, "MCCS version: Not specified"); } if (pcaps->commands) report_commands(pcaps->commands, d0); else { // not an error in the case of USB_IO, as the capabilities string was // synthesized and does not include a commands segment // also, HP LP2480zx does not have cmds segment if (pcaps->raw_cmds_segment_seen) damaged = true; } // if vcp version unspecified in capabilities string, use queried value DDCA_MCCS_Version_Spec vspec = pcaps->parsed_mccs_version; // if (true) { if ( vcp_version_eq(vspec, DDCA_VSPEC_UNKNOWN) || vcp_version_eq(vspec, DDCA_VSPEC_UNQUERIED)) { if (dh) vspec = get_vcp_version_by_dh(dh); else if (dref) vspec = get_vcp_version_by_dref(dref); } if (pcaps->vcp_features) { #ifdef X72_CAPABILITIES_TEST_CASES // for testing feature x72 gamma char * vstring = NULL; Capabilities_Feature_Record * cfr = NULL; vstring = "05 78 FB 50 64 78 8C"; cfr = new_capabilities_feature(0x72, vstring, strlen(vstring)); g_ptr_array_add(pcaps->vcp_features, cfr); vstring = "02 96 fe 50 a0"; cfr = new_capabilities_feature(0x72, vstring, strlen(vstring)); g_ptr_array_add(pcaps->vcp_features, cfr); vstring = "00 78 ff"; cfr = new_capabilities_feature(0x72, vstring, strlen(vstring)); g_ptr_array_add(pcaps->vcp_features, cfr); // invalid example in spec, inserted 3rd byte FB vstring = "FF 00 FB 01 03 05 07 09 11 13 15 17 19"; cfr = new_capabilities_feature(0x72, vstring, strlen(vstring)); g_ptr_array_add(pcaps->vcp_features, cfr); // invalid example in spec, 3rd byte should be bd or fc vstring = "FF 01 FC 05 15"; cfr = new_capabilities_feature(0x72, vstring, strlen(vstring)); g_ptr_array_add(pcaps->vcp_features, cfr); vstring = "FF 01 FE"; cfr = new_capabilities_feature(0x72, vstring, strlen(vstring)); g_ptr_array_add(pcaps->vcp_features, cfr); #endif dyn_report_cap_features(pcaps->vcp_features, dref, vspec); } else { // handle pathological case of 0 length capabilities string, e.g. Samsung S32D850T if (pcaps->raw_vcp_features_seen) damaged = true; } if (damaged) { // should use pcaps->caps_validity rpt_nl(); rpt_label(d0, "Capabilities string not completely parsed"); if (pcaps->messages && pcaps->messages->len > 0) { rpt_label(d1, "Errors:"); for (int ndx = 0; ndx < pcaps->messages->len; ndx++) { char * s = g_ptr_array_index(pcaps->messages, ndx); rpt_label(d2, s); } } } rpt_set_ornamentation_enabled(saved_prefix_report_output); DBGTRC_DONE(debug, TRACE_GROUP, ""); } void init_dyn_parsed_capabilities() { RTTI_ADD_FUNC(dyn_report_parsed_capabilities); RTTI_ADD_FUNC(dyn_report_cap_features); RTTI_ADD_FUNC(dyn_report_one_cap_feature); } ddcutil-2.2.0/src/dynvcp/dyn_feature_codes.c0000644000175000001440000005021414754153540014552 /** @file dyn_feature_codes.c * * Access VCP feature code descriptions at the DDC level in order to * incorporate user-defined per-monitor feature information. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include "util/report_util.h" /** \endcond */ #include "base/displays.h" #include "base/dynamic_features.h" #include "base/feature_metadata.h" #include "base/monitor_model_key.h" #include "base/rtti.h" #include "vcp/vcp_feature_codes.h" #include "dynvcp/dyn_feature_codes.h" #include "dynvcp/dyn_feature_files.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_UDF; /* Formats the name of a non-continuous feature whose value is returned in byte SL. * * Arguments: * code_info parsed feature data * value_table lookup table, if NULL, create generic name * buffer buffer in which to store output * bufsz buffer size * * Returns: * true if formatting successful, false if not */ bool dyn_format_feature_detail_sl_lookup( Nontable_Vcp_Value * code_info, DDCA_Feature_Value_Entry * value_table, char * buffer, int bufsz) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "code_info=%s", nontable_vcp_value_repr_t(code_info)); if (value_table) { char * s = sl_value_table_lookup(value_table, code_info->sl); if (!s) s = "Unrecognized value"; snprintf(buffer, bufsz,"%s (sl=0x%02x)", s, code_info->sl); } else snprintf(buffer, bufsz, "0x%02x", code_info->sl); // can only pass a variable, not an expression or constant, to DBGTRC_RET_BOOL() // because failure simulation may assign a new value to the variable bool result = true; DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, "*buffer=|%s|", buffer); return result; } /* Formats the name of a non-continuous feature whose value is returned in byte SL * and also byte SH * * Arguments: * code_info parsed feature data * value_table lookup table, if NULL, create generic name * buffer buffer in which to store output * bufsz buffer size * * Returns: * true if formatting successful, false if not */ bool dyn_format_feature_detail_sl_lookup_with_sh( Nontable_Vcp_Value * code_info, DDCA_Feature_Value_Entry * value_table, char * buffer, int bufsz) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "code_info=%s", nontable_vcp_value_repr_t(code_info)); if (value_table) { char * s = sl_value_table_lookup(value_table, code_info->sl); if (!s) s = "Unrecognized value"; g_snprintf(buffer, bufsz,"%s (sl=0x%02x), sh=0x%02x", s, code_info->sl, code_info->sh); } else g_snprintf(buffer, bufsz, "sh=0x%02x, sl=0x%02x", code_info->sh, code_info->sl); // can only pass a variable, not an expression or constant, to DBGTRC_RET_BOOL() // because failure simulation may assign a new value to the variable bool result = true; DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, "*buffer=|%s|", buffer); return result; } /** Returns a #Display_Feature_Metadata record for a specified feature, first * checking for a user supplied feature definition, and then from the internal * feature definition tables. * * @param feature_code feature code * @param dfr if non-NULL, points to Dynamic_Features_Record for the display * @param vspec VCP version of the display * @param with_default create default value if not found * @return Display_Feature_Metadata for the feature, caller must free, * NULL if feature not found either in the user supplied feature definitions * (Dynamic_Features_Record) or in the internal feature definitions */ Display_Feature_Metadata * dyn_get_feature_metadata_by_dfr_and_vspec_dfm( DDCA_Vcp_Feature_Code feature_code, Dynamic_Features_Rec * dfr, DDCA_MCCS_Version_Spec vspec, bool with_default) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "feature_code=0x%02x, dfr=%p, vspec=%d.%d, with_default=%s", feature_code, dfr, vspec.major, vspec.minor, sbool(with_default)); Display_Feature_Metadata * result = NULL; if (dfr) { Dyn_Feature_Metadata * dfr_metadata = dyn_get_dynamic_feature_metadata(dfr, feature_code); if (dfr_metadata) { result = dfm_from_dyn_feature_metadata(dfr_metadata); result->vcp_version = vspec; // ?? if (dfr_metadata->version_feature_flags & DDCA_SIMPLE_NC) { if (dfr_metadata->sl_values) result->nontable_formatter_sl = dyn_format_feature_detail_sl_lookup; // HACK else result->nontable_formatter = format_feature_detail_sl_byte; } else if (dfr_metadata->version_feature_flags & DDCA_EXTENDED_NC) { if (dfr_metadata->sl_values) result->nontable_formatter_sl = dyn_format_feature_detail_sl_lookup_with_sh; // HACK else result->nontable_formatter = format_feature_detail_sl_byte; } else if (dfr_metadata->version_feature_flags & DDCA_STD_CONT) result->nontable_formatter = format_feature_detail_standard_continuous; else if (dfr_metadata->version_feature_flags & DDCA_TABLE) result->table_formatter = default_table_feature_detail_function; else result->nontable_formatter = format_feature_detail_debug_bytes; } } if (!result) { // returns dref->vcp_version if already cached, queries monitor if not // DBGMSG("vspec=%d.%d", vspec.major, vspec.minor); VCP_Feature_Table_Entry * pentry = (with_default) ? vcp_find_feature_by_hexid_w_default(feature_code) : vcp_find_feature_by_hexid(feature_code); if (pentry) { result = extract_version_feature_info_from_feature_table_entry(pentry, vspec, /*version_sensitive*/ true); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) dbgrpt_vcp_entry(pentry, 2); if (result->version_feature_flags & DDCA_TABLE) { if (pentry->table_formatter) result->table_formatter = pentry->table_formatter; else { if (result->version_feature_flags & DDCA_NORMAL_TABLE) { result->table_formatter = default_table_feature_detail_function; } else if (result->version_feature_flags & DDCA_WO_TABLE) { // program logic error? result->table_formatter = NULL; } else { PROGRAM_LOGIC_ERROR("" "Neither DDCA_NORMAL_TABLE or DDCA_WO_TABLE set in meta->version_feature_flags"); } } } else if (result->version_feature_flags & DDCA_NON_TABLE) { if (result->version_feature_flags & DDCA_STD_CONT) { result->nontable_formatter = format_feature_detail_standard_continuous; // DBGMSG("DDCA_STD_CONT"); } else if (result->version_feature_flags & DDCA_SIMPLE_NC) { if (result->sl_values) { // DBGMSG("format_feature_detail_sl_lookup"); result->nontable_formatter = format_feature_detail_sl_lookup; } else { // DBGMSG("format_feature_detail_sl_byte"); result->nontable_formatter = format_feature_detail_sl_byte; } } else if (result->version_feature_flags & DDCA_EXTENDED_NC) { if (result->sl_values) { // DBGMSG("format_feature_detail_sl_lookup_with_sh"); result->nontable_formatter = format_feature_detail_sl_lookup_with_sh; } else { // DBGMSG("format_feature_detail_sh_sl_bytes"); result->nontable_formatter = format_feature_detail_sh_sl_bytes; } } else if (result->version_feature_flags & DDCA_WO_NC) { result->nontable_formatter = NULL; // but should never be called for this case } else { assert(result->version_feature_flags & (DDCA_COMPLEX_CONT | DDCA_COMPLEX_NC | DDCA_NC_CONT)); if (pentry->nontable_formatter) result->nontable_formatter = pentry->nontable_formatter; else result->nontable_formatter = format_feature_detail_debug_bytes; } } // DDCA_NON_TABLE else { assert (result->version_feature_flags & DDCA_DEPRECATED); result->nontable_formatter = format_feature_detail_debug_bytes; // ?? } if (pentry->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) free_synthetic_vcp_entry(pentry); } } DBGTRC_RET_STRUCT(debug, TRACE_GROUP, Display_Feature_Metadata, dbgrpt_display_feature_metadata, result); return result; } /** Returns a #Dynamic_Feature_Metadata record for a specified feature, first * checking for a user supplied feature definition using the specified * #DDCA_Monitor_Model_Key, and then from the internal feature definition tables. * * @param feature_code feature code * @param mmk monitor model key, if null do not check for user supplied feature def * @param vspec VCP version of the display * @param check_udf * @param with_default create default value if not found * @return Display_Feature_Metadata for the feature, caller must free, * NULL if feature not found either in the user supplied feature definitions * (Dynamic_Features_Record) or in the internal feature definitions * * @remark * Ensures user supplied features have been loaded by calling #dfr_load_by_mmk() */ Display_Feature_Metadata * dyn_get_feature_metadata_by_mmk_and_vspec( DDCA_Vcp_Feature_Code feature_code, Monitor_Model_Key mmk, DDCA_MCCS_Version_Spec vspec, bool check_udf, bool with_default) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "feature_code=0x%02x, mmk=%s, vspec=%d.%d, with_default=%s", feature_code, mmk_repr(mmk), vspec.major, vspec.minor, sbool(with_default)); Dynamic_Features_Rec * dfr = NULL; if (check_udf) { Error_Info * erec = dfr_load_by_mmk(mmk, &dfr); if (erec) { if (erec->status_code != DDCRC_NOT_FOUND || debug) errinfo_report(erec,1); errinfo_free(erec); } } Display_Feature_Metadata * result = dyn_get_feature_metadata_by_dfr_and_vspec_dfm(feature_code, dfr, vspec, with_default); if (dfr) dfr_free(dfr); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, Display_Feature_Metadata, dbgrpt_display_feature_metadata, result); return result; } /** Returns a #Display_Feature_Metadata record for a specified feature, first * checking for a user supplied feature definition, and then from the internal * feature definition tables. * * @param feature_code feature code * @param dref display reference * @oaram check_udf if true, first check for a user supplied feature definition * @param with_default create default value if not found * @return Display_Feature_Metadata for the feature, caller must free, * NULL if feature not found either in the user supplied feature definitions * (Dynamic_Features_Record) or in the internal feature definitions */ Display_Feature_Metadata * dyn_get_feature_metadata_by_dref( DDCA_Vcp_Feature_Code feature_code, Display_Ref * dref, bool check_udf, bool with_default) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "feature_code=0x%02x, dref=%s, check_udf=%s, with_default=%s", feature_code, dref_repr_t(dref), sbool(check_udf), sbool(with_default)); if (dref) DBGTRC_NOPREFIX(debug, TRACE_GROUP,"dref->dfr=%p, DREF_OPEN: %s", dref->dfr, sbool(dref->flags & DREF_OPEN)); DDCA_MCCS_Version_Spec vspec = DDCA_VSPEC_UNKNOWN; if (dref) get_vcp_version_by_dref(dref); Display_Feature_Metadata * result = dyn_get_feature_metadata_by_dfr_and_vspec_dfm( feature_code, (check_udf && dref) ? dref->dfr : NULL, vspec, with_default); if (result) result->display_ref = dref; DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "Display_Feature_Metadata", dbgrpt_display_feature_metadata, result); return result; } /** Returns a #Display_Feature_Metadata record for a specified feature, first * checking for a user supplied feature definition, and then from the internal * feature definition tables. * * @param feature_code feature code * @param dh display handle * @oaram check_udf if true, first check for a user supplied feature definition * @param with_default create default value if not found * @return Display_Feature_Metadata for the feature, caller must free, * NULL if feature not found either in the user supplied feature definitions * (Dynamic_Features_Record) or in the internal feature definitions */ Display_Feature_Metadata * dyn_get_feature_metadata_by_dh( DDCA_Vcp_Feature_Code id, Display_Handle * dh, bool check_udf, bool with_default) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "id=0x%02x, dh=%s, check_udf=%s, with_default=%s", id, dh_repr(dh), sbool(check_udf), sbool(with_default) ); // ensure dh->dref->vcp_version set without incurring additional open/close DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); // Display_Feature_Metadata * result = dyn_get_feature_metadata_by_dref_dfm(id, dh->dref, with_default); Display_Feature_Metadata * result = dyn_get_feature_metadata_by_dfr_and_vspec_dfm(id, (check_udf) ? dh->dref->dfr : NULL, vspec, with_default); if (result) result->display_ref = dh->dref; // needed? DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "Display_Feature_Metadata", dbgrpt_display_feature_metadata, result); return result; } // Functions that apply formatting bool dyn_format_nontable_feature_detail( Display_Feature_Metadata * dfm, // DDCA_MCCS_Version_Spec vcp_version, Nontable_Vcp_Value * code_info, char * buffer, int bufsz) { bool debug = false; DDCA_MCCS_Version_Spec vcp_version = dfm->vcp_version; DBGTRC_STARTING(debug, TRACE_GROUP, "Code=0x%02x, vcp_version=%d.%d", dfm->feature_code, vcp_version.major, vcp_version.minor); // assert(vcp_version_eq(dfm->vcp_version, vcp_version)); // check before eliminating vcp_version parm bool ok = false; buffer[0] = '\0'; if (dfm->nontable_formatter) { Format_Normal_Feature_Detail_Function ffd_func = dfm->nontable_formatter; // get_nontable_feature_detail_function(vfte, vcp_version); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Using normal feature detail function: %s", rtti_get_func_name_by_addr(ffd_func) ); ok = ffd_func(code_info, vcp_version, buffer, bufsz); } else if (dfm->nontable_formatter_sl) { Format_Normal_Feature_Detail_Function2 ffd_func = dfm->nontable_formatter_sl; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Using SL lookup feature detail function: %s", rtti_get_func_name_by_addr(ffd_func) ); ok = ffd_func(code_info, dfm->sl_values, buffer, bufsz); } else PROGRAM_LOGIC_ERROR("Neither nontable_formatter nor vcp_nontable_formatter set"); DBGTRC_RET_BOOL(debug, TRACE_GROUP, ok, "buffer=|%s|", buffer); return ok; } bool dyn_format_table_feature_detail( Display_Feature_Metadata * dfm, // DDCA_MCCS_Version_Spec vcp_version, Buffer * accumulated_value, char * * aformatted_data ) { DDCA_MCCS_Version_Spec vcp_version = dfm->vcp_version; Format_Table_Feature_Detail_Function ffd_func = dfm->table_formatter; // get_table_feature_detail_function(vfte, vcp_version); bool ok = ffd_func(accumulated_value, vcp_version, aformatted_data); return ok; } /* Given a feature table entry and a raw feature value, * return a formatted string interpretation of the value. * * Arguments: * vcp_entry vcp_feature_table_entry * vcp_version monitor VCP version * valrec feature value * aformatted_data location where to return formatted string value * * Returns: * true if formatting successful, false if not * * It is the caller's responsibility to free the returned string. */ bool dyn_format_feature_detail( Display_Feature_Metadata * dfm, DDCA_MCCS_Version_Spec vcp_version, DDCA_Any_Vcp_Value * valrec, char * * aformatted_data ) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "valrec: "); if (debug || IS_TRACING() ) { dbgrpt_single_vcp_value(valrec, 2); } bool ok = true; *aformatted_data = NULL; // DBGTRC(debug, TRACE_GROUP, "valrec->value_type = %d", valrec->value_type); if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "DDCA_NON_TABLE_VCP_VALUE"); Nontable_Vcp_Value* nontable_value = single_vcp_value_to_nontable_vcp_value(valrec); char workbuf[200]; ok = dyn_format_nontable_feature_detail( dfm, // vcp_version, nontable_value, workbuf, 200); free(nontable_value); if (ok) { *aformatted_data = g_strdup(workbuf); } } else { // TABLE_VCP_CALL DBGTRC_NOPREFIX(debug, TRACE_GROUP, "DDCA_TABLE_VCP_VALUE"); ok = dyn_format_table_feature_detail( dfm, // cp_version, buffer_new_with_value(valrec->val.t.bytes, valrec->val.t.bytect, __func__), aformatted_data); } DBGTRC_RET_BOOL(debug, TRACE_GROUP, ok, "*aformatted_data=%s", *aformatted_data); assert( (ok && *aformatted_data) || (!ok && !*aformatted_data) ); return ok; } char * dyn_get_feature_name( Byte feature_code, Display_Ref * dref) { bool debug = false; DBGMSF(debug, "feature_code=0x%02x, dref=%s", feature_code, dref_repr_t(dref)); char * result = NULL; if (dref) { DBGMSF(debug, "dref->dfr=%s", dfr_repr_t(dref->dfr)); if (dref->dfr) { Dyn_Feature_Metadata * dfr_metadata = dyn_get_dynamic_feature_metadata(dref->dfr, feature_code); if (dfr_metadata) result = dfr_metadata->feature_name; } if (!result) { DDCA_MCCS_Version_Spec // vspec = dref->vcp_version; // TODO use function call in case not set vspec = get_vcp_version_by_dref(dref); result = get_feature_name_by_id_and_vcp_version(feature_code, vspec); } } else { result = get_feature_name_by_id_only(feature_code); } DBGMSF(debug, "Done. Returning: %s", result); return result; } void init_dyn_feature_codes() { RTTI_ADD_FUNC(dyn_get_feature_metadata_by_dfr_and_vspec_dfm); RTTI_ADD_FUNC(dyn_get_feature_metadata_by_mmk_and_vspec); RTTI_ADD_FUNC(dyn_get_feature_metadata_by_dref); RTTI_ADD_FUNC(dyn_get_feature_metadata_by_dh); RTTI_ADD_FUNC(dyn_format_feature_detail); RTTI_ADD_FUNC(dyn_format_feature_detail_sl_lookup); RTTI_ADD_FUNC(dyn_format_feature_detail_sl_lookup_with_sh); RTTI_ADD_FUNC(dyn_format_nontable_feature_detail); } ddcutil-2.2.0/src/dynvcp/dyn_feature_files.c0000644000175000001440000002533514754153540014565 /** @file dyn_feature_files.c * * Maintain user-defined (aka dynamic) feature definitions */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include "public/ddcutil_types.h" #include "public/ddcutil_status_codes.h" #include "util/edid.h" #include "util/error_info.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/string_util.h" #include "util/xdg_util.h" /** \endcond */ #include "base/core.h" #include "base/displays.h" #include "base/dynamic_features.h" #ifdef USE_YANL #include "base/dynamic_features_yaml.h" #endif #include "base/monitor_model_key.h" #include "base/rtti.h" #include "dyn_feature_files.h" // Default trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_UDF; // global variable bool enable_dynamic_features = false; // for now, just use an array of pointers to DDCA_Feature_Metadata // static DDCA_Feature_Metadata * mfg_feature_info[32]; // array of features needs to be per-monitor // for each detected monitor, look for files with name of form: // MFG_modelName_productCode.MCCS // spaces and other special characters converted to "_" in modelName // search path: // local directory // XDG search path, use directory .local/share/ddcutil // once we have a dref, can look for feature definition files // functions: // find_feature_definition_file(char * mfg, char * model, uint16_t product_code) // load_feature_definition_file(char * fn) // creates an array of DDCA_Feature_Metadata // hang it off dref // dref needs additional flag DREF_LOCAL_FEATURES_SEARCHED // // vcp feature code lookup: // need function to add local tables // create VCP_Feature_Table_Entry from DDCA_Feature_Metadata // modify find_feature_by_hexid() to use local tables // problem: need to specify which monitor-specific list of local tables to use // function variant that takes aux table as argument? // perhaps put this function at ddc level? // // #ifdef UNUSED // Dynamic feature records are currently hung off the Display_Ref for a display, // so there is no need to look them up in a central table. // This might change if support for dynamically adding and removing displays is added, // in which case some variant of this code might prove useful. static GHashTable * dynamic_features_records; // entries are only added, never deleted or replaced static void dfr_init() { if (!dynamic_features_records) { dynamic_features_records = g_hash_table_new( g_str_hash, g_str_equal); } } static void dfr_save( Dynamic_Features_Rec * dfr) { char * key = mmk_model_id_string( dfr->mfg_id, dfr->model_name, dfr->product_code); if (!dynamic_features_records) dfr_init(); g_hash_table_insert(dynamic_features_records, key, dfr); } Dynamic_Features_Rec * dfr_lookup( char * mfg_id, char * model_name, uint16_t product_code) { Dynamic_Features_Rec * result = NULL; if (dynamic_features_records) { char * key = mmk_model_id_string(mfg_id, model_name, product_code); result = g_hash_table_lookup(dynamic_features_records, key); assert(memcmp(result->marker, DYNAMIC_FEATURES_REC_MARKER, 4) == 0); // if (result->flags & DFR_FLAGS_NOT_FOUND) // result = NULL; free(key); } return result; } Dynamic_Features_Rec * dfr_get( char * mfg_id, char * model_name, uint16_t product_code) { Dynamic_Features_Rec * result = NULL; Dynamic_Features_Rec * existing = NULL; existing = dfr_lookup(mfg_id, model_name, product_code); if (existing) { if (existing->flags & DFR_FLAGS_NOT_FOUND) { // we've already checked and it's not there result = NULL; } else result = existing; } else { // ??? what to do with errors from loading file? } return result; } /* static */ DDCA_Feature_Metadata * get_feature_metadata( GHashTable * features, uint8_t feature_code) { DDCA_Feature_Metadata * result = g_hash_table_lookup(features, GINT_TO_POINTER(feature_code)); if (result) assert( memcmp(result->marker, DDCA_FEATURE_METADATA_MARKER, 4) == 0); return result; } #endif /** Look for feature definition file on the XDG_DATA_PATH * * \param simple_fn simple filename, without ".mccs" suffix * \return fully qualified name of file found (caller must free), NULL if not found */ char * dfr_find_feature_def_file( const char * simple_fn) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "simple_fn=|%s|", simple_fn); char buf[PATH_MAX]; g_snprintf(buf, PATH_MAX, "%s.mccs", simple_fn); char * result = find_xdg_data_file("ddcutil", buf); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", result); return result; } /** Search the file system for a feature definition file specified by * a #DDCA_Monitor_Model_Key, and create a #Dynamic_Features_Rec for * the result. * * @param mmk monitor specifier * @param dfr_loc where to return the created #Dynamic_Features_Rec * @return #Error_Info struct describing errors. * * @remark * If a #Error_Info struct is returned, it has status code either * DDCRC_BAD_DATA, DDCRC_NOT_FOUND, or an error reading the file. * * @remark * If an #Error_Info struct is returned, then a dummy #Dynamic_Features_Rec is * created and returned, with flag DFR_FLAGS_NOT_FOUND set. This record can then * be saved along with with valid #Dynamic_Features_Rec instances to avoid * repeatedly scanning for non-existent or invalid feature definition files. * @remark * Caller is responsible for freeing the #Dynamic_Features_Rec returned in dfr_loc. */ Error_Info * dfr_load_by_mmk( Monitor_Model_Key mmk, Dynamic_Features_Rec ** dfr_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "mmk = %s", mmk_string(&mmk)); Error_Info * errs = NULL; Dynamic_Features_Rec * dfr = NULL; char * simple_fn = mmk_model_id_string(mmk.mfg_id, mmk.model_name,mmk.product_code); char * fqfn = dfr_find_feature_def_file(simple_fn); if (fqfn) { GPtrArray * lines = g_ptr_array_new_with_free_func(g_free); errs = file_getlines_errinfo(fqfn, lines); // read file into lines // if (get_output_level() >= DDCA_OL_VERBOSE) { // fprintf(fout(), "Using feature definition file: %s\n", fqfn); // } if (!errs) { #ifdef USE_YAML_LOAD errs = create_monitor_dynamic_features_yaml( mmk.mfg_id, mmk.model_name, mmk.product_code, fqfn, &dfr); #else errs = create_dynamic_features_rec( // DDCRC_BAD_DATA mmk.mfg_id, mmk.model_name, mmk.product_code, lines, fqfn, &dfr); // } #endif g_ptr_array_free(lines, true); assert( (errs && !dfr) || (!errs && dfr)); } free(fqfn); } else { errs = errinfo_new(DDCRC_NOT_FOUND, __func__, "Feature definition file not found: %s.mccs", simple_fn); } assert( (errs && !dfr) || (!errs && dfr)); // avoid clang warning if (errs) { // DBGMSG("errs set, create dummy entry"); // save a dummy entry so we don't issue error messages again for same record dfr = dfr_new(mmk.mfg_id, mmk.model_name, mmk.product_code, NULL); dfr->flags |= DFR_FLAGS_NOT_FOUND; } *dfr_loc = dfr; free(simple_fn); #ifdef UNUSED dfr_save(dfr); #endif ASSERT_IFF(errs, (*dfr_loc)->flags & DFR_FLAGS_NOT_FOUND); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, errs, "*dfr_loc=%p", *dfr_loc); return errs; } #ifdef UNUSED /** Search the file system for a feature definition file indicated by an EDID, * and create a #Dynamic_Features_Rec for the result. * * @param mmk monitor specifier * @param dfr_loc where to return the created #Dynamic_Features_Rec * @return #Error_Info struct describing errors. * * @remark * If a #Error_Info struct is returned, then a dummy #Dynamic_Features_Rec is * created and returned, with flag DFR_FLAGS_NOT_FOUND set. This record can then * be saved along with with valid #Dynamic_Features_Rec instances to avoid * repeatedly scanning for non-existent or invalid feature definition files. */ Error_Info * dfr_load_by_edid( Parsed_Edid * edid, Dynamic_Features_Rec ** dfr_loc) { Monitor_Model_Key mmk = monitor_model_key_value( edid->mfg_id, edid->model_name, edid->product_code); return dfr_load_by_mmk(mmk, dfr_loc); } #endif Error_Info * dfr_check_by_dref( Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref=%s, enable_dynamic_features=%s", dref_repr_t(dref), sbool(enable_dynamic_features)); ASSERT_IFF(dref->flags&DREF_DYNAMIC_FEATURES_CHECKED, dref->dfr); Error_Info * errs = NULL; if (enable_dynamic_features) { // global variable if ( !(dref->flags & DREF_DYNAMIC_FEATURES_CHECKED) ) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "DREF_DYNAMIC_FEATURES_CHECKED not yet set"); Monitor_Model_Key mmk = mmk_value_from_edid(dref->pedid); errs = dfr_load_by_mmk(mmk, &dref->dfr); // will be a dummy record if errors dref->flags |= DREF_DYNAMIC_FEATURES_CHECKED; } } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, errs, "dref->drf=%p", dref->dfr); return errs; } Error_Info * dfr_check_by_dh( Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, enable_dynamic_features=%s", dh_repr_p(dh), sbool(enable_dynamic_features)); Display_Ref * dref = dh->dref; Error_Info * errs = dfr_check_by_dref(dref); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, errs, "dh->dref->drf=%p", dh->dref->dfr); return errs; } #ifdef UNUSED Error_Info * dfr_check_by_mmk( Monitor_Model_Key mmk) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Starting. dref=%s", mmk_repr(mmk)); Error_Info * errs = NULL; Dynamic_Features_Rec * dfr = NULL; if (enable_dynamic_features) // global variable { errs = dfr_load_by_mmk(mmk, &dfr); } if (debug || IS_TRACING_GROUP(DDCA_TRC_UDF) ) { if (errs) { DBGMSG("Done. Returning errs: "); errinfo_report(errs, 1); } else DBGMSG("Done. dfr=%p", dfr); } return errs; } #endif void init_dyn_feature_files() { RTTI_ADD_FUNC(dfr_check_by_dref); RTTI_ADD_FUNC(dfr_load_by_mmk); RTTI_ADD_FUNC(dfr_find_feature_def_file); } ddcutil-2.2.0/src/dynvcp/dyn_feature_codes.h0000644000175000001440000000474014754576332014572 /** @file dyn_feature_codes.h * * Access VCP feature code descriptions at the DDC level in order to * incorporate user-defined per-monitor feature information. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DYN_FEATURE_CODES_H_ #define DYN_FEATURE_CODES_H_ #include "ddcutil_types.h" #include "base/feature_metadata.h" #include "vcp/vcp_feature_codes.h" #include "ddc/ddc_vcp_version.h" Display_Feature_Metadata * dyn_get_feature_metadata_by_mmk_and_vspec( DDCA_Vcp_Feature_Code feature_code, Monitor_Model_Key mmk, DDCA_MCCS_Version_Spec vspec, bool check_udf, bool with_default); Display_Feature_Metadata * dyn_get_feature_metadata_by_dref( DDCA_Vcp_Feature_Code id, Display_Ref * dref, bool check_udf, bool with_default); Display_Feature_Metadata * dyn_get_feature_metadata_by_dh( DDCA_Vcp_Feature_Code id, Display_Handle * dh, bool check_udf, bool with_default); bool dyn_format_nontable_feature_detail( Display_Feature_Metadata * dfm, // DDCA_MCCS_Version_Spec vcp_version, Nontable_Vcp_Value * code_info, char * buffer, int bufsz); bool dyn_format_table_feature_detail( Display_Feature_Metadata * dfm, // DDCA_MCCS_Version_Spec vcp_version, Buffer * accumulated_value, char * * aformatted_data); bool dyn_format_feature_detail( Display_Feature_Metadata * dfm, DDCA_MCCS_Version_Spec vcp_version, DDCA_Any_Vcp_Value * valrec, char * * aformatted_data); char * dyn_get_feature_name( Byte feature_code, Display_Ref* dref); bool dyn_format_feature_detail_sl_lookup( Nontable_Vcp_Value * code_info, DDCA_Feature_Value_Entry * value_table, char * buffer, int bufsz); bool dyn_format_feature_detail_sl_lookup_with_sh( Nontable_Vcp_Value * code_info, DDCA_Feature_Value_Entry * value_table, char * buffer, int bufsz); void init_dyn_feature_codes(); #endif /* DYN_FEATURE_CODES_H_ */ ddcutil-2.2.0/src/dynvcp/dyn_feature_files.h0000644000175000001440000000146014754576332014573 /** \file dyn_feature_files.h * * Maintain dynamic feature files */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DYN_FEATURE_FILES_H_ #define DYN_FEATURE_FILES_H_ /** \cond */ #include "ddcutil_types.h" #include "util/error_info.h" /** \endcond */ #include "base/displays.h" extern bool enable_dynamic_features; char * dfr_find_feature_def_file( const char * simple_fn); Error_Info * dfr_load_by_mmk( Monitor_Model_Key mmk, Dynamic_Features_Rec ** dfr_loc); Error_Info * dfr_check_by_dref(Display_Ref * dref); Error_Info * dfr_check_by_dh(Display_Handle * dh); #ifdef UNUSED Error_Info * dfr_check_by_mmk(Monitor_Model_Key mmk); #endif void init_dyn_feature_files(); #endif /* DYN_FEATURE_FILES_H_ */ ddcutil-2.2.0/src/dynvcp/dyn_feature_set.h0000644000175000001440000000472514754576332014273 /** @file dyn_feature_set.h * * Dyn_Feature_Set wrappers VCP_Feature_Set at the ddc level to incorporate * user supplied feature information in feature metadata. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DYN_FEATURE_SET_H_ #define DYN_FEATURE_SET_H_ #include "public/ddcutil_types.h" /** \cond */ #include #include #include #include "util/coredefs.h" /** \endcond */ #include "base/displays.h" #include "base/feature_set_ref.h" // #include "dynvcp/vcp_feature_set.h" #include "dynvcp/dyn_feature_codes.h" #define DYN_FEATURE_SET_MARKER "DSET" typedef struct { char marker[4]; VCP_Feature_Subset subset; // subset identifier DDCA_Display_Ref dref; GPtrArray * members_dfm; // array of pointers to Display_Feature_Metadata - alt } Dyn_Feature_Set; void free_dyn_feature_set(Dyn_Feature_Set * fset); void report_dyn_feature_set(Dyn_Feature_Set * fset, int depth); void dbgrpt_dyn_feature_set( Dyn_Feature_Set * feature_set, bool verbose, int depth); char * dyn_feature_set_repr_t( Dyn_Feature_Set * fset); Dyn_Feature_Set * dyn_create_feature_set( VCP_Feature_Subset subset, DDCA_Display_Ref dref, Feature_Set_Flags flags); Dyn_Feature_Set * create_dyn_feature_set_from_feature_set_ref( Feature_Set_Ref * fsref, DDCA_MCCS_Version_Spec vcp_version, Feature_Set_Flags flags); #ifdef UNUSED Dyn_Feature_Set * dyn_create_single_feature_set_by_hexid2( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref dref, bool force); #endif Display_Feature_Metadata * dyn_get_feature_set_entry( Dyn_Feature_Set * feature_set, unsigned index); int dyn_get_feature_set_size( Dyn_Feature_Set * feature_set); #ifdef UNUSED Dyn_Feature_Set * dyn_create_feature_set_from_feature_set_ref2( Feature_Set_Ref * fsref, // DDCA_MCCS_Version_Spec vcp_version, DDCA_Display_Ref dref, Feature_Set_Flags flags); #endif typedef bool (*Dyn_Feature_Set_Filter_Func)(Display_Feature_Metadata * p_metadata); void filter_feature_set( Dyn_Feature_Set* feature_set, Dyn_Feature_Set_Filter_Func func); void dyn_free_feature_set( Dyn_Feature_Set * feature_set); void init_dyn_feature_set(); #endif /* DYN_FEATURE_SET_H_ */ ddcutil-2.2.0/src/dynvcp/dyn_parsed_capabilities.h0000644000175000001440000000162414754576332015747 /** @file dyn_parsed_capabilities.h * * Report parsed capabilities, taking into account dynamic feature definitions. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DYN_PARSED_CAPABILITIES_H_ #define DYN_PARSED_CAPABILITIES_H_ #include "base/displays.h" #include "vcp/parse_capabilities.h" #ifdef UNNEEDED #include "base/vcp_version.h" #include "vcp/parsed_capabilities_feature.h" void report_capabilities_feature( Capabilities_Feature_Record * vfr, DDCA_MCCS_Version_Spec vcp_version, int depth); #endif void dyn_report_parsed_capabilities( Parsed_Capabilities* pcaps, Display_Handle * dh, Display_Ref * dref, int depth); void init_dyn_parsed_capabilities(); #endif /* DYN_PARSED_CAPABILITIES_H_ */ ddcutil-2.2.0/src/dynvcp/vcp_feature_set.h0000644000175000001440000000403214754576332014260 /** @file vcp_feature_set.h * Struct VCP_Feature_Set holds VCP_Feature_Table_Entry(s) for * some collection of VCP features. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef VCP_FEATURE_SET_H_ #define VCP_FEATURE_SET_H_ #include "public/ddcutil_types.h" /** \cond */ #include #include #include "util/coredefs.h" /** \endcond */ #include "base/feature_set_ref.h" #include "vcp/vcp_feature_codes.h" #define VCP_FEATURE_SET_MARKER "FSET" typedef struct vcp_feature_set { char marker[4]; VCP_Feature_Subset subset; // subset identifier GPtrArray * members; // array of pointers to VCP_Feature_Table_Entry } VCP_Feature_Set; void free_vcp_feature_set(VCP_Feature_Set * fset); typedef bool (*VCP_Feature_Set_Filter_Func)(VCP_Feature_Table_Entry * ventry); VCP_Feature_Table_Entry * get_vcp_feature_set_entry(VCP_Feature_Set * feature_set, unsigned index); int get_vcp_feature_set_size(VCP_Feature_Set * feature_set); void report_vcp_feature_set(VCP_Feature_Set * feature_set, int depth); void dbgrpt_vcp_feature_set(VCP_Feature_Set * feature_set, int depth); VCP_Feature_Set * create_vcp_feature_set_from_feature_set_ref( Feature_Set_Ref * fsref, DDCA_MCCS_Version_Spec vcp_version, Feature_Set_Flags flags); // bool force); #ifdef UNUSED VCP_Feature_Set * create_single_feature_set_by_vcp_entry(VCP_Feature_Table_Entry * vcp_entry); VCP_Feature_Set * create_single_feature_set_by_hexid(Byte id, bool force); void replace_vcp_feature_set_entry( VCP_Feature_Set * feature_set, unsigned index, VCP_Feature_Table_Entry * new_entry); VCP_Feature_Subset get_feature_set_subset_id(VCP_Feature_Set * feature_set); void filter_feature_set(VCP_Feature_Set * fset, VCP_Feature_Set_Filter_Func func); DDCA_Feature_List feature_list_from_feature_set(VCP_Feature_Set * feature_set); #endif void init_vcp_feature_set(); #endif /* VCP_FEATURE_SET_H_ */ ddcutil-2.2.0/src/i2c/0000775000175000001440000000000014754576332010166 5ddcutil-2.2.0/src/i2c/Makefile.am0000644000175000001440000000105714754153540012133 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ $(LIBDRM_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = -Wall if WARNINGS_ARE_ERRORS_COND AM_CFLAGS += -Werror endif # AM_CFLAGS += -Wpedantic if ENABLE_CALLGRAPH_COND AM_CFLAGS += -fdump-rtl-expand endif CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libi2c.la libi2c_la_SOURCES = \ i2c_bus_core.c \ i2c_bus_selector.c \ i2c_edid.c \ i2c_execute.c \ i2c_services.c \ i2c_strategy_dispatcher.c ddcutil-2.2.0/src/i2c/Makefile.in0000664000175000001440000005217314754576155012166 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @WARNINGS_ARE_ERRORS_COND_TRUE@am__append_1 = -Werror # AM_CFLAGS += -Wpedantic @ENABLE_CALLGRAPH_COND_TRUE@am__append_2 = -fdump-rtl-expand subdir = src/i2c ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libi2c_la_LIBADD = am_libi2c_la_OBJECTS = i2c_bus_core.lo i2c_bus_selector.lo i2c_edid.lo \ i2c_execute.lo i2c_services.lo i2c_strategy_dispatcher.lo libi2c_la_OBJECTS = $(am_libi2c_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/i2c_bus_core.Plo \ ./$(DEPDIR)/i2c_bus_selector.Plo ./$(DEPDIR)/i2c_edid.Plo \ ./$(DEPDIR)/i2c_execute.Plo ./$(DEPDIR)/i2c_services.Plo \ ./$(DEPDIR)/i2c_strategy_dispatcher.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libi2c_la_SOURCES) DIST_SOURCES = $(libi2c_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ $(LIBDRM_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = -Wall $(am__append_1) $(am__append_2) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libi2c.la libi2c_la_SOURCES = \ i2c_bus_core.c \ i2c_bus_selector.c \ i2c_edid.c \ i2c_execute.c \ i2c_services.c \ i2c_strategy_dispatcher.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/i2c/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/i2c/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libi2c.la: $(libi2c_la_OBJECTS) $(libi2c_la_DEPENDENCIES) $(EXTRA_libi2c_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libi2c_la_OBJECTS) $(libi2c_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_bus_core.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_bus_selector.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_edid.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_execute.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_strategy_dispatcher.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/i2c_bus_core.Plo -rm -f ./$(DEPDIR)/i2c_bus_selector.Plo -rm -f ./$(DEPDIR)/i2c_edid.Plo -rm -f ./$(DEPDIR)/i2c_execute.Plo -rm -f ./$(DEPDIR)/i2c_services.Plo -rm -f ./$(DEPDIR)/i2c_strategy_dispatcher.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/i2c_bus_core.Plo -rm -f ./$(DEPDIR)/i2c_bus_selector.Plo -rm -f ./$(DEPDIR)/i2c_edid.Plo -rm -f ./$(DEPDIR)/i2c_execute.Plo -rm -f ./$(DEPDIR)/i2c_services.Plo -rm -f ./$(DEPDIR)/i2c_strategy_dispatcher.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/i2c/i2c_bus_core.c0000644000175000001440000024174414754153540012612 /** @file i2c_bus_core.c * * I2C bus detection and inspection */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include #include #include #include #ifdef USE_X11 // #include #endif /** \endcond */ #include "util/coredefs_base.h" #include "util/debug_util.h" #include "util/data_structures.h" #include "util/drm_common.h" #include "util/edid.h" #include "util/error_info.h" #include "util/failsim.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/traced_function_stack.h" #ifdef ENABLE_UDEV #include "util/udev_i2c_util.h" #endif #include "util/utilrpt.h" #ifdef USE_X11 #include "util/x11_util.h" #endif #include "base/core.h" #include "base/ddc_errno.h" #include "base/display_lock.h" #include "base/drm_connector_state.h" #include "base/flock.h" #include "base/i2c_bus_base.h" #include "base/linux_errno.h" #include "base/monitor_model_key.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/rtti.h" #include "base/sleep.h" #include "base/status_code_mgt.h" #include "base/tuned_sleep.h" #include "sysfs/sysfs_i2c_info.h" #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "sysfs/sysfs_conflicting_drivers.h" #ifdef TARGET_BSD #include "bsd/i2c-dev.h" #else #include "i2c/wrap_i2c-dev.h" #endif #include "i2c/i2c_strategy_dispatcher.h" #include "i2c/i2c_execute.h" #include "i2c/i2c_edid.h" #include "i2c/i2c_bus_core.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_I2C; bool i2c_force_bus = false; // Another ugly global variable for testing purposes bool all_video_adapters_implement_drm = false; bool use_drm_connector_states = false; bool try_get_edid_from_sysfs_first = true; int i2c_businfo_async_threshold = DEFAULT_BUS_CHECK_ASYNC_THRESHOLD; // quick and dirty for debugging static char * edid_summary_from_bytes(Byte * edidbytes) { static GPrivate key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&key, 200); if (!edidbytes) strcpy(buf, "null edid ptr"); else { Parsed_Edid * parsed = create_parsed_edid(edidbytes); if (!parsed) strcpy(buf, "Invalid EDID"); else { strcpy(buf, parsed->model_name); free_parsed_edid(parsed); } } return buf; } /** Gets a list of all /dev/i2c devices by checking the file system * if devices named /dev/i2c-N exist. * * @return Byte_Value_Array containing the valid bus numbers */ Byte_Value_Array get_i2c_devices_by_existence_test(bool include_ignorable_devices) { Byte_Value_Array bva = bva_create(); for (int busno=0; busno < I2C_BUS_MAX; busno++) { if (i2c_device_exists(busno)) { if (include_ignorable_devices || !sysfs_is_ignorable_i2c_device(busno)) bva_append(bva, busno); } } return bva; } // // Bus open and close // static GMutex open_failures_mutex; static Bit_Set_256 open_failures_reported; /** Adds a set of bus numbers to the set of bus numbers * whose open failure has already been reported. * * @param failures set of bus numbers */ void add_open_failures_reported(Bit_Set_256 failures) { g_mutex_lock(&open_failures_mutex); open_failures_reported = bs256_or(open_failures_reported, failures); g_mutex_unlock(&open_failures_mutex); } /** Adds a single bus number to the set of open failures already reported. * * @param busno /dev/i2c-N bus number */ void include_open_failures_reported(int busno) { g_mutex_lock(&open_failures_mutex); open_failures_reported = bs256_insert(open_failures_reported, busno); g_mutex_unlock(&open_failures_mutex); } #ifdef ALT_LOCK_RECORD Error_Info * lock_display_by_businfo( I2C_Bus_Info * businfo, Display_Lock_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "bus = BusInfo[/dev/i2c-%d]", businfo->busno); Display_Lock_Record * lockid = businfo->lock_record; Error_Info * result = lock_display2(lockid, flags); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, "device=/dev/i2c-%d", businfo->busno); return result; } Error_Info * unlock_display_by_businfo(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "bus = BusInfo[/dev/i2c-%d]", businfo->busno); Display_Lock_Record * lockid = businfo->lock_record; Error_Info * result = unlock_display2(lockid); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, "device=/dev/i2c-%d", businfo->busno); return result; } #endif Error_Info * i2c_open_bus_basic(const char * filename, Byte callopts, int* fd_loc) { bool debug = false; Error_Info * err = NULL; RECORD_IO_EVENT( -1, IE_OPEN, ( *fd_loc = open(filename, (callopts & CALLOPT_RDONLY) ? O_RDONLY : O_RDWR) ) ); // if successful returns file descriptor, if fail, returns -1 and errno is set if (*fd_loc < 0) { int errsv = -errno; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "open(%s) failed. errno=%s", filename, psc_desc(errsv)); err = ERRINFO_NEW(errsv, "Open failed for %s, errno=%s", filename, psc_desc(errsv)); } return err; } /** Open an I2C bus device. * * @param busno bus number * @param callopts call option flags, controlling failure action * * @retval >=0 Linux file descriptor * @retval -errno negative Linux errno if open fails * * Call options recognized * - CALLOPT_WAIT */ Error_Info * i2c_open_bus( int busno, #ifdef ALT_LOCK_RECORD Display_Lock_Record * lockrec, #endif Byte callopts, int* fd_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "/dev/i2c-%d, callopts=0x%02x=%s", busno, callopts, interpret_call_options_t(callopts)); ASSERT_WITH_BACKTRACE(busno >= 0); #ifdef ALT_LOCK_REC assert(lockrec); #endif bool wait = callopts & CALLOPT_WAIT; // wait = true; // *** TEMP *** #ifdef ALT_LOCK_REC I2C_Bus_Info * businfo = i2c_find_bus_info_by_busno(busno); assert(businfo); // !!! fails, all_bus_info not yet set #endif int open_max_wait_millisec = DEFAULT_OPEN_MAX_WAIT_MILLISEC; int open_wait_interval_millisec = DEFAULT_OPEN_WAIT_INTERVAL_MILLISEC; int total_wait_millisec = 0; char filename[20]; Error_Info * master_error = NULL; assert(fd_loc); *fd_loc = -1; // ? Display_Lock_Flags ddisp_flags = DDISP_NONE; // if (wait) // ddisp_flags |= DDISP_WAIT; DDCA_IO_Path dpath; dpath.io_mode = DDCA_IO_I2C; dpath.path.i2c_busno = busno; snprintf(filename, 20, "/dev/"I2C"-%d", busno); int tryctr = 0; while( *fd_loc < 0 && total_wait_millisec <= open_max_wait_millisec) { bool device_locked = false; bool device_flocked = false; bool device_opened = false; tryctr++; Error_Info * cur_error = NULL; // 1) lock display within this ddcutil/libddcutil instance cur_error = lock_display_by_dpath(dpath, ddisp_flags); #ifdef ALT_LOCK_REC cur_error = lock_display2(businfo->lock_record, ddisp_flags); #endif if (cur_error) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "lock_display_by_dpath(%s) returned %s", filename, psc_desc(cur_error->status_code)); } else { device_locked = true; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "lock_display_by_dpath(%s) succeeded", dpath_repr_t(&dpath)); } // 2) Open the device if (!cur_error) { cur_error = i2c_open_bus_basic(filename, callopts, fd_loc); if (!cur_error) { device_opened = true; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "open(%s) succeeded, tryctr=%d", filename, tryctr); } else { if (cur_error->status_code == -EACCES || cur_error->status_code == -ENOENT) { // no point in retrying, force loop exit: total_wait_millisec = open_max_wait_millisec + 1; } } } // 3) create cross-instance lock if (!cur_error && cross_instance_locks_enabled) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Acquiring cross instance lock for %s", filename); Status_Errno flockrc = flock_lock_by_fd(*fd_loc, filename, wait ); if (flockrc != 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Cross instance locking failed for %s", filename); cur_error = ERRINFO_NEW(flockrc, "flock_lock_by_fd(%s) returned %s", filename, psc_desc(flockrc)); #ifdef EXPERIMENTAL_FLOCK_RECOVREY Buffer * edidbuf = buffer_new(256, ""); Status_Errno_DDC rc = i2c_get_raw_edid_by_fd(*fd_loc, edidbuf); bool found_edid = (rc == 0); buffer_free(edidbuf, ""); DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "able to read edid directly for /dev/i2c-%d: %s", busno, sbool(found_edid)); // TODO: read attributes // RPT_ATTR_TEXT(1, NULL, "/sys/class/drm", dh->dref-> #endif } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Cross instance locking succeeded for %s", filename); } } // operations complete, back out if error if (!cur_error) continue; // Something failed. Release attached resources. DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "something failed, %s, cur_error = %s", filename, errinfo_summary(cur_error)); assert (!device_flocked); // it was the last thing attempted // 2) close the device if it was opened ASSERT_IFF(*fd_loc >= 0, device_opened); if (*fd_loc >= 0) { close(*fd_loc); *fd_loc = -1; } // 1) release the cross-thread lock if (device_locked) { Error_Info * err = unlock_display_by_dpath(dpath); // only error returned is DDCRC_LOCKED, which is impossible in this case, but nonetheless: if (err) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "unlock_display_by_dpath(%s) returned %d", dpath_repr_t(&dpath), err->status_code); ASSERT_WITH_BACKTRACE(!err); } } #ifdef OLD if (!master_error) master_error = ERRINFO_NEW(DDCRC_OTHER, "i2c_open_bus() failed"); // need an DDCRC_OPEN errinfo_add_cause(master_error, cur_error); #endif if (!master_error) master_error = cur_error; else errinfo_add_cause(master_error, cur_error); total_wait_millisec += open_wait_interval_millisec; if (total_wait_millisec > open_max_wait_millisec) DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Total wait %d exceeds max wait %d, tries=%d", total_wait_millisec, open_max_wait_millisec, tryctr); else { DW_SLEEP_MILLIS(open_wait_interval_millisec, ""); // usleep(wait_interval_millisec * 1000); } } if (*fd_loc >= 0) { ERRINFO_FREE(master_error); master_error = NULL; } else { // if all causes have the same status code, replace the status code in the master error } ASSERT_IFF(master_error, *fd_loc == -1); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, master_error, "/dev/i2c-%d, tryctr=%d, Set file descriptor *fd_loc = %d", busno, tryctr, *fd_loc); return master_error; } Status_Errno i2c_close_bus_basic(int busno, int fd, Call_Options callopts) { int rc; Status_Errno result = 0; RECORD_IO_EVENT(fd, IE_CLOSE, ( rc = close(fd) ) ); assert( rc == 0 || rc == -1); // per documentation int errsv = errno; if (rc < 0) { // EBADF (9) fd isn't a valid open file descriptor // EINTR (4) close() interrupted by a signal // EIO (5) I/O error if (callopts & CALLOPT_ERR_MSG) f0printf(ferr(), "Close failed for %s, errno=%s\n", filename_for_fd_t(fd), linux_errno_desc(errsv)); result = -errsv; // assert(rc == 0); // don't bother with recovery for now } return result; } /** Closes an open I2C bus device. * * @param busno i2c_bus_number * @param fd Linux file descriptor * @param callopts call option flags, controlling failure action * * @retval 0 success * @retval <0 negative Linux errno value if close fails */ Status_Errno i2c_close_bus(int busno, int fd, Call_Options callopts) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, fd=%d - %s, callopts=%s", busno, fd, filename_for_fd_t(fd), interpret_call_options_t(callopts)); #ifdef ALT_LOCK_BASIC I2C_Bus_Info * businfo = i2c_find_bus_info_by_busno(busno); assert(businfo); #endif Status_Errno result = 0; // 3) release cross-instance lock DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "calling flock() for /dev/i2c-%d...", busno); if (cross_instance_locks_enabled) { int rc = flock_unlock_by_fd(fd); if (rc < 0) { DBGTRC_NOPREFIX(true, TRACE_GROUP, "%/dev/i2c-%d. Unexpected error from flock(..,LOCK_UN): %s", busno, psc_desc(rc)); } } // 2) Close the device DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_close_bus for /dev/i2c-%d...", busno); result = i2c_close_bus_basic(busno, fd, callopts); assert(result == 0); // TODO; handle failure DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "/dev/i2c-%d. i2c_close_bus_basic() returned %d", busno, result); assert(result == 0); // TODO; handle failure // 1) Release the cross-thread lock DDCA_IO_Path dpath; dpath.io_mode = DDCA_IO_I2C; dpath.path.i2c_busno = busno; #ifdef ALT_LOCK_REC Error_Info * erec = unlock_display2(businfo->lock_record); #endif DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling unlock_display_by_dpath(/dev/i2c-%d)...", busno); Error_Info * erec = unlock_display_by_dpath(dpath); if (erec) { char * s = g_strdup_printf("Unexpected error %s from unlock_display_by_dpath(%s)", psc_name(erec->status_code), dpath_repr_t(&dpath)); DBGTRC_NOPREFIX(true, TRACE_GROUP, "%s", s); SYSLOG2(DDCA_SYSLOG_ERROR, "%s", s); free(s); errinfo_free(erec); } assert(result <= 0); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, "busno=%d, fd=%d",busno, fd); return result; } // // I2C Bus Inspection - Slave Addresses // #ifdef UNUSED #define IS_EDP_DEVICE(_busno) is_laptop_drm_connector(_busno, "-eDP-") #define IS_LVDS_DEVICE(_busno) is_laptop_drm_connector(_busno, "-LVDS-") /** Checks whether a /dev/i2c-n device represents an eDP or LVDS device, * i.e. a laptop display. * * @param busno i2c bus number * #param drm_name_fragment string to look for * @return true/false * * @remark Works only for DRM displays, therefore use only * informationally. */ // Attempting to recode using opendir() and readdir() produced // a complicated mess. Using execute_shell_cmd_collect() is simple. // Simplicity has its virtues. static bool is_laptop_drm_connector(int busno, char * drm_name_fragment) { bool debug = false; // DBGTRC_STARTING(debug, DDCA_TRC_NONE, "busno=%d, drm_name_fragment=|%s|", busno, drm_name_fragment); bool result = false; char cmd[100]; snprintf(cmd, 100, "ls -d /sys/class/drm/card*/card*/"I2C"-%d", busno); // DBGMSG("cmd: %s", cmd); GPtrArray * lines = execute_shell_cmd_collect(cmd); if (lines) { // command should never fail, but just in case for (int ndx = 0; ndx < lines->len; ndx++) { char * s = g_ptr_array_index(lines, ndx); if (strstr(s, drm_name_fragment)) { result = true; break; } } g_ptr_array_free(lines, true); } DBGTRC_EXECUTED(debug, TRACE_GROUP, "busno=%d, drm_name_fragment |%s|, Returning: %s", busno, drm_name_fragment, sbool(result)); return result; } #endif STATIC bool is_laptop_drm_connector_name(const char * connector_name) { bool debug = false; bool result = strstr(connector_name, "-eDP-") || strstr(connector_name, "-LVDS-"); DBGF(debug, "connector_name=|%s|, returning %s", connector_name, sbool(result)); return result; } // // Check display status // /** Checks if the EDID of an existing display handle can be read * using the handle's I2C bus. Failure indicates that the display * has been disconnected and the display handle is no longer valid. * * @param dh display handle * @return true if the EDID can be read, false if not */ STATIC bool i2c_check_edid_exists_by_dh(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dh = %s", dh_repr(dh)); Buffer * edidbuf = buffer_new(256, ""); Status_Errno_DDC rc = i2c_get_raw_edid_by_fd(dh->fd, edidbuf); bool result = (rc == 0); buffer_free(edidbuf, ""); DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, ""); return result; } #ifdef UNUSED /** Attempts to read the EDID on the I2C bus specified in * a #Businfo record. * * @param businfo * @return true if the EDID can be read, false if not */ bool i2c_check_edid_exists_by_businfo(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "busno = %d", businfo->busno); bool result = false; int fd = -1; Error_Info * erec = i2c_open_bus(businfo->busno, CALLOPT_ERR_MSG, &fd); if (!erec) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Opened bus /dev/i2c-%d", businfo->busno); Buffer * edidbuf = buffer_new(256, ""); Status_Errno_DDC rc = i2c_get_raw_edid_by_fd(fd, edidbuf); if (rc == 0) result = true; buffer_free(edidbuf, ""); i2c_close_bus(businfo->busno,fd, CALLOPT_ERR_MSG); } else ERRINFO_FREE(erec); DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, ""); return result; } #endif #ifdef OUT // *** wrong for Nvidia driver *** Error_Info * i2c_check_bus_responsive_using_drm(const char * drm_connector_name) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "drm_connector_name = %s", drm_connector_name); assert(sys_drm_connectors); assert(drm_connector_name); Error_Info * result = NULL; char * status; RPT_ATTR_TEXT(-1, &status, "/sys/class/drm", drm_connector_name, "status"); if (streq(status, "disconnected")) // *** WRONG Nvidia driver always reports "disconnected" result = ERRINFO_NEW(DDCRC_DISCONNECTED, "Display was disconnected"); else { char * dpms; RPT_ATTR_TEXT(-1, &dpms, "/sys/class/drm", drm_connector_name, "dpms"); if ( !streq(dpms, "On")) result = ERRINFO_NEW(DDCRC_DPMS_ASLEEP, "Display is in a DPMS sleep mode"); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, ""); return result; } #endif static Status_Errno_DDC i2c_detect_x37(int fd, char * driver) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d - %s, driver=%s", fd, filename_for_fd_t(fd), driver ); // Quirks // - i2c_set_addr() Causes screen corruption on Dell XPS 13, which has a QHD+ eDP screen // avoided by never calling this function for an eDP screen // - Dell P2715Q does not respond to single byte read, but does respond to // a write (7/2018), so this function checks both Status_Errno_DDC rc = 0; int max_tries = DETECT_X37_MAX_TRIES; //2; // ***TEMP*** 3; bool use_file_io = false; int poll_wait_millisec = DETECT_X37_RETRY_MILLISEC; // 400; char * s = (use_file_io) ? "i2c" : "ioctl"; int loopctr; for (loopctr = 0; loopctr < max_tries; loopctr++) { // retries seem to give no benefit // regard either a successful write() or a read() as indication slave address is valid Byte writebuf = {0x00}; if (use_file_io) rc = invoke_i2c_writer(fd, 0x37, 1, &writebuf); else rc = i2c_ioctl_writer(fd, 0x37, 1, &writebuf); // rc = 6; // for testing DBGTRC_NOPREFIX(debug, TRACE_GROUP, "invoke_%s_writer() for slave address x37 returned %s", s, psc_name_code(rc)); if (rc != 0) { Byte readbuf[4]; // 4 byte buffer if (use_file_io) rc = invoke_i2c_reader(fd, 0x37, false, 4, readbuf); else rc = i2c_ioctl_reader(fd, 0x37, false, 4, readbuf); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "invoke_%s_reader() for slave address x37 returned %s", s, psc_name_code(rc)); } if (rc == 0) break; int wait = poll_wait_millisec; if (streq(driver, "nvidia")) wait = 2000; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "driver=%s, sleeping for %d millisec", driver, wait); // usleep(poll_wait_millisec*1000); DW_SLEEP_MILLIS(wait, "Extra x37 sleep"); // sleep_millis(wait); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc,"loopctr=%d", loopctr); return rc; } /** Tests if an open display handle is still valid * * @param dh display handle * @retval NULL ok * @retval Error_Info with status DDCRC_DISCONNECTED or DDCRC_DPMS_ASLEEP * DDCRC_OTHER slave addr x37 unresponsive * * @remark * Called from ddc_write_read_with_retry() */ Error_Info * i2c_check_open_bus_alive(Display_Handle * dh) { bool debug = false; assert(dh->dref->io_path.io_mode == DDCA_IO_I2C); I2C_Bus_Info * businfo = dh->dref->detail; DBGTRC_STARTING(debug, TRACE_GROUP, "dh=%s, busno=%d, businfo=%p", dh_repr(dh), businfo->busno, businfo ); assert(businfo && ( memcmp(businfo->marker, I2C_BUS_INFO_MARKER, 4) == 0) ); assert( (businfo->flags & I2C_BUS_EXISTS) && (businfo->flags & I2C_BUS_PROBED) ); if (IS_DBGTRC(debug, TRACE_GROUP)) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Traced function stack on entry to i2c_check_open_bus_alive",""); // show_backtrace(0); // all blank lines debug_current_traced_function_stack(false); } syslog(LOG_DEBUG, "Traced function stack on entry to i2c_check_open_bus_alive()"); current_traced_function_stack_to_syslog(LOG_DEBUG, /*reverse*/ false); Error_Info * err = NULL; bool edid_exists = false; int tryctr = 1; for (; !edid_exists && tryctr <= CHECK_OPEN_BUS_ALIVE_MAX_TRIES; tryctr++) { if (tryctr > 1) { // DBGTRC_NOPREFIX(debug, TRACE_GROUP, // "!!! (A) Retrying i2c_check_edid_exists, busno=%d, tryctr=%d, dh=%s", // businfo->busno, tryctr, dh_repr(dh)); // SYSLOG2(DDCA_SYSLOG_WARNING, // "!!! (B) Retrying i2c_check_edid_exists_by_dh, tryctr=%d, dh=%s", tryctr, dh_repr(dh)); DW_SLEEP_MILLIS2(DDCA_SYSLOG_WARNING, CHECK_OPEN_BUS_ALIVE_RETRY_MILLISEC, "Retrying i2c_check_edid_exists_by_dh() (c)"); } #ifdef SYSFS_PROBLEMATIC // apparently not by driver vfd on Raspberry pi if (businfo->drm_connector_name) { i2c_edid_exists = GET_ATTR_EDID(NULL, "/sys/class/drm/", businfo->drm_connector_name, "edid"); // edid_exists = i2c_check_bus_responsive_using_drm(businfo->drm_connector_name); // fails for Nvidia } else { // read edid i2c_edid_exists = i2c_check_edid_exists_by_dh(dh); } #else edid_exists = i2c_check_edid_exists_by_dh(dh); #endif } if (!edid_exists) { SYSLOG2(DDCA_SYSLOG_ERROR, "/dev/i2c-%d, Checking EDID failed after %d tries (B)", businfo->busno, CHECK_OPEN_BUS_ALIVE_MAX_TRIES); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "/dev/i2c-%d: Checking EDID failed (A)", businfo->busno); err = ERRINFO_NEW(DDCRC_DISCONNECTED, "/dev/i2c-%d", businfo->busno); businfo->flags &= ~(I2C_BUS_HAS_EDID|I2C_BUS_ADDR_X37); } else { if (tryctr > 1) { SYSLOG2(DDCA_SYSLOG_WARNING, "/dev/i2c-%d: Checking EDID succeeded after %d tries (G)", businfo->busno, tryctr); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "/dev/i2c-%d: Checking EDID succeeded after %d tries (H)", businfo->busno,tryctr); } char * driver = businfo->driver; int ddcrc = i2c_detect_x37(dh->fd, driver); if (ddcrc){ err = ERRINFO_NEW(DDCRC_OTHER, "/dev/i2c-%d: Slave address x37 unresponsive. io status = %s", businfo->busno, psc_desc(ddcrc)); businfo->flags &= ~I2C_BUS_ADDR_X37; } } if (!err) { if (dpms_check_drm_asleep_by_businfo(businfo)) err = ERRINFO_NEW(DDCRC_DPMS_ASLEEP, "/dev/i2c-%d", dh->dref->io_path.path.i2c_busno); } DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, err, ""); return err; } #ifdef UNUSED Bit_Set_256 check_edids(GPtrArray * buses) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "buses=%p, len=%d", buses, buses->len); Bit_Set_256 result = EMPTY_BIT_SET_256; for (int ndx = 0; ndx < buses->len; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(buses, ndx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_open_bus.."); bool ok = i2c_check_edid_exists_by_businfo(businfo); if (ok) bs256_insert(result, businfo->busno); } DBGTRC_RETURNING(debug, TRACE_GROUP, "%s", bs256_to_string(result, "", ", ")); return result; } #endif // // I2C Bus Inspection - Fill in and report Bus_Info // #ifdef UNUSED /** The EDID can be read in several ways. This function exists to * verify that these methods obtain the same value. It should be * used only for test purposes. * - value currently in struct I2C_Bus_Info * - direct read using I2C * - edid attribute in sysfs card-connector directory * - using the DRM API * * @param fd file descriptor for open /dev/i2c bus * @param businfo I2C_Bus_Info struct */ void compare_edid_read_methods(int fd, I2C_Bus_Info * businfo) { assert(businfo->edid); // 1 - does sysfs bus info match directly read // if not: // 2 - trigger sysfs reread // 2a - does value read from drm match directly read value? // 2b - does value now read from sysfs match directly read value? bool debug = true; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d", businfo->busno); Parsed_Edid * true_i2c_edid; DDCA_Status ddcrc = i2c_get_parsed_edid_by_fd(fd, &true_i2c_edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, i2c_get_parsed_edid_by_fd() returned %s", businfo->busno, psc_desc(ddcrc)); bool reset = false; if (!true_i2c_edid) { SEVEREMSG("EDID read from sysfs but not from I2C. Discarding sysfs value"); reset = true; } else if (memcmp( businfo->edid->bytes, true_i2c_edid->bytes, 128) != 0) { SEVEREMSG("busno=%d, Edid from sysfs does not match value read from i2c", businfo->busno); reset = true; } else { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, Edid initially read from sysfs matches direct read from I2C", businfo->busno); } if (reset) { free_parsed_edid(businfo->edid); businfo->flags &= ~ I2C_BUS_HAS_EDID; if (use_drm_connector_states) { DBGMSG("Resetting sysfs data using redetect_connector_states()"); redetect_drm_connector_states(); } // get the edid from connector states DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Getting edid from Drm Connector States for connector %s", businfo->drm_connector_name); Drm_Connector_Identifier dci = parse_sys_drm_connector_name(businfo->drm_connector_name); if (use_drm_connector_states) { Drm_Connector_State * cstate = find_drm_connector_state(dci); if (cstate) { if (cstate->edid && true_i2c_edid) { if (memcmp(true_i2c_edid->bytes, cstate->edid->bytes, 128) == 0) { DBGMSG("Correct edid now read from drm connector state"); } else { SEVEREMSG("Incorrect edid read from drm connector state"); } } else if (cstate->edid && !true_i2c_edid) { SEVEREMSG("edid that should be nonexistent read from drm"); } else if (!cstate->edid && true_i2c_edid) { SEVEREMSG("I2C edid exists but not read from drm"); } else { assert (!cstate->edid && !true_i2c_edid); DBGMSG("I2C edid non-existent and none read from drm"); } } else { SEVEREMSG("Drm_Connector_State not found for %s, %s", businfo->drm_connector_name, dci_repr_t(dci)); } } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Getting edid from sysfs for connector %s", businfo->drm_connector_name); GByteArray* sysfs_edid_bytes = NULL; // int d = IS_DBGTRC(debug, TRACE_GROUP) ? 1 : -1; int d = -1; RPT_ATTR_EDID(d, &sysfs_edid_bytes, "/sys/class/drm", businfo->drm_connector_name, "edid"); if (sysfs_edid_bytes && true_i2c_edid) { if (memcmp(true_i2c_edid->bytes, sysfs_edid_bytes, 128) == 0) { DBGMSG("Correct edid now read from sysfs"); } else { SEVEREMSG("Incorrect edid still read from sysfs"); } } else if (sysfs_edid_bytes && !true_i2c_edid) { SEVEREMSG("edid that should be nonexistent read from sysfs"); } else if (!sysfs_edid_bytes && true_i2c_edid) { SEVEREMSG("I2C edid exists but not read from sysfs"); } else { assert (!sysfs_edid_bytes && !true_i2c_edid); DBGMSG("I2C edid non-existent and none read from sysfs"); } } if (true_i2c_edid) { free_parsed_edid(true_i2c_edid); } if (reset) { free_parsed_edid(businfo->edid); businfo->edid = NULL; } DBGTRC_DONE(debug, TRACE_GROUP, ""); } #endif bool is_displaylink_device(int busno) { bool debug = false; bool result = false; char bus_path[40]; g_snprintf(bus_path, 40, "/sys/bus/i2c/devices/i2c-%d", busno); char * name; RPT_ATTR_TEXT((debug)? 1 : -1, &name, bus_path, "name"); if (name) { result = streq(name, "DisplayLink I2C Adapter"); free(name); } return result; } typedef struct { char * connector_name; int connector_id; Drm_Connector_Found_By found_by; } Find_Sys_Drm_Connector_Result; void free_find_sys_drm_connector_result_contents(Find_Sys_Drm_Connector_Result rec) { free(rec.connector_name); } void dbgrpt_find_sys_drm_connector_result(Find_Sys_Drm_Connector_Result val, int depth) { rpt_vstring(depth, "Find_Sys_Drm_Connector_Result:"); rpt_vstring(depth+1, "connector_name: %s", val.connector_name); rpt_vstring(depth+1, "connector_id: %d", val.connector_id); rpt_vstring(depth+1, "found_by: %s", drm_connector_found_by_name(val.found_by)); } // n. result returned on stack Find_Sys_Drm_Connector_Result find_sys_drm_connector_by_busno_or_edid( int busno, Byte * edid_bytes) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, " busno = %d, edid = %p" , busno, edid_bytes); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "edid=%p -> %s", edid_bytes, edid_summary_from_bytes(edid_bytes)); int d = (IS_DBGTRC(debug, DDCA_TRC_NONE)) ? 1 : -1; if (busno == 255) // happens somehow busno = -1; bool check_busno = (busno != -1); bool check_edid = edid_bytes; assert(check_busno || check_edid); Find_Sys_Drm_Connector_Result result; result.connector_name = NULL; result.found_by = DRM_CONNECTOR_NOT_FOUND; result.connector_id = 0; Sysfs_Connector_Names cnames = get_sysfs_drm_connector_names(); GPtrArray * drm_connector_names = cnames.all_connectors; bool found = false; for (int ndx = 0; ndx < drm_connector_names->len && !found; ndx++) { char * cname = g_ptr_array_index(drm_connector_names, ndx); if (check_busno) { Connector_Bus_Numbers * cbn = calloc(1, sizeof(Connector_Bus_Numbers)); get_connector_bus_numbers("/sys/class/drm", cname, cbn); if (cbn->i2c_busno == busno){ found = true; result.connector_name = strdup(cname); result.found_by = DRM_CONNECTOR_FOUND_BY_BUSNO; result.connector_id = cbn->connector_id; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Found connector %s by i2c bus number match for bus i2c-%d", cname, busno); } free_connector_bus_numbers(cbn); } if (check_edid) { // don't bother if we already have the answer if (result.found_by != DRM_CONNECTOR_FOUND_BY_BUSNO) { GByteArray* edid_bytes_array = NULL; possibly_write_detect_to_status_by_connector_name(cname); RPT_ATTR_EDID(d, &edid_bytes_array, "/sys/class/drm", cname, "edid"); if (edid_bytes_array && edid_bytes_array->len >= 128) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Got edid from sysfs: %s", edid_summary_from_bytes(edid_bytes_array->data)); if (memcmp(edid_bytes_array->data, edid_bytes, 128) == 0) { found = true; result.connector_name = strdup(cname); result.found_by = DRM_CONNECTOR_FOUND_BY_EDID; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Found connector %s by EDID match for bus i2c-%d", cname, busno); } g_byte_array_free(edid_bytes_array, true); } } } } free_sysfs_connector_names_contents(cnames); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { dbgrpt_find_sys_drm_connector_result(result, 1); } DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); return result; } /** Returns the value of the edid attribute for a DRM connector. * * @param connector_name * @return pointer to EDID bytes, caller responsible for freeing * NULL if not found */ Byte * get_connector_edid(const char * connector_name) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "connector_name = %s", connector_name); int d = (debug) ? 1 : -1; // char * driver = get_i2c_sysfs_driver_by_busno(busno); // where to get busno; // maybe_write_detect_to_status("nvidia", connector_name); // lie Byte * result = NULL; GByteArray* edid_bytes = NULL; possibly_write_detect_to_status_by_connector_name(connector_name); RPT_ATTR_EDID(d, &edid_bytes, "/sys/class/drm", connector_name, "edid"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "edid_bytes=%p", edid_bytes); if (edid_bytes && edid_bytes->len >= 128) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "edid_bytes->len=%d", edid_bytes->len); result = edid_bytes->data; g_byte_array_free(edid_bytes, false); } else { if (edid_bytes) { // handle pathological case of < 128 bytes read g_byte_array_free(edid_bytes, true); } } DBGTRC_DONE(debug, DDCA_TRC_NONE, "result = %p", result); if (IS_DBGTRC(debug, DDCA_TRC_NONE) && result) rpt_hex_dump(result, 128, 2); return result; } #ifdef IRRELEVANT BS256 possible_buses = i2c_detect_attached_buses_as_bitset(); // excludes SMBUS devices etc. Bit_Set_256 iter = bs256_iter_new(possible_buses); while(true) { int busno_to_check = bs256_iter_next(iter); if (busno_to_check < 0) break; /// } #endif /** Checks if an I2C bus has an EDID * * @param busno * @return true/false */ bool i2c_edid_exists(int busno) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d", busno); // int d = ( IS_DBGTRC(debug, TRACE_GROUP) ) ? 1 : -1; assert(busno >= 0); assert(busno != 255); char sysfs_name[30]; char dev_name[15]; char i2cN[10]; // only need 8, but coverity complains g_snprintf(i2cN, 10, "i2c-%d", busno); g_snprintf(sysfs_name, 30, "/sys/bus/i2c/devices/%s", i2cN); g_snprintf(dev_name, 15, "/dev/%s", i2cN); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "sysfs_name = |%s|, dev_name = |%s|", sysfs_name, dev_name); bool edid_exists = false; char * drm_connector_name = NULL; Error_Info *master_err = NULL; if (!i2c_device_exists(busno)) { goto bye; } Error_Info * err = i2c_check_device_access(dev_name); if (err != NULL) { errinfo_free(err); // for now goto bye; } if ( sysfs_is_ignorable_i2c_device(busno) ) { goto bye; } bool is_displaylink = is_displaylink_device(busno); // *** Try to find the drm connector by bus number // n. will fail for MST DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Finding DRM connector name for bus %s using busno", dev_name); Find_Sys_Drm_Connector_Result res = find_sys_drm_connector_by_busno_or_edid(busno, NULL); if (res.connector_name) { drm_connector_name = strdup(res.connector_name); free_find_sys_drm_connector_result_contents(res); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "DRM connector not found by busno %d", busno); } // *** Possibly try to get the EDID from sysfs bool checked_connector_for_edid = false; if (drm_connector_name) { // i.e. DRM_CONNECTOR_FOUND_BY_BUSNO if ((try_get_edid_from_sysfs_first && is_sysfs_reliable_for_busno(busno) && !primitive_sysfs ) || is_displaylink) // X50 can't be read for DisplayLink, must use sysfs { checked_connector_for_edid = true; Byte * edidbytes = get_connector_edid(drm_connector_name); if (edidbytes) { edid_exists = true; free(edidbytes); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Retrieved edid using DRM connector %s", drm_connector_name); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Failed to get edid using DRM connector %s", drm_connector_name); } } } if (checked_connector_for_edid) goto bye; // *** Open bus DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_open_bus for /dev/i2c-%d..", busno); int fd = -1; master_err = i2c_open_bus(busno, CALLOPT_WAIT, &fd); #ifdef ALT_LOCK_REC master_err = i2c_open_bus(businfo->busno, businfo->CALLOPT_WAIT, &fd); #endif if (master_err) { goto bye; } //open succeeded DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Opened bus /dev/i2c-%d", busno); Buffer * rawedidbuf = buffer_new(EDID_BUFFER_SIZE, NULL); Status_Errno_DDC rc = i2c_get_raw_edid_by_fd(fd, rawedidbuf); if (rc == 0) { edid_exists = true; } buffer_free(rawedidbuf, NULL); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Closing bus..."); i2c_close_bus(busno, fd, CALLOPT_ERR_MSG); bye: free(drm_connector_name); ERRINFO_FREE_WITH_REPORT(master_err, true); DBGTRC_RET_BOOL(debug, TRACE_GROUP, edid_exists, ""); return edid_exists; } // // Functions used only by i2c_check_bus(), but factored out to clarify // the function logic // Parsed_Edid * get_parsed_edid_for_businfo_using_sysfs(I2C_Bus_Info * businfo) { assert(businfo); bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "businfo = %p, businfo->busno=%d", businfo, businfo->busno); Parsed_Edid * pedid = NULL; // maybe_write_detect_to_status(businfo->driver, businfo->drm_connector_name); Byte * edidbytes = get_connector_edid(businfo->drm_connector_name); if (edidbytes) { pedid = create_parsed_edid2(edidbytes, "SYSFS"); if (!pedid) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Invalid EDID read from /sys/class/drm/%s/edid", businfo->drm_connector_name); SYSLOG2(DDCA_SYSLOG_ERROR, "Invalid EDID read from /sys/class/drm/%s/edid", businfo->drm_connector_name); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Found edid for /dev/i2c-%d using connector name %s", businfo->busno, businfo->drm_connector_name); } free(edidbytes); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Failed to get edid using DRM connector %s", businfo->drm_connector_name); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning %p", pedid); return pedid; } bool is_adapter_class_display_controller(const char * adapter_class) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "class = %s", adapter_class); bool result = true; uint32_t cl2 = 0; uint32_t i_class = 0; /* bool ok =*/ str_to_int(adapter_class, (int*) &i_class, 16); // if fails, &result unchanged cl2 = i_class & 0xffff0000; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "cl2 = 0x%08x", cl2); if (cl2 != 0x030000 && cl2 != 0x0a0000 /* docking station*/ ) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Device class not a display driver: 0x%08x", cl2); result = false; } DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, ""); return result; } void set_connector_for_businfo_using_edid(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "Finding DRM connector name for bus i2c-%d using EDID", businfo->busno); assert(businfo->edid); businfo->drm_connector_name = NULL; Find_Sys_Drm_Connector_Result conres = // n.b. struct returned on stack, not pointer find_sys_drm_connector_by_busno_or_edid(-1, businfo->edid->bytes); if (conres.connector_name) { businfo->drm_connector_name = conres.connector_name; businfo->drm_connector_found_by = DRM_CONNECTOR_FOUND_BY_EDID; businfo->drm_connector_id = conres.connector_id; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Finding connector name for /dev/i2c-%d using EDID found: %s", businfo->busno, businfo->drm_connector_name); } else { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "Failed to find connector name for /dev/i2c-%d using EDID %p", businfo->busno, businfo->edid->bytes); start_capture(DDCA_CAPTURE_STDERR); rpt_vstring(0, "Failed to find connector name for /dev/i2c-%d, %s at line %d in file %s. ", businfo->busno, __func__, __LINE__, __FILE__); i2c_dbgrpt_bus_info(businfo, /*include_sysinfo*/ true, 1); rpt_nl(); report_sys_drm_connectors(true, 1); Null_Terminated_String_Array lines = end_capture_as_ntsa(); for (int ndx=0; lines[ndx]; ndx++) { LOGABLE_MSG(DDCA_SYSLOG_ERROR, "%s", lines[ndx]); } ntsa_free(lines, true); } DBGTRC_DONE(debug, DDCA_TRC_NONE,""); } bool is_laptop_for_businfo(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "businfo=%p, busno=%d", businfo, businfo->busno); bool is_laptop = false; if (businfo->drm_connector_name) { if ( is_laptop_drm_connector_name(businfo->drm_connector_name) ) { // double check, eDP has been seen to be applied to external display, see: // ddcutil issue #384 // freedesktop.org issue #10389, DRM connector for external monitor has name card1-eDP-1 bool b = is_laptop_parsed_edid(businfo->edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "connector name = %s, is_laptop_parsed_edid() returned %s", businfo->drm_connector_name, SBOOL(b)); if (b) { businfo->flags |= I2C_BUS_LVDS_OR_EDP; is_laptop = true; } } } else { if ( is_laptop_parsed_edid(businfo->edid) ) { businfo->flags |= I2C_BUS_APPARENT_LAPTOP; is_laptop = true; } } ASSERT_IFF(is_laptop, businfo->flags & (I2C_BUS_LVDS_OR_EDP | I2C_BUS_APPARENT_LAPTOP)); DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, is_laptop, ""); return is_laptop; } bool check_x37_for_businfo(int fd, I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "fd=%d, businfo=%p, use_x37_detection_table=%s", fd, businfo, SBOOL(use_x37_detection_table)); bool first_x37_check = true; X37_Detection_State x37_detection_state = X37_Not_Recorded; if (use_x37_detection_table) { x37_detection_state = i2c_query_x37_detected(businfo->busno, businfo->edid->bytes); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Restored(1) %s", x37_detection_state_name(x37_detection_state)); if (x37_detection_state == X37_Detected) { businfo->flags |= I2C_BUS_ADDR_X37; first_x37_check=false; } } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "first_x37_check = %s", SBOOL(first_x37_check)); if (x37_detection_state != X37_Detected) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_detect_x37() for /dev/i2c-%d...", businfo->busno); int rc = i2c_detect_x37(fd, businfo->driver); // if (rc == -EBUSY) // businfo->flags |= I2C_BUS_BUSY; #ifdef TEST if (rc == 0) { if (businfo->busno == 6 || businfo->busno == 8) { rc = -EBUSY; DBGMSG("Forcing -EBUSY on i2c_detect_37()"); } } #endif DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "/dev/i2c-%d. i2c_detect_x37() returned %s", businfo->busno, psc_desc(rc)); if (rc == 0) { businfo->flags |= I2C_BUS_ADDR_X37; x37_detection_state = X37_Detected; } else x37_detection_state = X37_Not_Detected; if (use_x37_detection_table) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Recording %s", x37_detection_state_name(x37_detection_state)); i2c_record_x37_detected(businfo->busno, businfo->edid->bytes, x37_detection_state); } if (first_x37_check) { businfo->flags &= ~I2C_BUS_DDC_CHECKS_IGNORABLE; } } bool result = (x37_detection_state == X37_Detected); DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, "I2C_DDC_CHECKS_IGNORABLE is set: %s", SBOOL(businfo->flags&I2C_BUS_DDC_CHECKS_IGNORABLE) ); return result; } /** Inspects an I2C bus. * * Takes the number of the bus to be inspected from the #I2C_Bus_Info struct passed * as an argument. * * @param businfo pointer to #I2C_Bus_Info struct in which information will be set * @return status code */ Status_Errno i2c_check_bus(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, businfo=%p, primitive_sysfs=%s", businfo->busno, businfo, SBOOL(primitive_sysfs) ); assert(businfo && ( memcmp(businfo->marker, I2C_BUS_INFO_MARKER, 4) == 0) ); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "businfo->flags = 0x%04x = %s", businfo->flags, i2c_interpret_bus_flags_t(businfo->flags)); if (debug) { show_backtrace(1); } // int d = ( IS_DBGTRC(debug, TRACE_GROUP) ) ? 1 : -1; assert(businfo->busno >= 0); assert(businfo->busno != 255); bool try_get_edid_from_sysfs_first = true; // int busno = businfo->busno; char sysfs_name[30]; char dev_name[15]; char i2cN[10]; // only need 8, but coverity complains g_snprintf(i2cN, 10, "i2c-%d", businfo->busno); g_snprintf(sysfs_name, 30, "/sys/bus/i2c/devices/%s", i2cN); g_snprintf(dev_name, 15, "/dev/%s", i2cN); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "sysfs_name = |%s|, dev_name = |%s|", sysfs_name, dev_name); // int d = (IS_DBGTRC(debug, DDCA_TRC_NONE)) ? 1 : -1; int ddcrc = 0; businfo->flags |= I2C_BUS_PROBED; Error_Info *master_err = NULL; if (!i2c_device_exists(businfo->busno)) { master_err = ERRINFO_NEW(-ENOENT, "Device does not exist: /dev/i2c-%d", businfo->busno); goto bye; } master_err = i2c_check_device_access(dev_name); if (master_err != NULL) { // if (err->status_code != -ENOENT) businfo->open_errno = master_err->status_code; // errinfo_free(err); // for now goto bye; } if (!primitive_sysfs) { if (!businfo->driver) { Sysfs_I2C_Info * driver_info = get_i2c_driver_info(businfo->busno, -1); businfo->driver = g_strdup(driver_info->driver); // ** LEAKY // perhaps save businfo->driver_version // assert(driver_info->adapter_class); bool is_video_driver = false; if (driver_info->adapter_class) { is_video_driver = is_adapter_class_display_controller(driver_info->adapter_class); } if (!is_video_driver) { master_err = ERRINFO_NEW(DDCRC_OTHER, "Display controller for bus %d has class %s", businfo->busno, driver_info->adapter_class); free_sysfs_i2c_info(driver_info); goto bye; } free_sysfs_i2c_info(driver_info); } } businfo->flags |= I2C_BUS_EXISTS; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "initial flags = %s", i2c_interpret_bus_flags_t(businfo->flags)); if (is_displaylink_device(businfo->busno)) businfo->flags |= I2C_BUS_DISPLAYLINK; if (is_sysfs_reliable_for_busno(businfo->busno)) businfo->flags |= I2C_BUS_SYSFS_KNOWN_RELIABLE; // *** Try to find the drm connector by bus number if (!businfo->drm_connector_name) { // i.e. this is a recheck //assert(businfo->drm_connector_found_by == DRM_CONNECTOR_NOT_CHECKED || // businfo->drm_connector_found_by == DRM_CONNECTOR_NOT_FOUND); businfo->drm_connector_found_by = DRM_CONNECTOR_NOT_CHECKED; // n. will fail for MST DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Finding DRM connector name for bus %s using busno", dev_name); Find_Sys_Drm_Connector_Result res = find_sys_drm_connector_by_busno_or_edid(businfo->busno, NULL); if (res.connector_name) { businfo->drm_connector_name = strdup(res.connector_name); // *** LEAKS *** businfo->drm_connector_found_by = DRM_CONNECTOR_FOUND_BY_BUSNO; businfo->drm_connector_id = res.connector_id; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Found DRM connector name %s by busno, found_by=%s", businfo->drm_connector_name, drm_connector_found_by_name(businfo->drm_connector_found_by)); free_find_sys_drm_connector_result_contents(res); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "DRM connector not found by busno %d", businfo->busno); } } // *** Possibly try to get the EDID from sysfs bool checked_connector_for_edid = false; if (businfo->drm_connector_name) { // i.e. DRM_CONNECTOR_FOUND_BY_BUSNO // assert(businfo->drm_connector_found_by == DRM_CONNECTOR_FOUND_BY_BUSNO); if ((try_get_edid_from_sysfs_first && businfo->flags&I2C_BUS_SYSFS_KNOWN_RELIABLE) || (businfo->flags&I2C_BUS_DISPLAYLINK)) // X50 can't be read for DisplayLink, must use sysfs { Parsed_Edid * edid = get_parsed_edid_for_businfo_using_sysfs(businfo); if (edid) { businfo->edid = edid; businfo->flags |= I2C_BUS_SYSFS_EDID; } checked_connector_for_edid = true; } } // *** Open bus DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_open_bus for /dev/i2c-%d..", businfo->busno); int fd = -1; master_err = i2c_open_bus(businfo->busno, CALLOPT_WAIT, &fd); #ifdef ALT_LOCK_REC master_err = i2c_open_bus(businfo->busno, businfo->CALLOPT_WAIT, &fd); #endif if (master_err) { businfo->open_errno = master_err->status_code; goto bye; } //open succeeded DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Opened bus /dev/i2c-%d", businfo->busno); businfo->flags |= I2C_BUS_ACCESSIBLE; businfo->functionality = i2c_get_functionality_flags_by_fd(fd); // is this really needed? #ifdef TEST_EDID_SMBUS if (EDID_Read_Uses_Smbus) { // for the smbus hack assert(businfo->functionality & I2C_FUNC_SMBUS_READ_BYTE_DATA); } #endif if (!checked_connector_for_edid) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, calling i2c_get_parsed_edid", businfo->busno); assert(!businfo->edid); DDCA_Status ddcrc = i2c_get_parsed_edid_by_fd(fd, &businfo->edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, i2c_get_parsed_edid_by_fd() returned %s", businfo->busno, psc_desc(ddcrc)); // NB It's quite possible that bus has no edid if (ddcrc == 0) { businfo->flags |= I2C_BUS_X50_EDID; } else { // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, i2c_get_parsed_edid_by_fd() returned %s", // businfo->busno, psc_desc(ddcrc)); } } // If there's an EDID on the bus and we don't yet have the connector name // based on a busno match, try EDID match if (!businfo->drm_connector_name && businfo->edid) { set_connector_for_businfo_using_edid(businfo); } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Bus %s: connector_name=%s, found by: %s", dev_name, businfo->drm_connector_name, drm_connector_found_by_name(businfo->drm_connector_found_by)); if (businfo->drm_connector_found_by == DRM_CONNECTOR_NOT_CHECKED) businfo->drm_connector_found_by = DRM_CONNECTOR_NOT_FOUND; // *** Check if laptop bool is_laptop = false; if (businfo->edid && !(businfo->flags&I2C_BUS_DISPLAYLINK)) { is_laptop = is_laptop_for_businfo(businfo); } // *** Check x37 if (is_laptop) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Laptop display detected, not checking x37"); } else if (businfo->edid) { // start, x37 check Monitor_Model_Key mmk = mmk_value_from_edid(businfo->edid); bool disabled_mmk = is_disabled_mmk(mmk); if (disabled_mmk) { businfo->flags |= I2C_BUS_DDC_DISABLED; } else { // The check here for slave address x37 had previously been removed. // It was commented out in commit 78fb4b on 4/29/2013, and the code // finally delete by commit f12d7a on 3/20/2020, with the following // comments: // have seen case where laptop display reports addr 37 active, but // it doesn't respond to DDC // 8/2017: If DDC turned off on U3011 monitor, addr x37 still detected // DDC checking was therefore moved entirely to the DDC layer. // 6/25/2023: // Testing for slave address x37 turns out to be needed to avoid // trying to reload cached display information for a display no // longer present check_x37_for_businfo(fd,businfo); } } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Closing bus..."); i2c_close_bus(businfo->busno, fd, CALLOPT_ERR_MSG); // doesn't really belong here businfo->last_checked_dpms_asleep = dpms_check_drm_asleep_by_businfo(businfo); businfo->flags |= I2C_BUS_INITIAL_CHECK_DONE; bye: if ( IS_DBGTRC(debug, TRACE_GROUP)) { DBGTRC_NOPREFIX(true, TRACE_GROUP, "busno=%d, flags = %s", businfo->busno, i2c_interpret_bus_flags_t(businfo->flags)); // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "businfo:"); // i2c_dbgrpt_bus_info(businfo, 2); if (master_err) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "businfo:"); i2c_dbgrpt_bus_info(businfo, /* include_sysinfo */ true, 2); ddcrc = master_err->status_code; ERRINFO_FREE_WITH_REPORT(master_err, true); } } else { if (master_err) { ddcrc = master_err->status_code; ERRINFO_FREE_WITH_REPORT(master_err, false); } } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, ""); return ddcrc; } // i2c_check_bus #ifdef OUT void i2c_recheck_bus(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, businfo=%p, flags=%s", businfo->busno, businfo, i2c_interpret_bus_flags(businfo->flags) ); assert(businfo && ( memcmp(businfo->marker, I2C_BUS_INFO_MARKER, 4) == 0) ); // show_backtrace(1); // int d = ( IS_DBGTRC(debug, TRACE_GROUP) ) ? 1 : -1; assert(businfo->busno >= 0); assert(businfo->busno != 255); // bool try_get_edid_from_sysfs_first = true; // int busno = businfo->busno; char sysfs_name[30]; char dev_name[15]; char i2cN[10]; // only need 8, but coverity complains g_snprintf(i2cN, 10, "i2c-%d", businfo->busno); g_snprintf(sysfs_name, 30, "/sys/bus/i2c/devices/%s", i2cN); g_snprintf(dev_name, 15, "/dev/%s", i2cN); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "sysfs_name = |%s|, dev_name = |%s|", sysfs_name, dev_name); // int d = (IS_DBGTRC(debug, DDCA_TRC_NONE)) ? 1 : -1; i2c_reset_bus_info(businfo); businfo->flags |= I2C_BUS_PROBED; Error_Info *master_err = NULL; // if (!i2c_device_exists(businfo->busno)) // goto bye; master_err = i2c_check_device_access(dev_name); if (master_err != NULL) { goto bye; } businfo->flags |= I2C_BUS_EXISTS | I2C_BUS_ACCESSIBLE; assert(businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_CHECKED); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "flags after i2c_reset_bus() and i2c_check_bus_access() = %s", i2c_interpret_bus_flags_t(businfo->flags)); // *** Possibly try to get the EDID from sysfs bool checked_connector_for_edid = false; if ( !(businfo->drm_connector_found_by == DRM_CONNECTOR_NOT_FOUND) && !(businfo->flags&I2C_BUS_SYSFS_UNRELIABLE) ) { checked_connector_for_edid = true; Byte * edidbytes = get_connector_edid(businfo->drm_connector_name); if (edidbytes) { businfo->edid = create_parsed_edid2(edidbytes, "SYSFS"); if (!businfo->edid) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Invalid EDID read from /sys/class/drm%s/edid", businfo->drm_connector_name); } else { businfo->flags |= I2C_BUS_SYSFS_EDID; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Found edid for %s using connector name %s", dev_name, businfo->drm_connector_name); } free(edidbytes); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Failed to get edid using DRM connector %s", businfo->drm_connector_name); } } else { assert(businfo->drm_connector_found_by == DRM_CONNECTOR_NOT_FOUND); } X37_Detection_State x37_detection_state = X37_Not_Recorded; if (businfo->edid) { x37_detection_state = i2c_query_x37_detected(businfo->busno, businfo->edid->bytes); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Restored(1) %s", x37_detection_state_name(x37_detection_state)); if (x37_detection_state == X37_Detected) { businfo->flags |= I2C_BUS_ADDR_X37; } } if (!checked_connector_for_edid || x37_detection_state != X37_Not_Recorded) { // *** Open bus DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_open_bus for /dev/i2c-%d..", businfo->busno); int fd = -1; master_err = i2c_open_bus(businfo->busno, CALLOPT_WAIT, &fd); #ifdef ALT_LOCK_REC master_err = i2c_open_bus(businfo->busno, businfo->CALLOPT_WAIT, &fd); #endif if (master_err) { businfo->open_errno = master_err->status_code; goto bye; } //open succeeded DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Opened bus /dev/i2c-%d", businfo->busno); businfo->flags |= I2C_BUS_ACCESSIBLE; if (!checked_connector_for_edid) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, calling i2c_get_parsed_edid", businfo->busno); DDCA_Status ddcrc = i2c_get_parsed_edid_by_fd(fd, &businfo->edid); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, i2c_get_parsed_edid_by_fd() returned %s", businfo->busno, psc_desc(ddcrc)); // NB It's quite possible that bus has no edid if (ddcrc == 0) { businfo->flags |= I2C_BUS_X50_EDID; } } // *** Check x37 if (businfo->flags & (I2C_BUS_LVDS_OR_EDP)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Laptop display detected, not checking x37"); } else if (businfo->edid) { // start, x37 check x37_detection_state = i2c_query_x37_detected(businfo->busno, businfo->edid->bytes); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Restored(2) %s", x37_detection_state_name(x37_detection_state)); if (x37_detection_state == X37_Not_Recorded) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_detect() for /dev/i2c-%d...", businfo->busno); int rc = i2c_detect_x37(fd); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "%s. i2c_detect_x37() returned %s", dev_name, psc_desc(rc)); X37_Detection_State detection_state = X37_Not_Detected; if (rc == 0) { businfo->flags |= I2C_BUS_ADDR_X37; detection_state = X37_Detected; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Recording %s", x37_detection_state_name(detection_state)); i2c_record_x37_detected(businfo->busno, businfo->edid->bytes, detection_state); } else { if (x37_detection_state == X37_Detected) { businfo->flags |= I2C_BUS_ADDR_X37; } } } // end x37 check DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Closing bus..."); i2c_close_bus(businfo->busno, fd, CALLOPT_ERR_MSG); } // doesn't really belong here businfo->last_checked_dpms_asleep = dpms_check_drm_asleep_by_businfo(businfo); bye: businfo->flags |= I2C_BUS_PROBED; if ( IS_DBGTRC(debug, TRACE_GROUP)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "busno=%d, flags = %s", businfo->busno, i2c_interpret_bus_flags_t(businfo->flags)); // DBGTRC_NOPREFIX(debug, TRACE_GROUP, "businfo:"); // i2c_dbgrpt_bus_info(businfo, 2); DBGTRC_DONE(true, TRACE_GROUP, "busno=%d", businfo->busno); ERRINFO_FREE_WITH_REPORT(master_err, true); } else { ERRINFO_FREE_WITH_REPORT(master_err, false); } } #endif STATIC void * i2c_threaded_initial_checks_by_businfo(gpointer data) { bool debug = false; I2C_Bus_Info * businfo = data; TRACED_ASSERT(memcmp(businfo->marker, I2C_BUS_INFO_MARKER, 4) == 0 ); DBGTRC_STARTING(debug, TRACE_GROUP, "bus = /dev/i2c-%d", businfo->busno ); i2c_check_bus(businfo); // g_thread_exit(NULL); DBGTRC_DONE(debug, TRACE_GROUP, "Returning NULL. bus=/dev/i2c-%d", businfo->busno ); free_current_traced_function_stack(); return NULL; } /** Spawns threads to perform initial checks and waits for them all to complete. * * @param all_displays #GPtrArray of pointers to #I2c_Bus_Info */ STATIC void i2c_async_scan(GPtrArray * i2c_buses) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "i2c_buses=%p, bus count=%d", i2c_buses, i2c_buses->len); GPtrArray * threads = g_ptr_array_new(); for (int ndx = 0; ndx < i2c_buses->len; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(i2c_buses, ndx); TRACED_ASSERT( memcmp(businfo->marker, I2C_BUS_INFO_MARKER, 4) == 0 ); char buf[16]; g_snprintf(buf, 16, "/dev/i2c-%d", businfo->busno); GThread * th = g_thread_new( buf, // thread name i2c_threaded_initial_checks_by_businfo, businfo); // pass pointer to display ref as data g_ptr_array_add(threads, th); } DBGMSF(debug, "Started %d threads", threads->len); for (int ndx = 0; ndx < threads->len; ndx++) { GThread * thread = g_ptr_array_index(threads, ndx); g_thread_join(thread); // implicitly unrefs the GThread } DBGMSF(debug, "Threads joined"); g_ptr_array_free(threads, true); DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Loops through a list of I2C_Bus_Info, performing initial checks on each. * * @param i2c_buses #GPtrArray of pointers to #I2C_Bus_Info */ void i2c_non_async_scan(GPtrArray * i2c_buses) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "checking %d buses", i2c_buses->len); for (int ndx = 0; ndx < i2c_buses->len; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(i2c_buses, ndx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_check_bus() synchronously for bus %d", businfo->busno); i2c_check_bus(businfo); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Attached buses // // moved from udev_i2c_util.c /** Gets the numbers of I2C devices * * \param include_ignorable_devices if true, do not exclude SMBus and other ignorable devices * \return sorted #Byte_Value_Array of I2C device numbers, caller is responsible for freeing */ Byte_Value_Array get_i2c_device_numbers_using_udev(bool include_ignorable_devices) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "include_ignorable_devices=%s", SBOOL(include_ignorable_devices)); Byte_Value_Array bva = bva_create(); GPtrArray * summaries = get_i2c_devices_using_udev(); if (summaries) { for (int ndx = 0; ndx < summaries->len; ndx++) { Udev_Device_Summary * summary = g_ptr_array_index(summaries, ndx); int busno = udev_i2c_device_summary_busno(summary); assert(busno >= 0); assert(busno <= 127); if ( include_ignorable_devices || !sysfs_is_ignorable_i2c_device(busno) ) bva_append(bva, busno); } free_udev_device_summaries(summaries); } char * s = bva_as_string(bva, /*as_hex*/ false, ","); DBGTRC_DONE(debug, TRACE_GROUP, "Returning I2C bus numbers: %s", s); free(s); // bva_report(bva, "Returning I2c bus numbers:"); return bva; } Bit_Set_256 attached_buses; /** Returns the bus numbers for /dev/i2c buses that could possibly be * connected to a monitor.: * * @return array of bus numbers */ Byte_Value_Array i2c_detect_attached_buses() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, ""); #ifdef ENABLE_UDEV // perhaps slightly faster TODO: perform test // do not include devices with ignorable name, etc.: Byte_Value_Array i2c_bus_bva = get_i2c_device_numbers_using_udev(/*include_ignorable_devices=*/ false); #else Byte_Value_Array i2c_bus_bva = get_i2c_devices_by_existence_test(/*include_ignorable_devices=*/ false); #endif char * s = bva_as_string(i2c_bus_bva, false, ", "); DBGTRC_DONE(debug, DDCA_TRC_NONE, "possible i2c device bus numbers: %s", s); free(s); return i2c_bus_bva;; } /** Returns the bus numbers for /dev/i2c buses that could possibly be * connected to a monitor. * * @return bitset of bus numbers */ Bit_Set_256 i2c_detect_attached_buses_as_bitset() { Byte_Value_Array bva = i2c_detect_attached_buses(); Bit_Set_256 cur_buses = bs256_from_bva(bva); bva_free(bva); return cur_buses; } Bit_Set_256 i2c_filter_buses_w_edid_as_bitset(BS256 bs_all_buses) { BS256 bs_buses_w_edid = EMPTY_BIT_SET_256; Bit_Set_256_Iterator iter = bs256_iter_new(bs_all_buses); int bitno = bs256_iter_next(iter); while (bitno >= 0) { if (i2c_edid_exists(bitno)) bs_buses_w_edid = bs256_insert(bs_buses_w_edid, bitno); bitno = bs256_iter_next(iter); } bs256_iter_free(iter); return bs_buses_w_edid; } Bit_Set_256 i2c_buses_w_edid_as_bitset() { BS256 bs_all_buses = i2c_detect_attached_buses_as_bitset(); return i2c_filter_buses_w_edid_as_bitset(bs_all_buses); } #ifdef UNUSED void i2c_check_attached_buses( Bit_Set_256* newly_attached_buses_loc, Bit_Set_256* newly_detached_buses_loc) { Bit_Set_256 cur_attached_buses = i2c_detect_attached_buses_as_bitset(); *newly_attached_buses_loc = EMPTY_BIT_SET_256; *newly_detached_buses_loc = EMPTY_BIT_SET_256; if (!bs256_eq(cur_attached_buses, attached_buses)) { // will be rare Bit_Set_256 newly_attached_buses = bs256_and_not(cur_attached_buses, attached_buses); Bit_Set_256 newly_detached_buses = bs256_and_not(attached_buses, cur_attached_buses); *newly_attached_buses_loc = newly_attached_buses; *newly_detached_buses_loc = newly_detached_buses; } } #endif /** Detect all currently attached buses and checks each to see if a display * is connected, i.e. if an EDID is present * * @return array of #I2C_Bus_Info for all attached buses */ GPtrArray * i2c_detect_buses0() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, ""); // rpt_label(0, "*** Temporary code to exercise get_all_i2c_infos() ***"); // GPtrArray * i2c_infos = get_all_i2c_info(true, -1); // dbgrpt_all_sysfs_i2c_info(i2c_infos, 2); BS256 bs_attached_buses = i2c_detect_attached_buses_as_bitset(); Bit_Set_256_Iterator iter = bs256_iter_new(bs_attached_buses); GPtrArray * buses = g_ptr_array_sized_new(bs256_count(bs_attached_buses)); while (true) { int busno = bs256_iter_next(iter); if (busno < 0) break; I2C_Bus_Info * businfo = i2c_new_bus_info(busno); assert(businfo->drm_connector_found_by == DRM_CONNECTOR_NOT_CHECKED); businfo->flags = I2C_BUS_EXISTS; DBGMSF(debug, "Valid bus: /dev/"I2C"-%d", busno); g_ptr_array_add(buses, businfo); } bs256_iter_free(iter); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "buses->len = %d, i2c_businfo_async_threhold=%d", buses->len, i2c_businfo_async_threshold); if (buses->len < i2c_businfo_async_threshold) { i2c_non_async_scan(buses); } else { i2c_async_scan(buses); } if (debug) { for (int ndx = 0; ndx < buses->len; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(buses, ndx); i2c_dbgrpt_bus_info(businfo, true, 0); } } if (debug) { for (int ndx = 0; ndx < buses->len; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(buses, ndx); GPtrArray * conflicts = collect_conflicting_drivers(businfo->busno, -1); report_conflicting_drivers(conflicts, 1); DBGMSG("Conflicting drivers: %s", conflicting_driver_names_string_t(conflicts)); free_conflicting_drivers(conflicts); } } DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %p containing %d I2C_Bus_Info records", buses, buses->len); return buses; } I2C_Bus_Info * i2c_get_and_check_bus_info(int busno) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "busno=%d", busno); bool new_info = false; I2C_Bus_Info* businfo = i2c_get_bus_info(busno, &new_info); if (!new_info) i2c_reset_bus_info(businfo); i2c_check_bus(businfo); #ifdef OLD if (new_info | !(businfo->flags&I2C_BUS_INITIAL_CHECK_DONE)) { i2c_check_bus(businfo); } else { i2c_recheck_bus(businfo); } #endif DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning %p, new_info=%s", businfo, SBOOL(new_info)); return businfo; } /** Detect buses if not already detected. * * Stores the result in global array all_i2c_buses and also * the bitset connected_buses. * * @return number of i2c buses */ int i2c_detect_buses() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "all_i2c_buses = %p", all_i2c_buses); if (!all_i2c_buses) { all_i2c_buses = i2c_detect_buses0(); g_ptr_array_set_free_func(all_i2c_buses, (GDestroyNotify) i2c_free_bus_info); } int result = all_i2c_buses->len; DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %d", result); return result; } // used only by main.c, not shared library, does not need mutex protection I2C_Bus_Info * i2c_detect_single_bus(int busno) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "busno = %d", busno); I2C_Bus_Info * businfo = NULL; if (i2c_device_exists(busno) ) { if (!all_i2c_buses) { all_i2c_buses = g_ptr_array_sized_new(1); g_ptr_array_set_free_func(all_i2c_buses, (GDestroyNotify) i2c_free_bus_info); } businfo = i2c_new_bus_info(busno); businfo->flags = I2C_BUS_EXISTS; i2c_check_bus(businfo); if (debug) i2c_dbgrpt_bus_info(businfo, true, 0); g_ptr_array_add(all_i2c_buses, businfo); } DBGTRC_DONE(debug, DDCA_TRC_I2C, "busno=%d, returning: %p", busno, businfo); return businfo; } /** Creates a bit set in which the nth bit is set corresponding to the number * of each bus in an array of #I2C_Bus_Info, possibly restricted to those buses * for which a monitor is connected, i.e. for which an EDID is detected. * * @param buses array of I2C_Bus_Info * @param only_connected if true, only include buses having EDID * @return bit set */ Bit_Set_256 buses_bitset_from_businfo_array(GPtrArray * businfo_array, bool only_connected) { bool debug = false; assert(businfo_array); DBGTRC_STARTING(debug, TRACE_GROUP, "businfo_array=%p, len=%d, only_connected=%s", businfo_array, businfo_array->len, SBOOL(only_connected)); Bit_Set_256 result = EMPTY_BIT_SET_256; for (int ndx = 0; ndx < businfo_array->len; ndx++) { I2C_Bus_Info * businfo = g_ptr_array_index(businfo_array, ndx); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "businfo=%p", businfo); if (!only_connected || businfo->edid) { // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "EDID exists"); result = bs256_insert(result, businfo->busno); } } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %s", bs256_to_string_decimal_t(result, "", ", ")); return result; } // // I2C Bus Inquiry // #ifdef UNUSED /** Checks whether an I2C bus supports DDC. * * @param busno I2C bus number * @param callopts standard call options, used to control error messages * * @return true or false */ bool i2c_is_valid_bus(int busno, Call_Options callopts) { bool emit_error_msg = callopts & CALLOPT_ERR_MSG; bool debug = false; if (debug) { char * s = interpret_call_options_a(callopts); DBGMSG("Starting. busno=%d, callopts=%s", busno, s); free(s); } bool result = false; char * complaint = NULL; // Bus_Info * businfo = i2c_get_bus_info(busno, DISPSEL_NONE); I2C_Bus_Info * businfo = i2c_find_bus_info_by_busno(busno); if (debug && businfo) i2c_dbgrpt_bus_info(businfo, 1); bool overridable = false; if (!businfo) complaint = "I2C bus not found:"; else if (!(businfo->flags & I2C_BUS_EXISTS)) complaint = "I2C bus not found: /dev/i2c-%d\n"; else if (!(businfo->flags & I2C_BUS_ACCESSIBLE)) complaint = "Inaccessible I2C bus:"; else if (!(businfo->flags & I2C_BUS_ADDR_0X50)) { complaint = "No monitor found on bus"; overridable = true; } else if (!(businfo->flags & I2C_BUS_ADDR_X37)) complaint = "Cannot communicate DDC on I2C bus slave address 0x37"; else result = true; if (complaint && emit_error_msg) { f0printf(ferr(), "%s /dev/i2c-%d\n", complaint, busno); } if (complaint && overridable && (callopts & CALLOPT_FORCE)) { f0printf(ferr(), "Continuing. --force option was specified.\n"); result = true; } DBGMSF(debug, "Returning %s", sbool(result)); return result; } #endif // // Reports // /** Reports bus information for a single active display. * * Output is written to the current report destination. * Content shown is dependant on output level * * @param businfo bus record * @param depth logical indentation depth * * @remark * This function is used by detect, interrogate commands, C API */ void i2c_report_active_bus(I2C_Bus_Info * businfo, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "businfo=%p", businfo); assert(businfo); int d1 = depth+1; DDCA_Output_Level output_level = get_output_level(); if (output_level >= DDCA_OL_NORMAL) rpt_vstring(depth, "I2C bus: /dev/"I2C"-%d", businfo->busno); // will work for amdgpu, maybe others assert(businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_CHECKED); // if (!(businfo->flags & I2C_BUS_DRM_CONNECTOR_CHECKED)) // i2c_check_businfo_connector(businfo); int title_width = (output_level >= DDCA_OL_VERBOSE) ? 39 : 25; if (businfo->drm_connector_name && output_level >= DDCA_OL_NORMAL) { int d = (output_level >= DDCA_OL_VERBOSE) ? d1 : depth; rpt_vstring( d, "%-*s%s", title_width, "DRM connector:", (businfo->drm_connector_name) ? businfo->drm_connector_name : "Not found" ); if (output_level >= DDCA_OL_VERBOSE) { if (businfo->drm_connector_name) { char title_buf[100]; int tw = title_width; // 35; // title_width; char * attr_value = NULL; char * attr = "dpms"; attr_value = i2c_get_drm_connector_attribute(businfo, attr); g_snprintf(title_buf, 100, "/sys/class/drm/%s/%s", businfo->drm_connector_name, attr); rpt_vstring(d, "%-*s%s", tw, title_buf, attr_value); free(attr_value); attr = "enabled"; attr_value = i2c_get_drm_connector_attribute(businfo, attr); g_snprintf(title_buf, 100, "/sys/class/drm/%s/%s", businfo->drm_connector_name, attr); rpt_vstring(d, "%-*s%s", tw, title_buf, attr_value); free(attr_value); attr = "status"; attr_value = i2c_get_drm_connector_attribute(businfo, attr); g_snprintf(title_buf, 100, "/sys/class/drm/%s/%s", businfo->drm_connector_name, attr); rpt_vstring(d, "%-*s%s", tw, title_buf, attr_value); free(attr_value); attr = "connector_id"; attr_value = i2c_get_drm_connector_attribute(businfo, attr); g_snprintf(title_buf, 100, "/sys/class/drm/%s/%s", businfo->drm_connector_name, attr); rpt_vstring(d, "%-*s%s", tw, title_buf, attr_value); free(attr_value); } } } // 08/2018 Disable. // Test for DDC communication is now done more sophisticatedly at the DDC level // The simple X37 test can have both false positives (DDC turned off in monitor but // X37 responsive), and false negatives (Dell P2715Q) // if (output_level >= DDCA_OL_NORMAL) // rpt_vstring(depth, "Supports DDC: %s", sbool(businfo->flags & I2C_BUS_ADDR_0X37)); if (output_level >= DDCA_OL_VERBOSE) { rpt_vstring(d1, "Driver: %s", (businfo->driver) ? businfo->driver : "Unknown"); #ifdef DETECT_SLAVE_ADDRS rpt_vstring(d1, "I2C address 0x30 (EDID block#) present: %-5s", srepr(businfo->flags & I2C_BUS_ADDR_0X30)); #endif rpt_vstring(d1, "EDID exists: %-5s", sbool(businfo->flags & I2C_BUS_HAS_EDID)); rpt_vstring(d1, "I2C address 0x37 (DDC) responsive: %-5s", sbool(businfo->flags & I2C_BUS_ADDR_X37)); #ifdef OLD rpt_vstring(d1, "Is eDP device: %-5s", sbool(businfo->flags & I2C_BUS_EDP)); rpt_vstring(d1, "Is LVDS device: %-5s", sbool(businfo->flags & I2C_BUS_LVDS)); #endif rpt_vstring(d1, "Is LVDS or EDP display: %-5s", sbool(businfo->flags & I2C_BUS_LVDS_OR_EDP)); rpt_vstring(d1, "Is laptop display by EDID: %-5s", sbool(businfo->flags & I2C_BUS_APPARENT_LAPTOP)); rpt_vstring(d1, "Is laptop display: %-5s", sbool(businfo->flags & I2C_BUS_LAPTOP)); // if ( !(businfo->flags & (I2C_BUS_EDP|I2C_BUS_LVDS)) ) // rpt_vstring(d1, "I2C address 0x37 (DDC) responsive: %-5s", sbool(businfo->flags & I2C_BUS_ADDR_0X37)); char fn[PATH_MAX]; // yes, PATH_MAX is dangerous, but not as used here sprintf(fn, "/sys/bus/i2c/devices/i2c-%d/name", businfo->busno); char * sysattr_name = file_get_first_line(fn, /* verbose*/ false); rpt_vstring(d1, "%-*s%s", title_width, fn, sysattr_name); free(sysattr_name); sprintf(fn, "/sys/bus/i2c/devices/i2c-%d", businfo->busno); char * path = NULL; GET_ATTR_REALPATH(&path, fn); rpt_vstring(d1, "PCI device path: %s", path); free(path); #ifdef REDUNDANT #ifndef TARGET_BSD2 if (output_level >= DDCA_OL_VV) { I2C_Sys_Info * info = get_i2c_sys_info(businfo->busno, -1); dbgrpt_i2c_sys_info(info, depth); free_i2c_sys_info(info); } #endif #endif } if (businfo->edid) { if (output_level == DDCA_OL_TERSE) { rpt_vstring(depth, "I2C bus: /dev/"I2C"-%d", businfo->busno); if (businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_FOUND) rpt_vstring(depth, "DRM connector: %s", businfo->drm_connector_name); rpt_vstring(depth, "drm_connector_id: %d", businfo->drm_connector_id); rpt_vstring(depth, "Monitor: %s:%s:%s", businfo->edid->mfg_id, businfo->edid->model_name, businfo->edid->serial_ascii); } else report_parsed_edid_base(businfo->edid, (output_level >= DDCA_OL_VERBOSE), // was DDCA_OL_VV (output_level >= DDCA_OL_VERBOSE), depth); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } static void init_i2c_bus_core_func_name_table() { RTTI_ADD_FUNC(find_sys_drm_connector_by_busno_or_edid); RTTI_ADD_FUNC(check_x37_for_businfo); RTTI_ADD_FUNC(get_connector_edid); RTTI_ADD_FUNC(get_i2c_device_numbers_using_udev); RTTI_ADD_FUNC(get_parsed_edid_for_businfo_using_sysfs); RTTI_ADD_FUNC(i2c_async_scan); RTTI_ADD_FUNC(i2c_check_bus); RTTI_ADD_FUNC(i2c_check_edid_exists_by_dh); RTTI_ADD_FUNC(i2c_check_open_bus_alive); RTTI_ADD_FUNC(i2c_close_bus); RTTI_ADD_FUNC(i2c_detect_attached_buses); RTTI_ADD_FUNC(i2c_detect_buses); RTTI_ADD_FUNC(i2c_detect_buses0); RTTI_ADD_FUNC(i2c_detect_single_bus); RTTI_ADD_FUNC(i2c_detect_x37); RTTI_ADD_FUNC(i2c_edid_exists); RTTI_ADD_FUNC(i2c_enable_cross_instance_locks); RTTI_ADD_FUNC(i2c_get_and_check_bus_info); RTTI_ADD_FUNC(i2c_non_async_scan); RTTI_ADD_FUNC(i2c_open_bus); RTTI_ADD_FUNC(i2c_report_active_bus); RTTI_ADD_FUNC(i2c_threaded_initial_checks_by_businfo); RTTI_ADD_FUNC(is_adapter_class_display_controller); RTTI_ADD_FUNC(is_laptop_drm_connector_name); RTTI_ADD_FUNC(is_laptop_for_businfo); } void subinit_i2c_bus_core() { // init_sysfs_drm_connector_names(); } void init_i2c_bus_core() { init_i2c_bus_core_func_name_table(); open_failures_reported = EMPTY_BIT_SET_256; attached_buses = EMPTY_BIT_SET_256; // connected_buses = EMPTY_BIT_SET_256; } ddcutil-2.2.0/src/i2c/i2c_bus_selector.c0000644000175000001440000001402614754153540013471 /** @file i2c_bus_selector.c * * Generalized Bus_Info search * * Overkill for current use. * Was coded at the time when selecting display by criteria occurred at the i2c/adn/usb * level rather than in ddc_displays.c. * Still used by USB layer as a fallback to find the EDID by model etc. * if the EDID can't be gotten from USB services. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include "i2c_bus_selector.h" typedef struct { int busno; const char * mfg_id; const char * model_name; const char * serial_ascii; const Byte * edidbytes; Byte options; } I2C_Bus_Selector; static void report_i2c_bus_selector(I2C_Bus_Selector * sel, int depth) { int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("I2C_Bus_Selector", sel, depth); rpt_int("busno", NULL, sel->busno, d1); rpt_str("mfg_id", NULL, sel->mfg_id, d1); rpt_str("model_name", NULL, sel->model_name, d1); rpt_str("serial_ascii", NULL, sel->serial_ascii, d1); rpt_structure_loc("edidbytes", sel->edidbytes, d1); if (sel->edidbytes) rpt_hex_dump(sel->edidbytes, 128, d2); } static void init_i2c_bus_selector(I2C_Bus_Selector* sel) { assert(sel); memset(sel, 0, sizeof(I2C_Bus_Selector)); sel->busno = -1; } // Note: No need for free_i2c_bus_selector() function since strings and memory // pointed to by selector are always in other data structures /* Tests if a bus_info table entry matches the criteria of a selector. * * Arguments: * bus_info pointer to Bus_Info instance to test * sel selection criteria * * Returns: true/false */ static bool bus_info_matches_selector(I2C_Bus_Info * bus_info, I2C_Bus_Selector * sel) { bool debug = false; if (debug) { DBGMSG("Starting"); i2c_dbgrpt_bus_info(bus_info, true, 1); } assert( bus_info && sel); assert( sel->busno >= 0 || sel->mfg_id || sel->model_name || sel->serial_ascii || sel->edidbytes); bool result = false; // does the bus represent a valid display? // 8/2018: This function is called only (indirectly) from get_fallback_hidev_edid() // in usb_edid.c to get the EDID for an EIZO display communicated with using USB. // DISPSEL_VALID_ONLY is not set in that case. if (sel->options & DISPSEL_VALID_ONLY) { #ifdef DETECT_SLAVE_ADDRS if (!(bus_info->flags & I2C_BUS_ADDR_0X37)) goto bye; #endif } bool some_test_passed = false; if (sel->busno >= 0) { DBGMSF(debug, "bus_info->busno = %d", bus_info->busno); if (sel->busno != bus_info->busno) { result = false; goto bye; } DBGMSF(debug, "busno test passed"); some_test_passed = true; } Parsed_Edid * edid = bus_info->edid; // will be NULL for I2C bus with no monitor if (sel->mfg_id && strlen(sel->mfg_id) > 0) { if ((!edid) || strlen(edid->mfg_id) == 0 || !streq(sel->mfg_id, edid->mfg_id) ) { result = false; goto bye; } some_test_passed = true; } if (sel->model_name && strlen(sel->model_name) > 0) { if ((!edid) || strlen(edid->model_name) == 0 || !streq(sel->model_name, edid->model_name) ) { result = false; goto bye; } some_test_passed = true; } if (sel->serial_ascii && strlen(sel->serial_ascii) > 0) { if ((!edid) || strlen(edid->serial_ascii) == 0 || !streq(sel->serial_ascii, edid->serial_ascii) ) { result = false; goto bye; } some_test_passed = true; } if (sel->edidbytes) { if ((!edid) || (memcmp(sel->edidbytes, edid->bytes, 128) != 0) ) { result = false; goto bye; } some_test_passed = true; } if (some_test_passed) result = true; bye: DBGMSF(debug, "Returning: %s", sbool(result)); return result; } /* Finds the first Bus_Info instance that matches a selector * * Arguments: * sel pointer to selection criteria * * Returns: pointer to Bus_Info instance if found, NULL if not */ static I2C_Bus_Info * find_bus_info_by_selector(I2C_Bus_Selector * sel) { assert(sel); bool debug = false; if (debug) { DBGMSG("Starting."); report_i2c_bus_selector(sel, 1); } I2C_Bus_Info * bus_info = NULL; assert(all_i2c_buses); int busct = all_i2c_buses->len; for (int ndx = 0; ndx < busct; ndx++) { I2C_Bus_Info * cur_info = g_ptr_array_index(all_i2c_buses, ndx); if (bus_info_matches_selector(cur_info, sel)) { bus_info = cur_info; break; } } DBGMSF(debug, "returning %p", bus_info ); if (debug && bus_info) { i2c_dbgrpt_bus_info(bus_info, true, 1); } return bus_info; } // Finally, functions that use the generalized bus selection mechanism /** Retrieves bus information by some combination of the monitor's * mfg id, model name and/or serial number. * * @param mfg_id 3 character manufacturer id * @param model monitor model (as listed in the EDID) * @param sn monitor ascii serial number (as listed in the EDID) * @param findopts selector options * * @return pointer to Bus_Info struct for the bus,\n * NULL if not found * * @remark used by get_fallback_hiddev_edid() in usb_edid.c */ I2C_Bus_Info * i2c_find_bus_info_by_mfg_model_sn( const char * mfg_id, const char * model, const char * sn, Byte findopts) { bool debug = false; DBGMSF(debug, "Starting. mfg_id=|%s|, model=|%s|, sn=|%s|", mfg_id, model, sn ); assert(mfg_id || model || sn); // loosen the requirements I2C_Bus_Selector sel; init_i2c_bus_selector(&sel); sel.mfg_id = mfg_id; sel.model_name = model; sel.serial_ascii = sn; sel.options = findopts; I2C_Bus_Info * result = find_bus_info_by_selector(&sel); DBGMSF(debug, "Returning: %p", result ); return result; } ddcutil-2.2.0/src/i2c/i2c_edid.c0000644000175000001440000004162614754153540011713 /** @file i2c_edid.c Read and parse EDID * Implements multiple methods to read an EDID, attempting to work around * various quirks. */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #ifdef TEST_EDID_SMBUG #include #endif #include #include #include #include #include /** \endcond */ #include "public/ddcutil_status_codes.h" #include "public/ddcutil_types.h" #include "util/coredefs.h" #include "util/file_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/edid.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/utilrpt.h" #include "base/parms.h" #include "base/core.h" #include "base/execution_stats.h" #include "base/rtti.h" #ifdef TARGET_BSD #include "bsd/i2c-dev.h" #else #include "i2c/wrap_i2c-dev.h" #endif #include "i2c/i2c_strategy_dispatcher.h" #include "i2c/i2c_edid.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_I2C; // // I2C Bus Inspection - EDID Retrieval // // Globals: bool EDID_Read_Uses_I2C_Layer = DEFAULT_EDID_READ_USES_I2C_LAYER; bool EDID_Read_Bytewise = DEFAULT_EDID_READ_BYTEWISE; int EDID_Read_Size = DEFAULT_EDID_READ_SIZE; bool EDID_Write_Before_Read = DEFAULT_EDID_WRITE_BEFORE_READ; #ifdef TEST_EDID_SMBUS bool EDID_Read_Uses_Smbus = false; #endif static Status_Errno_DDC i2c_get_edid_bytes_directly_using_ioctl( int fd, Buffer* rawedid, int edid_read_size, bool read_bytewise) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Getting EDID. File descriptor = %d, filename=%s, edid_read_size=%d, read_bytewise=%s", fd, filename_for_fd_t(fd), edid_read_size, sbool(read_bytewise)); assert(rawedid && rawedid->buffer_size >= EDID_BUFFER_SIZE); bool write_before_read = EDID_Write_Before_Read; // write_before_read = false; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "write_before_read = %s", sbool(write_before_read)); int rc = 0; if (write_before_read) { Byte byte_to_write = 0x00; struct i2c_msg messages[1]; struct i2c_rdwr_ioctl_data msgset; // The memset() calls are logically unnecessary, and code works fine without them. // However, without the memset() calls, valgrind complains about uninitialized bytes // on the ioctl() call. // See: https://stackoverflow.com/questions/17859320/valgrind-error-in-ioctl-call-while-sending-an-i2c-message // Also: https://github.com/the-tcpdump-group/libpcap/issues/1083 memset(messages,0, sizeof(messages)); memset(&msgset,0,sizeof(msgset)); messages[0].addr = 0x50; messages[0].flags = 0; messages[0].len = 1; messages[0].buf = &byte_to_write; msgset.msgs = messages; msgset.nmsgs = 1; RECORD_IO_EVENT( fd, IE_IOCTL_WRITE, ( rc = ioctl(fd, I2C_RDWR, &msgset) ) ); int errsv = errno; if (rc < 0) { if (debug) { REPORT_IOCTL_ERROR("I2C_RDWR", errno); } } // DBGMSG("ioctl(..I2C_RDWR..) returned %d", rc); if (rc >= 0) { if (rc != 1) // expected success value DBGMSG("Unexpected: ioctl() write returned %d", rc); rc = 0; } else if (rc < 0) { rc = -errsv; } } if (rc == 0) { read_bytewise = false; if (read_bytewise) { // unimplemented PROGRAM_LOGIC_ERROR("oops"); #ifdef FOR_REF int ndx = 0; for (; ndx < edid_read_size && rc == 0; ndx++) { RECORD_IO_EVENT( fd, IE_FILEIO_READ, ( rc = read(fd, &rawedid->bytes[ndx], 1) ) ); if (rc < 0) { rc = -errno; break; } assert(rc == 1); rc = 0; } rawedid->len = ndx; DBGMSF(debug, "Final single byte read returned %d, ndx=%d", rc, ndx); #endif } else { // messages needs to be allocated, cannot be on stack: struct i2c_msg * messages = calloc(1, sizeof(struct i2c_msg)); struct i2c_rdwr_ioctl_data msgset; memset(&msgset,0,sizeof(msgset)); // see comment in i2c_ioctl_writer() messages[0].addr = 0x50; messages[0].flags = I2C_M_RD; messages[0].len = edid_read_size; messages[0].buf = rawedid->bytes; msgset.msgs = messages; msgset.nmsgs = 1; RECORD_IO_EVENT( fd, IE_IOCTL_READ, ( rc = ioctl(fd, I2C_RDWR, &msgset)) ); int errsv = errno; if (rc < 0) { if (debug) { REPORT_IOCTL_ERROR("I2C_RDWR", errno); } } // DBGMSG("ioctl(..I2C_RDWR..) returned %d", rc); if (rc >= 0) { // always see rc == 1 if (rc != 1) { DBGMSG("Unexpected ioctl rc = %d, bytect =%d", rc, edid_read_size); } buffer_set_length(rawedid, edid_read_size); rc = 0; } else if (rc < 0) rc = -errsv; free(messages); } } // rc = -EINVAL; // ***TESTING*** if ( (debug || IS_TRACING()) && rc == 0) { DBGMSG("Returning buffer:"); rpt_hex_dump(rawedid->bytes, rawedid->len, 2); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } static Status_Errno_DDC i2c_get_edid_bytes_directly_using_fileio( int fd, Buffer* rawedid, int edid_read_size, bool read_bytewise) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Getting EDID. File descriptor = %d, filename=%s, edid_read_size=%d, read_bytewise=%s", fd, filename_for_fd_t(fd), edid_read_size, sbool(read_bytewise)); assert(rawedid && rawedid->buffer_size >= EDID_BUFFER_SIZE); bool write_before_read = EDID_Write_Before_Read; // write_before_read = false; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "write_before_read = %s", sbool(write_before_read)); int rc = i2c_set_addr(fd, 0x50); if (rc < 0) { goto bye; } if (write_before_read) { Byte byte_to_write = 0x00; RECORD_IO_EVENT( fd, IE_FILEIO_WRITE, ( rc = write(fd, &byte_to_write, 1) ) ); if (rc < 0) { rc = -errno; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "write() failed. rc = %s", psc_name_code(rc)); } else { rc = 0; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "write() succeeded"); } } if (rc == 0) { if (read_bytewise) { int ndx = 0; for (; ndx < edid_read_size && rc == 0; ndx++) { #ifdef TEST_EDID_SMBUS if (EDID_Read_Uses_Smbus) { // ndx 0 reads byte 1, why? __s32 smbdata = i2c_smbus_read_byte_data(fd, ndx); if (smbdata < 0) { rc = -errno; break; } assert((smbdata & 0xff) == smbdata); rawedid->bytes[ndx] = smbdata; } else { #endif RECORD_IO_EVENT( fd, IE_FILEIO_READ, ( rc = read(fd, &rawedid->bytes[ndx], 1) ) ); #ifdef TEST_EDID_SMBUS } #endif RECORD_IO_EVENT( fd, IE_FILEIO_READ, ( rc = read(fd, &rawedid->bytes[ndx], 1) ) ); if (rc < 0) { rc = -errno; break; } assert(rc == 1); rc = 0; } rawedid->len = ndx; DBGMSF(debug, "Final single byte read returned %d, ndx=%d", rc, ndx); } else { RECORD_IO_EVENT( fd, IE_FILEIO_READ, ( rc = read(fd, rawedid->bytes, edid_read_size) ) ); if (rc >= 0) { DBGMSF(debug, "read() returned %d", rc); rawedid->len = rc; // assert(rc == 128 || rc == 256); rc = 0; } else { rc = -errno; } DBGMSF(debug, "read() returned %s", psc_desc(rc) ); } } bye: if ( (debug || IS_TRACING()) && rc == 0) { DBGMSG("Returning buffer:"); rpt_hex_dump(rawedid->bytes, rawedid->len, 2); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } static Status_Errno_DDC i2c_get_edid_bytes_using_i2c_layer( int fd, Buffer* rawedid, int edid_read_size, bool read_bytewise) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, filename=%s, rawedid=%p, edid_read_size=%d, read_bytewise=%s", fd, filename_for_fd_t(fd), (void*)rawedid, edid_read_size, sbool(read_bytewise)); assert(rawedid && rawedid->buffer_size >= EDID_BUFFER_SIZE); int rc = 0; bool write_before_read = EDID_Write_Before_Read; rc = 0; if (write_before_read) { Byte byte_to_write = 0x00; rc = invoke_i2c_writer(fd, 0x50, 1, &byte_to_write); DBGMSF(debug, "invoke_i2c_writer returned %s", psc_desc(rc)); } if (rc == 0) { // write succeeded or no write if (read_bytewise) { int ndx = 0; for (; ndx < edid_read_size && rc == 0; ndx++) { // DBGMSG("Before invoke_i2c_reader() call"); rc = invoke_i2c_reader(fd, 0x50, false, 1, &rawedid->bytes[ndx] ); } DBGMSF(debug, "Final single byte read returned %d, ndx=%d", rc, ndx); } // read_bytewise == true else { rc = invoke_i2c_reader(fd, 0x50, read_bytewise, edid_read_size, rawedid->bytes); DBGMSF(debug, "invoke_i2c_reader returned %s", psc_desc(rc)); } if (rc == 0) { rawedid->len = edid_read_size; } } // write succeeded if ( (debug || IS_TRACING()) && rc == 0) { DBGMSG("Returning buffer:"); rpt_hex_dump(rawedid->bytes, rawedid->len, 2); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } /** Gets EDID bytes of a monitor on an open I2C device. * * @param fd file descriptor for open /dev/i2c-n * @param rawedid buffer in which to return bytes of the EDID * * @retval 0 success * @retval <0 error */ Status_Errno_DDC i2c_get_raw_edid_by_fd(int fd, Buffer * rawedid) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Getting EDID. File descriptor = %d, filename=%s", fd, filename_for_fd_t(fd)); assert(rawedid && rawedid->buffer_size >= EDID_BUFFER_SIZE); int max_tries = (EDID_Read_Size == 0) ? 4 : 2; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "EDID_Read_Size=%d, max_tries=%d", EDID_Read_Size, max_tries); // n. prior to gcc 11, declaration cannot immediately follow label I2C_IO_Strategy_Id cur_strategy_id = I2C_IO_STRATEGY_NOT_SET; retry: cur_strategy_id = i2c_get_io_strategy_id(); assert(cur_strategy_id != I2C_IO_STRATEGY_NOT_SET); DBGMSF(debug, "Using strategy %s", i2c_io_strategy_id_name(cur_strategy_id) ); int rc = -1; bool read_bytewise = EDID_Read_Bytewise; // DBGMSF(debug, "EDID read performed using %s,read_bytewise=%s", // (EDID_Read_Uses_I2C_Layer) ? "I2C layer" : "local io", sbool(read_bytewise)); int tryctr = 0; #ifdef TEST_EDID_SMBUS if (EDID_Read_Uses_Smbus) { read_bytewise = true; cur_strategy_id = I2C_IO_STRATEGY_FILEIO; EDID_Read_Uses_I2C_Layer = false; } DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "EDID_Read_Uses_Smbus = %s", sbool(EDID_Read_Uses_Smbus)); #endif while (tryctr < max_tries && rc != 0) { int edid_read_size = EDID_Read_Size; if (EDID_Read_Size == 0) edid_read_size = (tryctr < 2) ? 128 : 256; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Trying EDID read. tryctr=%d, max_tries=%d," " edid_read_size=%d, read_bytewise=%s, using %s", tryctr, max_tries, edid_read_size, sbool(read_bytewise), (EDID_Read_Uses_I2C_Layer) ? "I2C layer" : "local io"); char * called_func_name = NULL; if (EDID_Read_Uses_I2C_Layer) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_get_edid_bytes_using_i2c_layer, cur_strategy_id = %s...", i2c_io_strategy_id_name(cur_strategy_id)); rc = i2c_get_edid_bytes_using_i2c_layer(fd, rawedid, edid_read_size, read_bytewise); called_func_name = "i2c_get_edid_bytes_using_i2c_layer"; } else { // use local functions if (cur_strategy_id == I2C_IO_STRATEGY_IOCTL) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_get_edid_bytes_directly_using_ioctl()..."); called_func_name = "i2c_get_edid_bytes_directly_using_ioctl"; rc = i2c_get_edid_bytes_directly_using_ioctl( fd, rawedid, edid_read_size, read_bytewise); if (rc == -EINVAL) { int busno = extract_number_after_hyphen(filename_for_fd_t(fd)); assert(busno >= 0); if ( is_nvidia_einval_bug(I2C_IO_STRATEGY_IOCTL, busno, rc)) goto retry; } } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Calling i2c_get_edid_bytes_directly_using_fileio()..."); called_func_name = "i2c_get_edid_bytes_directly_using_fileio"; rc = i2c_get_edid_bytes_directly_using_fileio(fd, rawedid, edid_read_size, read_bytewise); } } // use local functions tryctr++; if (rc == -ENXIO || rc == -EOPNOTSUPP || rc == -ETIMEDOUT || rc == -EBUSY) { // removed -EIO 3/4/2021 // DBGMSG("breaking"); break; } assert(rc <= 0); if (rc == 0) { // rawedid->len = 128; if (IS_DBGTRC(debug, DDCA_TRC_NONE) ) { // only show if explicitly tracing this function DBGMSG("%s returned:", called_func_name); dbgrpt_buffer(rawedid, 1); DBGMSG("edid checksum = %d", edid_checksum(rawedid->bytes) ); } if (!is_valid_raw_edid(rawedid->bytes, rawedid->len)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Invalid EDID"); rc = DDCRC_INVALID_EDID; if (is_valid_raw_cea861_extension_block(rawedid->bytes, rawedid->len)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "EDID appears to start with a CEA 861 extension block"); } } if (rawedid->len == 256) { if (is_valid_raw_cea861_extension_block(rawedid->bytes+128, rawedid->len-128)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Second physical EDID block appears to be a CEA 861 extension block"); } else if (is_valid_raw_edid(rawedid->bytes+128, rawedid->len-128)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Second physical EDID block read is actually the initial EDID block"); memcpy(rawedid->bytes, rawedid->bytes+128, 128); buffer_set_length(rawedid, 128); rc = 0; } } } // get bytes succeeded } if (rc < 0) rawedid->len = 0; DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "tries=%d", tryctr); return rc; } /** Returns a parsed EDID record for the monitor on an I2C bus. * * @param fd file descriptor for open /dev/i2c-n * @param edid_ptr_loc where to return pointer to newly allocated #Parsed_Edid, * or NULL if error * @return status code */ Status_Errno_DDC i2c_get_parsed_edid_by_fd(int fd, Parsed_Edid ** edid_ptr_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, filename=%s", fd, filename_for_fd_t(fd)); Parsed_Edid * edid = NULL; Buffer * rawedidbuf = buffer_new(EDID_BUFFER_SIZE, NULL); Status_Errno_DDC rc = i2c_get_raw_edid_by_fd(fd, rawedidbuf); if (rc == 0) { edid = create_parsed_edid2(rawedidbuf->bytes, "I2C"); if (debug) { if (edid) report_parsed_edid(edid, false /* verbose */, 0); else DBGMSG("create_parsed_edid() returned NULL"); } if (!edid) rc = DDCRC_INVALID_EDID; } buffer_free(rawedidbuf, NULL); *edid_ptr_loc = edid; if (edid) DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "*edid_ptr_loc = %p -> ...%s", edid, hexstring3_t(edid->bytes+124, 4, "", 1, false)); else DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } void init_i2c_edid() { RTTI_ADD_FUNC(i2c_get_edid_bytes_using_i2c_layer); RTTI_ADD_FUNC(i2c_get_edid_bytes_directly_using_fileio); RTTI_ADD_FUNC(i2c_get_edid_bytes_directly_using_ioctl); RTTI_ADD_FUNC(i2c_get_raw_edid_by_fd); RTTI_ADD_FUNC(i2c_get_parsed_edid_by_fd); } ddcutil-2.2.0/src/i2c/i2c_execute.c0000644000175000001440000004577114754153540012455 /** \file i2c_execute.c * * Basic functions for writing to and reading from the I2C bus using * alternative mechanisms. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include "ddcutil_types.h" #include #include #include #include #include #include #include #include #include /** \endcond */ #include "util/coredefs.h" #include "util/debug_util.h" #include "util/file_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/i2c_util.h" #include "util/sysfs_i2c_util.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/execution_stats.h" #include "base/linux_errno.h" #include "base/parms.h" #include "base/rtti.h" #include "base/tuned_sleep.h" #ifdef TARGET_BSD #include "bsd/i2c.h" #include "bsd/i2c-dev.h" #else #include "i2c/wrap_i2c-dev.h" #endif #include "i2c_execute.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_I2C; /** Global variable. Controls whether function #i2c_set_addr() attempts retry * after EBUSY error by changing ioctl op I2C_SLAVE to I2C_SLAVE_FORCE. */ bool i2c_forceable_slave_addr_flag = false; Status_Errno i2c_set_addr0(int fd, uint16_t op, int addr) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, addr=0x%02x, filename=%s, op=%s", fd, addr, filename_for_fd_t(fd), (op == I2C_SLAVE) ? "I2C_SLAVE" : "I2C_SLAVE_FORCE"); // FAILSIM; bool force_pseudo_failure = false; Status_Errno result = 0; int ioctl_rc = 0; int errsv = 0; if (force_pseudo_failure && op == I2C_SLAVE) { DBGTRC_NOPREFIX(true, TRACE_GROUP, "Forcing pseudo failure"); ioctl_rc = -1; errno=EBUSY; } else { RECORD_IO_EVENT(-1, IE_OTHER, ( ioctl_rc = ioctl(fd, op, addr) ) ); } if (ioctl_rc < 0) { errsv = errno; if (errsv == EBUSY) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "ioctl(%s, I2C_SLAVE, 0x%02x) returned EBUSY", filename_for_fd_t(fd), addr); } else { REPORT_IOCTL_ERROR( (op == I2C_SLAVE) ? "I2C_SLAVE" : "I2C_SLAVE_FORCE", errsv); } result = -errsv; } assert(result <= 0); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } /** Sets the slave address to be used in subsequent i2c-dev write() and read() * operations. * * @param fd file descriptor * @param addr slave address * @return status code */ Status_Errno i2c_set_addr(int fd, int addr) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, addr=0x%02x, filename=%s, i2c_forceable_slave_addr_flag=%s", fd, addr, filename_for_fd_t(fd), sbool(i2c_forceable_slave_addr_flag) ); Status_Errno result = 0; uint16_t op = I2C_SLAVE; bool done = false; while (!done) { done = true; result = i2c_set_addr0(fd, op, addr); if (result < 0) { if (result == -EBUSY) { if (op == I2C_SLAVE && i2c_forceable_slave_addr_flag) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Retrying using IOCTL op I2C_SLAVE_FORCE for %s, slave address 0x%02x", filename_for_fd_t(fd), addr ); // normally errors counted at higher level, but in this case it would be // lost because of retry COUNT_STATUS_CODE(result); op = I2C_SLAVE_FORCE; done = false; } } } } if (result == -EBUSY) { char msgbuf[80]; g_snprintf(msgbuf, 60, "set_addr(%s,%s,0x%02x) failed, error = EBUSY", filename_for_fd_t(fd), (op == I2C_SLAVE) ? "I2C_SLAVE" : "I2C_SLAVE_FORCE", addr); DBGTRC_NOPREFIX(debug || get_output_level() >= DDCA_OL_VERBOSE, TRACE_GROUP, "%s", msgbuf); SYSLOG2(DDCA_SYSLOG_ERROR, "%s", msgbuf); } else if (result == 0 && op == I2C_SLAVE_FORCE) { char msgbuf[80]; g_snprintf(msgbuf, 80, "set_addr(%s,I2C_SLAVE_FORCE,0x%02x) succeeded on retry after EBUSY error", filename_for_fd_t(fd), addr); DBGTRC_NOPREFIX(debug || get_output_level() >= DDCA_OL_VERBOSE, TRACE_GROUP, "%s", msgbuf); SYSLOG2(DDCA_SYSLOG_ERROR, "%s", msgbuf); } assert(result <= 0); // if (addr == 0x37) result = -EBUSY; // for testing DBGTRC_RET_DDCRC(debug, TRACE_GROUP, result, ""); return result; } static bool read_with_timeout = false; static bool write_with_timeout = false; void set_i2c_fileio_use_timeout(bool yesno) { // DBGMSG("Setting %s", sbool(yesno)); read_with_timeout = yesno; write_with_timeout = yesno; } bool get_i2c_fileio_use_timeout() { return read_with_timeout; } /** Writes to i2c bus using write() * * @param fd Linux file descriptor * @param slave_address I2C slave address being written to (unused) * @param bytect number of bytes to write * @param pbytes pointer to bytes to write * * @retval 0 success * @retval DDCRC_DDC_DATA incorrect number of bytes read * @retval -errno negative Linux error number */ Status_Errno_DDC i2c_fileio_writer( int fd, Byte slave_address, int bytect, Byte * pbytes) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, filename=%s, slave_address=0x%02x, bytect=%d, pbytes=%p -> %s", fd, filename_for_fd_t(fd), slave_address, bytect, pbytes, hexstring_t(pbytes, bytect)); int rc = 0; rc = i2c_set_addr(fd, slave_address); if (rc < 0) goto bye; // #ifdef USE_POLL if (write_with_timeout) { struct pollfd pfds[1]; pfds[0].fd = fd; pfds[0].events = POLLOUT; int pollrc; int timeout_msec = 100; RECORD_IO_EVENT( fd, IE_OTHER, ( pollrc = poll(pfds, 1, timeout_msec) ) ); int errsv = errno; if (pollrc < 0) { // i.e. -1 DBGMSG("poll() returned %d, errno=%d", pollrc, errsv); rc = -errsv; goto bye; } else if (pollrc == 0) { DBGMSG("poll() timed out after %d milliseconds", timeout_msec); rc = -ETIMEDOUT; goto bye; } else { if ( !( pfds[0].revents & POLLOUT) ) { DBGMSG("pfds[0].revents: 0x%04x", pfds[0].revents); // just continue, write() will fail and we'll return that status code } } } // #endif RECORD_IO_EVENT( fd, IE_FILEIO_WRITE, ( rc = write(fd, pbytes, bytect) ) ); // per write() man page: // if >= 0, number of bytes actually written, must be <= bytect // if -1, error occurred, errno is set if (rc >= 0) { if (rc == bytect) rc = 0; else rc = DDCRC_DDC_DATA; // was DDCRC_BAD_BYTECT } else { // ioctl_rc < 0 int errsv = errno; DBGMSF(debug, "write() returned %d, errno=%s", rc, linux_errno_desc(errsv)); rc = -errsv; } bye: DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } /** Reads from I2C bus using read() * * @param fd Linux file descriptor * @param slave_address I2C slave address being read from * @param read_bytewise if true, use single byte reads * @param bytect number of bytes to read * @param readbuf read bytes into this buffer * * @retval 0 success * @retval DDCRC_DDC_DATA incorrect number of bytes read * @retval -errno negative Linux errno value from read() * * @remark * read_bytewise == true fails on some monitors, should generally be false */ Status_Errno_DDC i2c_fileio_reader( int fd, Byte slave_address, bool single_byte_reads, int bytect, Byte * readbuf) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, fn=%s, bytect=%d, slave_address=0x%02x, single_byte_reads=%s", fd, filename_for_fd_t(fd), bytect, slave_address, sbool(single_byte_reads)); int rc = i2c_set_addr(fd, slave_address); if (rc < 0) goto bye; if (single_byte_reads) { // for Acer and P2411h, reads bytes 1,3,5,7 .. for (int ndx=0; ndx < bytect && rc == 0; ndx++) { // DBGMSF(debug, "Calling read() for 1 byte, ndx=%d", ndx); RECORD_IO_EVENT( fd, IE_FILEIO_READ, ( rc = read(fd, readbuf+ndx, 1) ) ); // DBGMSF(debug, "Byte read: readbuf[%d] = 0x%02x", ndx, readbuf[ndx]); // rc = read(fd, readbuf+ndx, 1); if (rc >= 0) { if (rc == 1) { rc = 0; // does not solve problem of every other byte read on some monitors // TUNED_SLEEP_WITH_TRACE(DDCA_IO_I2C, SE_POST_READ, "After 1 byte read"); } else rc = DDCRC_DDC_DATA; } } } else { // #ifdef USE_POLL if (read_with_timeout) { struct pollfd pfds[1]; pfds[0].fd = fd; pfds[0].events = POLLIN; int pollrc; int timeout_msec = 100; RECORD_IO_EVENT( fd, IE_OTHER, ( pollrc = poll(pfds, 1, timeout_msec) ) ); int errsv = errno; if (pollrc < 0) { // i.e. -1 DBGMSG("poll() returned %d, errno=%d", pollrc, errsv); rc = -errsv; goto bye; } else if (pollrc == 0) { DBGMSG("poll() timed out after %d milliseconds", timeout_msec); rc = -ETIMEDOUT; goto bye; } else { if ( !(pfds[0].revents & POLLIN) ) { DBGMSG("pfds[0].revents: 0x%04x", pfds[0].revents); // just continue, read() will fail and we'll return that status code } } } // #endif RECORD_IO_EVENT( fd, IE_FILEIO_READ, ( rc = read(fd, readbuf, bytect) ) ); // per read() man page: // if rc >= 0, number of bytes actually read // if rc ==-1, error occurred, errno is set if (rc >= 0) { if (rc == bytect) rc = 0; else rc = DDCRC_DDC_DATA; // was DDCRC_BAD_BYTECT } } if (rc < 0) { int errsv = errno; DBGMSF(debug, "read() returned %d, errno=%s", rc, linux_errno_desc(errsv)); rc = -errsv; } bye: DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "readbuf: %s", hexstring_t(readbuf, bytect)); return rc; } STATIC void dbgrpt_i2c_msg(int depth, struct i2c_msg message) { rpt_vstring(depth, "addr: 0x%04x", message.addr); // __u16 addr; rpt_vstring(depth, "flags: 0x%04x", message.flags); // #define I2C_M_RD 0x0001 /* guaranteed to be 0x0001! */ // #define I2C_M_TEN 0x0010 /* use only if I2C_FUNC_10BIT_ADDR */ // #define I2C_M_DMA_SAFE 0x0200 /* use only in kernel space */ // #define I2C_M_RECV_LEN 0x0400 /* use only if I2C_FUNC_SMBUS_READ_BLOCK_DATA */ // #define I2C_M_NO_RD_ACK 0x0800 /* use only if I2C_FUNC_PROTOCOL_MANGLING */ // #define I2C_M_IGNORE_NAK 0x1000 /* use only if I2C_FUNC_PROTOCOL_MANGLING */ // #define I2C_M_REV_DIR_ADDR 0x2000 /* use only if I2C_FUNC_PROTOCOL_MANGLING */ // #define I2C_M_NOSTART 0x4000 /* use only if I2C_FUNC_NOSTART */ // #define I2C_M_STOP 0x8000 /* use only if I2C_FUNC_PROTOCOL_MANGLING */ rpt_vstring(depth, "len: 0x%04x (%d)", message.len, message.len); // __u16 // rpt_vstring(depth, "buf: %p -> %s", message.buf, hexstring_t(message.buf, message.len)); // __u8 *buf; rpt_vstring(depth, "buf: %p", message.buf); // __u8 *buf; } STATIC void dbgrpt_i2c_rdwr_ioctl_data(int depth, struct i2c_rdwr_ioctl_data * data) { bool debug = false; DBGMSF(debug, "data=%p", data); rpt_structure_loc("i2c_rdwr_ioctl_data", data, depth); int d1 = depth+1; int d2 = depth+2; rpt_vstring(d1, "nmsgs: %d", data->nmsgs); for (int ndx = 0; ndx < data->nmsgs; ndx++) { struct i2c_msg cur = data->msgs[ndx]; rpt_vstring(d1, "i2c_msg[%d]", ndx); // rpt_structure_loc("i2c_msg", cur, depth); dbgrpt_i2c_msg(d2, cur); } } /** Writes to I2C bus using ioctl(I2C_RDWR) * * @param fd Linux file descriptor * @param slave_address slave address to write to * @param bytect number of bytes to write * @param pbytes pointer to bytes to write * * @retval 0 success * @retval <0 negative Linux errno value */ Status_Errno_DDC i2c_ioctl_writer( int fd, Byte slave_address, int bytect, Byte * pbytes) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fh=%d, filename=%s, slave_address=0x%02x, bytect=%d, pbytes=%p -> %s", fd, filename_for_fd_t(fd), slave_address, bytect, pbytes, hexstring_t(pbytes, bytect)); int rc = 0; struct i2c_msg messages[1]; struct i2c_rdwr_ioctl_data msgset; // The memset() calls are logically unnecessary, and code works fine without them. // However, without the memset() calls, valgrind complains about uninitialized bytes // on the ioctl() call. // See: https://stackoverflow.com/questions/17859320/valgrind-error-in-ioctl-call-while-sending-an-i2c-message // Also: https://github.com/the-tcpdump-group/libpcap/issues/1083 memset(messages,0, sizeof(messages)); memset(&msgset,0,sizeof(msgset)); messages[0].addr = slave_address; messages[0].flags = 0; messages[0].len = bytect; messages[0].buf = pbytes; msgset.msgs = messages; msgset.nmsgs = 1; if (IS_DBGTRC(debug, DDCA_TRC_NONE)) dbgrpt_i2c_rdwr_ioctl_data(1, &msgset); // per ioctl() man page: // if success: // normally: 0 // occasionally >0 is output parm // if error: // -1, errno is set // 11/15: as seen: always returns 1 for success RECORD_IO_EVENT( fd, IE_IOCTL_WRITE, ( rc = ioctl(fd, I2C_RDWR, &msgset) ) ); int errsv = errno; if (rc < 0) { if (rc != -1) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Unexpected: ioctl() write returned %d", rc); SYSLOG2(DDCA_SYSLOG_ERROR, "Unexpected: (%s) ioctl() write returned %d", __func__, rc); // show_backtrace(1); } rc = -errsv; } else { // (rc >= 0) { if (rc != 1) { // expected success value DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Unexpected: ioctl() write returned %d", rc); SYSLOG2(DDCA_SYSLOG_ERROR, "(%s) Unexpected: ioctl() write returned %d", __func__, rc); // show_backtrace(1); } rc = 0; } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "fh=%d, filename=%s", fd, filename_for_fd_t(fd)); return rc; } /** Reads from I2C bus using ioctl(I2C_RDWR) * * @param fd Linux file descriptor * @param slave_addr slave address to read from * @param bytect number of bytes to read * @param readbuf read bytes into this buffer * * @retval 0 success * @retval <0 negative Linux errno value */ STATIC Status_Errno_DDC i2c_ioctl_reader1( int fd, Byte slave_addr, int bytect, Byte * readbuf) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, fn=%s, slave_addr=0x%02x, bytect=%d, readbuf=%p", fd, filename_for_fd_t(fd), slave_addr, bytect, readbuf); // If read fails, readbuf will not be set. // Initialize it here, otherwise valgrind complains about uninitialized variable // in hexstring_t() memset(readbuf, 0x00, bytect); int rc = 0; // messages needs to be allocated, cannot be on stack: struct i2c_msg * messages = calloc(1, sizeof(struct i2c_msg)); struct i2c_rdwr_ioctl_data msgset; memset(&msgset,0,sizeof(msgset)); // see comment in is2_ioctl_writer() messages[0].addr = slave_addr; messages[0].flags = I2C_M_RD; messages[0].len = bytect; messages[0].buf = readbuf; msgset.msgs = messages; msgset.nmsgs = 1; if (IS_DBGTRC(debug, DDCA_TRC_NONE)) dbgrpt_i2c_rdwr_ioctl_data(1, &msgset); RECORD_IO_EVENT( fd, IE_IOCTL_READ, ( rc = ioctl(fd, I2C_RDWR, &msgset)) ); int errsv = errno; if (rc < 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Error in ioctl() read, rc=%d, errno=%s, device=%s", rc, psc_desc(-errsv), filename_for_fd_t(fd)); SYSLOG2(DDCA_SYSLOG_DEBUG, "(%s) Error in ioctl() read, rc=%d, errno=%s, device=%s", __func__, rc, psc_desc(-errsv), filename_for_fd_t(fd)); if (IS_DBGTRC(debug, TRACE_GROUP)) { show_backtrace(0); dbgrpt_traced_callstack_call_table(0); } rc = -errsv; } else { if (rc != 1) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Unexpected ioctl() read rc=%d, bytect =%d, device=%s", rc, bytect, filename_for_fd_t(fd)); SYSLOG2(DDCA_SYSLOG_ERROR, "(%s) Unexpected ioctl() read rc = %d, bytect =%d, device=%s", __func__, rc, bytect, filename_for_fd_t(fd)); // show_backtrace(1); } rc = 0; } free(messages); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "fh=%d, filename=%s, readbuf: %s", fd, filename_for_fd_t(fd), hexstring_t(readbuf, bytect)); return rc; } /** Reads from I2C bus using ioctl(I2C_RDWR) * * @param fd Linux file descriptor * @param slave_addr slave address to read from * @param read_bytewise if true, read single byte at a time * @param bytect number of bytes to read * @param readbuf read bytes into this buffer * * @retval 0 success * @retval <0 negative Linux errno value */ Status_Errno_DDC i2c_ioctl_reader( int fd, Byte slave_addr, bool read_bytewise, int bytect, Byte * readbuf) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, fn=%s, slave_addr=0x%02x, read_bytewise=%s, bytect=%d, readbuf=%p", fd, filename_for_fd_t(fd), slave_addr, SBOOL(read_bytewise), bytect, readbuf); int rc = 0; if (read_bytewise) { int ndx = 0; for (; ndx < bytect && rc == 0; ndx++) { rc = i2c_ioctl_reader1(fd, slave_addr, 1, readbuf+ndx); } } else { rc = i2c_ioctl_reader1(fd, slave_addr, bytect, readbuf); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "fh=%d, filename=%s, readbuf: %s", fd, filename_for_fd_t(fd), hexstring_t(readbuf, bytect)); return rc; } void init_i2c_execute() { RTTI_ADD_FUNC(i2c_set_addr); RTTI_ADD_FUNC(i2c_set_addr0); RTTI_ADD_FUNC(i2c_ioctl_reader); RTTI_ADD_FUNC(i2c_ioctl_reader1); RTTI_ADD_FUNC(i2c_ioctl_writer); RTTI_ADD_FUNC(i2c_fileio_reader); RTTI_ADD_FUNC(i2c_fileio_writer); } ddcutil-2.2.0/src/i2c/i2c_services.c0000644000175000001440000000101714754153540012617 /** @file i2c_services.c */ // Copyright (C) 2022-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "base/i2c_bus_base.h" #include "i2c_bus_core.h" #include "i2c_edid.h" #include "i2c_execute.h" #include "i2c_strategy_dispatcher.h" /** Master initializer for directory i2c */ void init_i2c_services() { init_i2c_bus_core(); init_i2c_edid(); init_i2c_execute(); init_i2c_strategy_dispatcher(); } void terminate_i2c_services() { terminate_i2c_bus_base(); } ddcutil-2.2.0/src/i2c/i2c_strategy_dispatcher.c0000644000175000001440000001725214754576332015064 /** \file i2c_strategy_dispatcher.c * * Allows for alternative mechanisms to read and write to the IC2 bus. */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include "config.h" #include #include #include #include /** \endcond */ #include "util/file_util.h" #include "util/i2c_util.h" #include "util/string_util.h" #include "util/sysfs_i2c_util.h" #include "base/core.h" #include "base/i2c_bus_base.h" #include "base/parms.h" #include "base/rtti.h" #include "base/status_code_mgt.h" #include "sysfs/sysfs_base.h" #include "i2c_strategy_dispatcher.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_I2C; #define I2C_STRATEGY_BUSCT_MAX 32 I2C_IO_Strategy i2c_file_io_strategy = { I2C_IO_STRATEGY_FILEIO, "I2C_IO_STRATEGY_FILEIO", i2c_fileio_writer, i2c_fileio_reader, "fileio_writer", "fileio_reader" }; I2C_IO_Strategy i2c_ioctl_io_strategy = { I2C_IO_STRATEGY_IOCTL, "I2C_IO_STRATEGY_IOCTL", i2c_ioctl_writer, i2c_ioctl_reader, "ioctl_writer", "ioctl_reader" }; static char * strategy_names[] = { "I2C_IO_STRATEGY_NOT_SET", "I2C_IO_STRATEGY_FILEIO", "I2C_IO_STRATEGY_IOCTL"}; char * i2c_io_strategy_id_name(I2C_IO_Strategy_Id id) { assert(id < ARRAY_SIZE(strategy_names)); char * result = strategy_names[id]; return result; } static I2C_IO_Strategy * active_i2c_io_strategy = NULL; static bool nvidia_einval_bug_encountered = false; /** Sets the active I2C IO strategy * * @param strategy_id I2C IO strategy id */ void i2c_set_io_strategy_by_id(I2C_IO_Strategy_Id strategy_id) { bool debug = false; assert(strategy_id != I2C_IO_STRATEGY_NOT_SET); DBGMSF(debug, "Starting. id=%d", strategy_id); switch (strategy_id) { case (I2C_IO_STRATEGY_NOT_SET): PROGRAM_LOGIC_ERROR("Impossible case"); active_i2c_io_strategy = NULL; break; case (I2C_IO_STRATEGY_FILEIO): active_i2c_io_strategy = &i2c_file_io_strategy; break; case (I2C_IO_STRATEGY_IOCTL): active_i2c_io_strategy= &i2c_ioctl_io_strategy; break; } DBGMSF(debug, "Done. Set strategy: %s", active_i2c_io_strategy->strategy_name); } /** Gets the strategy to be used on the next read or write * * @return pointer to strategy record */ static I2C_IO_Strategy * i2c_get_io_strategy() { bool debug = false; DBGMSF(debug, "Executing. Returning strategy %s", active_i2c_io_strategy->strategy_name); return active_i2c_io_strategy; } I2C_IO_Strategy_Id i2c_get_io_strategy_id() { bool debug = false; I2C_IO_Strategy_Id result = (active_i2c_io_strategy) ? active_i2c_io_strategy->strategy_id : I2C_IO_STRATEGY_NOT_SET; DBGMSF(debug, "Returning %s", i2c_io_strategy_id_name(result)); return result; } /** Checks a status code to see if it indicates the nvida/i2c-dev driver bug. * * It is if the following 3 tests are met: * - the status code is -EINVAL * - the driver name is "nvidia" * - the current io strategy is I2C_IO_STRATEGY_IOCTL * * @param strategy_id current io strategy * @param busno /dev/i2c-N bus number * @param rc status code to check * @return true if all tests are met, false otherwise * * If the function returns true: * - global variable nvidia_einval_bug_encountered is set true * - the current IO strategy is set to I2C_IO_STRATEGY_FILEIO */ bool is_nvidia_einval_bug( I2C_IO_Strategy_Id strategy_id, int busno, int rc) { bool debug = false; bool result = false; if ( rc == -EINVAL && strategy_id == I2C_IO_STRATEGY_IOCTL) { char * driver_name = get_i2c_sysfs_driver_by_busno(busno); if (streq(driver_name, "nvidia")) { nvidia_einval_bug_encountered = true; i2c_set_io_strategy_by_id(I2C_IO_STRATEGY_FILEIO); // the new normal char * msg = "nvida/i2c-dev bug encountered. Forcing future io to I2C_IO_STRATEGY_FILEIO. Retrying"; DBGTRC(debug, TRACE_GROUP, msg); SYSLOG2(DDCA_SYSLOG_WARNING, "%s", msg); result = true; } free(driver_name); } return result; } /** Writes to the I2C bus, using the function specified in the * currently active strategy. * * @param fd Linux file descriptor for open /dev/i2c bus * @param slave_address slave address to write to * @param bytect number of bytes to write * @param bytes_to_write pointer to bytes to be written * @return status code */ Status_Errno_DDC invoke_i2c_writer( int fd, Byte slave_address, int bytect, Byte * bytes_to_write) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, filename=%s, slave_address=0x%02x, bytect=%d, bytes_to_write=%p -> %s", fd, filename_for_fd_t(fd), slave_address, bytect, bytes_to_write, hexstring_t(bytes_to_write, bytect)); // n. prior to gcc 11, declaration cannot immediately follow label I2C_IO_Strategy * strategy = I2C_IO_STRATEGY_NOT_SET; retry: strategy = i2c_get_io_strategy(); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "strategy = %s", strategy->strategy_name); Status_Errno_DDC rc = strategy->i2c_writer(fd, slave_address, bytect, bytes_to_write); if (rc == -EINVAL) { int busno = extract_number_after_hyphen(filename_for_fd_t(fd)); assert(busno >= 0); if (is_nvidia_einval_bug(strategy->strategy_id, busno, rc)) { goto retry; } } assert (rc <= 0); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } /** Reads from the I2C bus, using the function specified in the * currently active strategy. * * @param fd Linux file descriptor for open /dev/i2c bus * @param slave_address I2C slave address to read from * @param read_bytewise if true, read one byte at a time * @param bytect number of bytes to read * @param readbuf location where bytes will be read to * @return status code */ Status_Errno_DDC invoke_i2c_reader( int fd, Byte slave_address, bool read_bytewise, int bytect, Byte * readbuf) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "fd=%d, filename=%s, slave_address=0x%02x, bytect=%d, read_bytewise=%s, readbuf=%p", fd, filename_for_fd_t(fd), slave_address, bytect, sbool(read_bytewise), readbuf); // n. prior to gcc 11, declaration cannot immediately follow label I2C_IO_Strategy * strategy = I2C_IO_STRATEGY_NOT_SET; retry: strategy = i2c_get_io_strategy(); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "strategy = %s", strategy->strategy_name); Status_Errno_DDC rc = strategy->i2c_reader(fd, slave_address, read_bytewise, bytect, readbuf); assert (rc <= 0); if (rc == -EINVAL) { int busno = extract_number_after_hyphen(filename_for_fd_t(fd)); assert(busno >= 0); if (is_nvidia_einval_bug(strategy->strategy_id, busno, rc)) { goto retry; } } if (rc == 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Bytes read: %s", hexstring_t(readbuf, bytect) ); } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, ""); return rc; } void init_i2c_strategy_dispatcher() { i2c_set_io_strategy_by_id(DEFAULT_I2C_IO_STRATEGY); RTTI_ADD_FUNC(invoke_i2c_reader); RTTI_ADD_FUNC(invoke_i2c_writer); } ddcutil-2.2.0/src/i2c/i2c_bus_selector.h0000644000175000001440000000114314754576332013502 /** @file i2c_bus_selector.h * * Generalized bus_info finder, now used only within usb_edid.c to find * a fallback EDID */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_BUS_SELECTOR_H_ #define I2C_BUS_SELECTOR_H_ #include "util/coredefs.h" #include "i2c_bus_core.h" // Complex Bus_Info retrieval I2C_Bus_Info * i2c_find_bus_info_by_mfg_model_sn( const char * mfg_id, const char * model, const char * sn, Byte findopts); #endif /* I2C_BUS_SELECTOR_H_ */ ddcutil-2.2.0/src/i2c/wrap_i2c-dev.h0000644000175000001440000000243414754576332012542 /** \file wrap_i2c-dev.h * * Including file i2c-dev.h presents multiple issues. * This header file addresses those issues in one place. * * Currently this file is included by i2c_base_io.c and i2c_do_io.c. * * This code is in a separate file instead of an existing header * file because it is not part of the public interface of any * header file. */ // Copyright (C) 2014-2016 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef WRAP_I2C_DEV_H_ #define WRAP_I2C_DEV_H_ // On Fedora 23 and SUSE 13.2, there is no problem with NULL. // But on Fedora 22 and SUSE 13.1, we get an error that NULL is // undefined. Including stddef.h does not solve the problem - apparently // the dummy version in /usr/include/linux/i2c-dev.h is picked up. // This hack seems to solve that problem. #ifndef NULL #define NULL ((void*)0) #endif // On Fedora, i2c-dev.h is minimal. i2c.h is required for struct i2c_msg and // other stuff. On Ubuntu and SuSE, including both causes redefinition errors. // If I2C_FUNC_I2C is not defined, the definition is present in the full version // of i2c-dev.h but not in the abbreviated version, so i2c.h must be included. #include #ifndef I2C_FUNC_I2C #include #endif #endif /* WRAP_I2C_DEV_H_ */ ddcutil-2.2.0/src/i2c/i2c_execute.h0000644000175000001440000000303614754576332012456 /** @file i2c_execute.h * * Low level functions for writing to and reading from the I2C bus, * using various mechanisms. */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_EXECUTE_H_ #define I2C_EXECUTE_H_ #include "util/coredefs.h" #include "base/status_code_mgt.h" // Controls whether function #i2c_set_addr() retries from EBUSY error by // changing ioctl op I2C_SLAVE to op I2C_SLAVE_FORCE. extern bool i2c_forceable_slave_addr_flag; Status_Errno i2c_set_addr(int fd, int addr); /** Function template for I2C write function */ typedef Status_Errno_DDC (*I2C_Writer)( int fd, Byte slave_address, int bytect, Byte * bytes_to_write); /** Function template for I2C read function */ typedef Status_Errno_DDC (*I2C_Reader)( int fd, Byte slave_addr, bool read_bytewise, int bytect, Byte * readbuf); Status_Errno_DDC i2c_fileio_writer( int fd, Byte slave_address, int bytect, Byte * pbytes); Status_Errno_DDC i2c_fileio_reader ( int fd, Byte slave_address, bool read_bytewise, int bytect, Byte * readbuf); Status_Errno_DDC i2c_ioctl_writer( int fd, Byte slave_address, int bytect, Byte * pbytes); Status_Errno_DDC i2c_ioctl_reader( int fd, Byte slave_address, bool read_bytewise, int bytect, Byte * readbuf); void init_i2c_execute(); #endif /* I2C_EXECUTE_H_ */ ddcutil-2.2.0/src/i2c/i2c_strategy_dispatcher.h0000644000175000001440000000332314754576332015063 /** \file i2c_strategy_dispatcher.h * * Vestigial code for testing alternative mechanisms to read from and write to * the IC2 bus. */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_STRATEGY_DISPATCHER_H_ #define I2C_STRATEGY_DISPATCHER_H_ #include "util/coredefs.h" #include "base/execution_stats.h" #include "base/status_code_mgt.h" #include "i2c_execute.h" /** I2C IO strategy ids */ typedef enum { I2C_IO_STRATEGY_NOT_SET, I2C_IO_STRATEGY_FILEIO, ///< use file write() and read() I2C_IO_STRATEGY_IOCTL} ///< use ioctl(I2C_RDWR) I2C_IO_Strategy_Id; char * i2c_io_strategy_id_name(I2C_IO_Strategy_Id id); /** Describes one I2C IO strategy */ typedef struct { I2C_IO_Strategy_Id strategy_id; ///< id of strategy char * strategy_name; ///< name of strategy I2C_Writer i2c_writer; ///< writer function I2C_Reader i2c_reader; ///< read function char * i2c_writer_name; ///< write function name char * i2c_reader_name; ///< read function name } I2C_IO_Strategy; bool is_nvidia_einval_bug(I2C_IO_Strategy_Id strategy_id, int busno, int rc); void i2c_set_io_strategy_by_id(I2C_IO_Strategy_Id strategy_id); I2C_IO_Strategy_Id i2c_get_io_strategy_id(); Status_Errno_DDC invoke_i2c_writer( int fd, Byte slave_address, int bytect, Byte * bytes_to_write); Status_Errno_DDC invoke_i2c_reader( int fd, Byte slave_address, bool read_bytewise, int bytect, Byte * readbuf); void init_i2c_strategy_dispatcher(); #endif /* I2C_STRATEGY_DISPATCHER_H_ */ ddcutil-2.2.0/src/i2c/i2c_services.h0000644000175000001440000000042314754576332012634 /* @file i2c_services.h */ // Copyright (C) 2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_SERVICES_H_ #define I2C_SERVICES_H_ void init_i2c_services(); void terminate_i2c_services(); #endif /* I2C_SERVICES_H_ */ ddcutil-2.2.0/src/i2c/i2c_edid.h0000644000175000001440000000135114754576332011717 /** \file i2c_edid.h */ // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_EDID_H_ #define I2C_EDID_H_ /** \cond */ #include /** \endcond */ #include "util/edid.h" #include "util/data_structures.h" #include "base/core.h" #include "base/status_code_mgt.h" extern bool EDID_Read_Uses_I2C_Layer; extern bool EDID_Read_Bytewise; extern bool EDID_Write_Before_Read; extern int EDID_Read_Size; #ifdef TEST_EDID_SMBUS extern bool EDID_Read_Uses_Smbus; #endif Status_Errno_DDC i2c_get_raw_edid_by_fd(int fd, Buffer * rawedid); Status_Errno_DDC i2c_get_parsed_edid_by_fd(int fd, Parsed_Edid ** edid_ptr_loc); void init_i2c_edid(); #endif /* I2C_EDID_H_ */ ddcutil-2.2.0/src/i2c/i2c_bus_core.h0000644000175000001440000000550414754576332012617 /** @file i2c_bus_core.h * * I2C bus detection and inspection */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_BUS_CORE_H_ #define I2C_BUS_CORE_H_ /** \cond */ #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/edid.h" #include "util/error_info.h" #include "base/core.h" #include "base/displays.h" #include "base/execution_stats.h" #include "base/i2c_bus_base.h" #include "base/parms.h" #include "base/status_code_mgt.h" #include "sysfs/sysfs_sys_drm_connector.h" /** \def I2C_SLAVE_ADDR_MAX Addresses on an I2C bus are 7 bits in size */ #define I2C_SLAVE_ADDR_MAX 128 extern bool i2c_force_bus; extern bool all_video_adapters_implement_drm; extern bool use_drm_connector_states; extern bool try_get_edid_from_sysfs_first; extern int i2c_businfo_async_threshold; extern bool cross_instance_locks_enabled; Byte_Value_Array get_i2c_devices_by_existence_test(bool include_ignorable_devices); // Lifecycle I2C_Bus_Info * remove_i2c_bus_info(); // Bus open and close void add_open_failures_reported(Bit_Set_256 failures); void include_open_failures_reported(int busno); Error_Info * open_bus_basic(const char * filename, Byte callopts, int* fd_loc); Error_Info * i2c_open_bus_basic(const char * filename, Byte callopts, int* fd_loc); Error_Info * i2c_open_bus(int busno, Byte callopts, int * fd_loc); #ifdef ALT_LOCK_REC Error_Info * i2c_open_bus(int busno, Display_Lock_Record lockrec, Byte callopts, int * fd_loc); #endif Status_Errno i2c_close_bus(int busno, int fd, Call_Options callopts); // Bus inspection I2C_Bus_Info * i2c_get_and_check_bus_info(int busno); bool i2c_edid_exists(int busno); Status_Errno i2c_check_bus(I2C_Bus_Info * businfo); Error_Info * i2c_check_open_bus_alive(Display_Handle * dh); // Bus inventory - detect and probe buses Byte_Value_Array // one byte for each I2C bus number get_i2c_device_numbers_using_udev(bool include_ignorable_devices); Bit_Set_256 buses_bitset_from_businfo_array(GPtrArray * buses, bool only_connected); // buses: array of I2C_Bus_Info GPtrArray * i2c_detect_buses0(); int i2c_detect_buses(); // creates internal array of Bus_Info for I2C buses I2C_Bus_Info * i2c_detect_single_bus(int busno); Byte_Value_Array i2c_detect_attached_buses(); Bit_Set_256 i2c_detect_attached_buses_as_bitset(); Bit_Set_256 i2c_filter_buses_w_edid_as_bitset(BS256 bs_all_buses) ; Bit_Set_256 i2c_buses_w_edid_as_bitset(); // Reports void i2c_report_active_bus(I2C_Bus_Info * businfo, int depth); // Initialization void subinit_i2c_bus_core(); void init_i2c_bus_core(); #endif /* I2C_BUS_CORE_H_ */ ddcutil-2.2.0/src/libmain/0000775000175000001440000000000014754576333011125 5ddcutil-2.2.0/src/libmain/Makefile.am0000644000175000001440000000105514754153540013067 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) if WARNINGS_ARE_ERRORS_COND AM_CFLAGS += -Werror endif # AM_CFLAGS += -Wpedantic if ENABLE_CALLGRAPH_COND AM_CFLAGS += -fdump-rtl-expand endif CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libsharedlib.la libsharedlib_la_SOURCES = \ api_base.c \ api_displays.c \ api_error_info_internal.c \ api_metadata.c \ api_feature_access.c \ api_capabilities.c \ api_services_internal.c ddcutil-2.2.0/src/libmain/Makefile.in0000664000175000001440000005300214754576155013114 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @WARNINGS_ARE_ERRORS_COND_TRUE@am__append_1 = -Werror # AM_CFLAGS += -Wpedantic @ENABLE_CALLGRAPH_COND_TRUE@am__append_2 = -fdump-rtl-expand subdir = src/libmain ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsharedlib_la_LIBADD = am_libsharedlib_la_OBJECTS = api_base.lo api_displays.lo \ api_error_info_internal.lo api_metadata.lo \ api_feature_access.lo api_capabilities.lo \ api_services_internal.lo libsharedlib_la_OBJECTS = $(am_libsharedlib_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/api_base.Plo \ ./$(DEPDIR)/api_capabilities.Plo ./$(DEPDIR)/api_displays.Plo \ ./$(DEPDIR)/api_error_info_internal.Plo \ ./$(DEPDIR)/api_feature_access.Plo \ ./$(DEPDIR)/api_metadata.Plo \ ./$(DEPDIR)/api_services_internal.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libsharedlib_la_SOURCES) DIST_SOURCES = $(libsharedlib_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) $(am__append_1) $(am__append_2) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libsharedlib.la libsharedlib_la_SOURCES = \ api_base.c \ api_displays.c \ api_error_info_internal.c \ api_metadata.c \ api_feature_access.c \ api_capabilities.c \ api_services_internal.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libmain/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/libmain/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsharedlib.la: $(libsharedlib_la_OBJECTS) $(libsharedlib_la_DEPENDENCIES) $(EXTRA_libsharedlib_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libsharedlib_la_OBJECTS) $(libsharedlib_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/api_base.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/api_capabilities.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/api_displays.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/api_error_info_internal.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/api_feature_access.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/api_metadata.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/api_services_internal.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/api_base.Plo -rm -f ./$(DEPDIR)/api_capabilities.Plo -rm -f ./$(DEPDIR)/api_displays.Plo -rm -f ./$(DEPDIR)/api_error_info_internal.Plo -rm -f ./$(DEPDIR)/api_feature_access.Plo -rm -f ./$(DEPDIR)/api_metadata.Plo -rm -f ./$(DEPDIR)/api_services_internal.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/api_base.Plo -rm -f ./$(DEPDIR)/api_capabilities.Plo -rm -f ./$(DEPDIR)/api_displays.Plo -rm -f ./$(DEPDIR)/api_error_info_internal.Plo -rm -f ./$(DEPDIR)/api_feature_access.Plo -rm -f ./$(DEPDIR)/api_metadata.Plo -rm -f ./$(DEPDIR)/api_services_internal.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/libmain/api_base.c0000644000175000001440000012216714754153540012752 /** @file api_base.c #include * * C API base functions. */ // Copyright (C) 2015-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include // _GNU_SOURCE for dladdr() #include #include #include #include #include #include #include "public/ddcutil_c_api.h" #include "util/ddcutil_config_file.h" #include "util/debug_util.h" #include "util/file_util.h" #include "util/msg_util.h" #include "util/regex_util.h" #include "util/report_util.h" #include "util/sysfs_filter_functions.h" #include "util/traced_function_stack.h" #include "util/xdg_util.h" #include "base/base_services.h" #include "base/build_info.h" #include "base/build_timestamp.h" #include "base/core_per_thread_settings.h" #include "base/display_lock.h" #include "base/core.h" #include "base/dsa2.h" #include "base/parms.h" #include "base/per_display_data.h" #include "base/per_thread_data.h" #include "base/rtti.h" #include "base/trace_control.h" #include "base/tuned_sleep.h" #include "cmdline/cmd_parser.h" #include "cmdline/parsed_cmd.h" #include "sysfs/sysfs_base.h" #include "i2c/i2c_bus_core.h" // for testing watch_devices #include "i2c/i2c_execute.h" // for i2c_set_addr() #include "ddc/ddc_common_init.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_multi_part_io.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_serialize.h" #include "ddc/ddc_services.h" #include "ddc/ddc_try_data.h" #include "ddc/ddc_vcp.h" #include "dw/dw_main.h" #include "dw/dw_services.h" #include "libmain/api_error_info_internal.h" #include "libmain/api_base_internal.h" #include "libmain/api_services_internal.h" // // Forward Declarations // void init_api_base(); // // Globals // bool library_initialized = false; bool library_initialization_failed = false; static bool client_opened_syslog = false; static bool enable_init_msgs = false; static FILE * flog = NULL; static DDCA_Stats_Type requested_stats = 0; static bool per_display_stats = false; static bool dsa_detail_stats; static int active_calls = 0; static int max_active_calls = 0; static GMutex active_calls_mutex; static bool api_quiesced = false; static GMutex api_quiesced_mutex; // // Precondition Failure // DDCI_Api_Precondition_Failure_Mode api_failure_mode = DDCI_PRECOND_STDERR_RETURN; #ifdef UNUSED static DDCI_Api_Precondition_Failure_Mode ddci_set_precondition_failure_mode( DDCI_Api_Precondition_Failure_Mode failure_mode) { DDCI_Api_Precondition_Failure_Mode old = api_failure_mode; api_failure_mode = failure_mode; return old; } static DDCI_Api_Precondition_Failure_Mode ddci_get_precondition_failure_mode() { return api_failure_mode; } #endif // // Library Build Information // DDCA_Ddcutil_Version_Spec ddca_ddcutil_version(void) { static DDCA_Ddcutil_Version_Spec vspec = {255,255,255}; static bool vspec_init = false; if (!vspec_init) { #ifndef NDEBUG int ct = #endif sscanf(get_base_ddcutil_version(), "%hhu.%hhu.%hhu", &vspec.major, &vspec.minor, &vspec.micro); #ifndef NDEBUG assert(ct == 3); #endif vspec_init = true; } // DBGMSG("Returning: %d.%d.%d", vspec.major, vspec.minor, vspec.micro); return vspec; } /** Returns the ddcutil version as a string in the form "major.minor.micro". * */ const char * ddca_ddcutil_version_string(void) { return get_base_ddcutil_version(); } // Returns the full ddcutil version as a string that may be suffixed with an extension const char * ddca_ddcutil_extended_version_string(void) { return get_full_ddcutil_version(); } #ifdef UNUSED // Indicates whether the ddcutil library was built with support for USB connected monitors. bool ddca_built_with_usb(void) { #ifdef ENABLE_USB return true; #else return false; #endif } #endif // Alternative to individual ddca_built_with...() functions. // conciseness vs documentability // how to document bits? should doxygen doc be in header instead? DDCA_Build_Option_Flags ddca_build_options(void) { uint8_t result = 0x00; #ifdef ENABLE_USB result |= DDCA_BUILT_WITH_USB; #endif #ifdef FAILSIM_ENABLED result |= DDCA_BUILT_WITH_FAILSIM; #endif // DBGMSG("Returning 0x%02x", result); return result; } const char * ddca_libddcutil_filename(void) { Dl_info info = {NULL,NULL,NULL,NULL}; static char fullname[PATH_MAX]; static char * p = NULL; if (!p) { dladdr(ddca_build_options, &info); p = realpath(info.dli_fname, fullname); assert(p == fullname); } return p; } bool increment_active_api_calls(const char * funcname) { bool debug = false; DBGMSF(debug, "Starting. funcname=%s, active_calls=%d", funcname, active_calls); bool result = true; g_mutex_lock(&api_quiesced_mutex); // blocks API calls from starting g_mutex_lock(&active_calls_mutex); if (api_quiesced || library_disabled) result = false; else { active_calls++; if (active_calls > max_active_calls) max_active_calls = active_calls; } g_mutex_unlock(&active_calls_mutex); g_mutex_unlock(&api_quiesced_mutex); DBGMSF(debug, "funcname=%s, returning %s", funcname, SBOOL(result)); return result; } void decrement_active_api_calls(const char * funcname) { bool debug = false; DBGMSF(debug, "Starting. funcname=%s, active_calls=%d", funcname, active_calls); bool oops = false; g_mutex_lock(&active_calls_mutex); if (active_calls > 0) { active_calls--; } else { oops = true; } g_mutex_unlock(&active_calls_mutex); if (oops) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Unmatched active call ct in %s", funcname); } DBGMSF(debug, "Done funcname=%s, oops=%s", funcname, SBOOL(oops)); } /** Quiesce the API. * * When quiesced, API calls that can affect monitor state terminate immediately with status DDCRC_QUIESCED. */ void quiesce_api() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, ""); SYSLOG2(DDCA_SYSLOG_NOTICE, "Quiescing libddcutil API..."); bool oops = false; int slept_nanosec = 0; g_mutex_lock(&api_quiesced_mutex); g_mutex_lock(&active_calls_mutex); if (active_calls > 0) { int poll_max_millisec = 3000; // move to parms.h int poll_interval_millisec = 100; // move to parms.h int poll_max_nanosec = poll_max_millisec * 1000; int poll_interval_nanosec = poll_interval_millisec * 1000; oops = true; for (; slept_nanosec < poll_max_nanosec; slept_nanosec += poll_interval_nanosec) { usleep(poll_interval_nanosec); if (active_calls == 0) { oops = false; break; } } } g_mutex_unlock(&active_calls_mutex); api_quiesced = true; g_mutex_unlock(&api_quiesced_mutex); if (oops) { MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Error queiscing libdducitl API. %d active API calls outstanding.", active_calls); } else { SYSLOG2(DDCA_SYSLOG_NOTICE, "Quiesce libddcutil API complete"); } DBGTRC_DONE(debug, DDCA_TRC_API, "Terminating with %d active API calls outstanding. Waited %d millisec", active_calls, slept_nanosec/1000); } /** Unquiesce the API. */ void unquiesce_api() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, ""); SYSLOG2(DDCA_SYSLOG_NOTICE, "Unquiescing libddcutil API..."); g_mutex_lock(&api_quiesced_mutex); api_quiesced = false; g_mutex_unlock(&api_quiesced_mutex); DBGTRC_DONE(debug, DDCA_TRC_API, ""); } Error_Info* perform_parse( int new_argc, char ** new_argv, char * combined, Parsed_Cmd ** parsed_cmd_loc) { GPtrArray * errmsgs = g_ptr_array_new_with_free_func(g_free); bool debug = false; Error_Info * result = NULL; DBGF(debug, "Calling parse_command(), errmsgs=%p\n", errmsgs); *parsed_cmd_loc = parse_command(new_argc, new_argv, MODE_LIBDDCUTIL, errmsgs); DBGF(debug, "*parsed_cmd_loc=%p, errmsgs->len=%d", *parsed_cmd_loc, errmsgs->len); ASSERT_IFF(*parsed_cmd_loc, errmsgs->len == 0); if (!*parsed_cmd_loc) { if (test_emit_syslog(DDCA_SYSLOG_ERROR)) { syslog(LOG_ERR, "Invalid option string: %s", combined); for (int ndx = 0; ndx < errmsgs->len; ndx++) { char * msg = g_ptr_array_index(errmsgs,ndx); syslog(LOG_ERR, "%s", msg); } } result = ERRINFO_NEW(DDCRC_INVALID_CONFIG_FILE, "Invalid option string: %s", combined); for (int ndx = 0; ndx < errmsgs->len; ndx++) { char * msg = g_ptr_array_index(errmsgs, ndx); errinfo_add_cause(result, errinfo_new(DDCRC_INVALID_CONFIG_FILE, __func__, msg)); } } else { if (debug) dbgrpt_parsed_cmd(*parsed_cmd_loc, 1); } g_ptr_array_free(errmsgs, true); ASSERT_IFF(*parsed_cmd_loc, !result); return result; } static inline void emit_parse_info_msg(const char * msg, GPtrArray* infomsgs) { if (infomsgs) g_ptr_array_add(infomsgs, g_strdup_printf("%s%s", "libddcutil: ", msg)); SYSLOG2(DDCA_SYSLOG_NOTICE,"%s", msg); } // // Initialization // static Error_Info * get_parsed_libmain_config(const char * libopts_string, bool disable_config_file, GPtrArray* infomsgs, Parsed_Cmd** parsed_cmd_loc) { bool debug = false; DBGF(debug, "Starting. disable_config_file = %s, libopts_string = %sn", sbool(disable_config_file), libopts_string); char * msg = g_strdup_printf("Options passed from client: %s", (libopts_string) ? libopts_string : ""); emit_parse_info_msg(msg, infomsgs); free(msg); Error_Info * result = NULL; *parsed_cmd_loc = NULL; char ** libopts_tokens = NULL; int libopts_token_ct = 0; if (libopts_string) { libopts_token_ct = tokenize_options_line(libopts_string, &libopts_tokens); DBGF(debug, "libopts_token_ct = %d, libopts_tokens=%p:", libopts_token_ct,libopts_tokens); if (debug) ntsa_show(libopts_tokens); } Null_Terminated_String_Array cmd_name_array = calloc(2 + libopts_token_ct, sizeof(char*)); cmd_name_array[0] = strdup("libddcutil"); // so libddcutil not a special case for parser int ndx = 0; for (; ndx < libopts_token_ct; ndx++) cmd_name_array[ndx+1] = g_strdup(libopts_tokens[ndx]); cmd_name_array[ndx+1] = NULL; ntsa_free(libopts_tokens,true); DBGF(debug, "cmd_name_array=%p, cmd_name_array[1]=%p -> %s", cmd_name_array, cmd_name_array[0], cmd_name_array[0]); char ** new_argv = NULL; int new_argc = 0; char * untokenized_option_string = NULL; if (disable_config_file) { DBGF(debug, "config file disabled"); new_argv = ntsa_copy(cmd_name_array, true); new_argc = ntsa_length(cmd_name_array); ntsa_free(cmd_name_array, true); } else { GPtrArray * errmsgs = g_ptr_array_new_with_free_func(g_free); char * config_fn = NULL; DBGF(debug, "Calling apply_config_file()..."); int apply_config_rc = apply_config_file( "libddcutil", // use this section of config file ntsa_length(cmd_name_array), cmd_name_array, &new_argc, &new_argv, &untokenized_option_string, &config_fn, errmsgs); ntsa_free(cmd_name_array, true); assert(apply_config_rc <= 0); ASSERT_IFF(apply_config_rc == 0, errmsgs->len == 0); // DBGF(debug, "Calling ntsa_free(cmd_name_array=%p", cmd_name_array); DBGF(debug, "apply_config_file() returned: %d (%s), new_argc=%d, new_argv=%p:", apply_config_rc, psc_desc(apply_config_rc), new_argc, new_argv); if (apply_config_rc == -EBADMSG) { result = errinfo_new(DDCRC_INVALID_CONFIG_FILE, __func__, "Error(s) processing configuration file: %s", config_fn); for (int ndx = 0; ndx < errmsgs->len; ndx++) { errinfo_add_cause(result, errinfo_new(DDCRC_INVALID_CONFIG_FILE, __func__, g_ptr_array_index(errmsgs, ndx))); } } // else if (apply_config_rc == -ENOENT) { // result = errinfo_new(-ENOENT, __func__, "Configuration file not found"); // } else if (apply_config_rc < 0) { result = errinfo_new(apply_config_rc, __func__, "Unexpected error reading configuration file: %s", psc_desc(apply_config_rc)); } else { assert( new_argc == ntsa_length(new_argv) ); if (debug) ntsa_show(new_argv); if (untokenized_option_string && strlen(untokenized_option_string) > 0) { char * msg = g_strdup_printf("Using options from %s: %s", config_fn, untokenized_option_string); emit_parse_info_msg(msg, infomsgs); free(msg); } } g_ptr_array_free(errmsgs, true); free(config_fn); } if (!result) { // if no errors assert(new_argc >= 1); char * combined = strjoin((const char**)(new_argv+1), new_argc, " "); char * msg = g_strdup_printf("Applying combined libddcutil options: %s", combined); emit_parse_info_msg(msg, infomsgs); free(msg); result = perform_parse(new_argc, new_argv, combined, parsed_cmd_loc); ntsa_free(new_argv, true); free(combined); free(untokenized_option_string); } DBGF(debug, "Done. *parsed_cmd_loc=%p. Returning %s", *parsed_cmd_loc, errinfo_summary(result)); ASSERT_IFF(*parsed_cmd_loc, !result); return result; } #ifdef TESTING_CLEANUP void done() { printf("(%s) Starting\n", __func__); _ddca_terminate(); SYSLOG(LOG_INFO, "(%s) executing done()", __func__); printf("(%s) Done.\n", __func__); } void dummy_sigterm_handler() { printf("(%s) Executing. library_initialized = %s\n", __func__, SBOOL(library_initialized)); } void atexit_func() { printf("(%s) Executing. library_initalized = %s\n", __func__, SBOOL(library_initialized)); } #endif /** Initializes the ddcutil library module. * * Called automatically when the shared library is loaded. * * Registers functions in RTTI table, performs additional initialization * that cannot fail. */ void __attribute__ ((constructor)) _libddcutil_constructor(void) { bool debug = false; char * s = getenv("DDCUTIL_DEBUG_LIBINIT"); if (s && strlen(s) > 0) debug = true; DBGF(debug, "Starting. library built %s at %s", BUILD_DATE, BUILD_TIME); detect_stdout_stderr_redirection(); DBGF(debug, "stdout_stderr_redirected = %s", SBOOL(stdout_stderr_redirected)); syslog(LOG_NOTICE, "Starting libddcutil. library built %s at %s. stdout_stderr_redirected=%s", BUILD_DATE, BUILD_TIME, sbool(stdout_stderr_redirected)); init_api_base(); // registers functions in RTTI table init_base_services(); // initializes tracing related modules init_ddc_services(); // initializes i2c, usb, ddc, vcp, dynvcp init_dw_services(); // initializes dw init_api_services(); // other files in directory libmain #ifdef TESTING_CLEANUP // int atexit_rc = atexit(done); // TESTING CLEANUP // printf("(%s) atexit() returned %d\n", __func__, atexit_rc); #endif DBGF(debug, "Done."); } // // Profiling // void profiling_enable(bool enabled) { ptd_api_profiling_enabled = enabled; } void profiling_reset() { ptd_profile_reset_all_stats(); } void profile_start_call(void * func) { ptd_profile_function_start(func); } void profile_end_call(void * func) { ptd_profile_function_end(func); } void profile_report(FILE * dest, bool by_thread) { if (dest) { rpt_push_output_dest(dest); } if (by_thread) ptd_profile_report_all_threads(0); ptd_profile_report_stats_summary(0); if (dest) { rpt_pop_output_dest(); } } // // Tracing // /** Collects all output that normally goes to the terminal and appends it in * the specified file. The file is created if it does not already exist. * * @param library_trace_file file in which to store the output. * @param debug if true, issue debug messages * * If the file name is not fully qualified, it is considered to be a * subdirectory of the user's XDG state file, normally * $HOME/.local/state/libddcutil. */ void init_library_trace_file(char * library_trace_file, bool debug) { DBGF(debug, "library_trace_file = \"%s\"", library_trace_file); char * fq_trace_file = (library_trace_file[0] != '/') ? xdg_state_home_file("libddcutil", library_trace_file) : g_strdup(library_trace_file); fopen_mkdir(fq_trace_file, "a", stderr, &flog); if (flog) { DBGF(debug, "Writing %s trace output to %s", "libddcutil",fq_trace_file); syslog(LOG_NOTICE, "Trace destination: %s", fq_trace_file); time_t trace_start_time = time(NULL); char * trace_start_time_s = asctime(localtime(&trace_start_time)); if (trace_start_time_s[strlen(trace_start_time_s)-1] == 0x0a) trace_start_time_s[strlen(trace_start_time_s)-1] = 0; fprintf(flog, "%s tracing started %s\n", "libddcutil", trace_start_time_s); set_default_thread_output_settings(flog, flog); set_fout(flog); set_ferr(flog); rpt_set_default_output_dest(flog); // for future threads rpt_push_output_dest(flog); // for this thread } else { fprintf(stderr, "Error opening libddcutil trace file %s: %s\n", fq_trace_file, strerror(errno)); syslog(LOG_ERR, "Error opening libddcutil trace file %s: %s", fq_trace_file, strerror(errno)); } free(fq_trace_file); DBGF(debug, "Done"); } /** Cleanup at library termination * * - Terminates thread that watches for display addition or removal. * - Releases heap memory to avoid error reports from memory analyzers. */ void __attribute__ ((destructor)) _ddca_terminate(void) { bool debug = false; reset_current_traced_function_stack(); // ?? needed? DBGTRC_STARTING(debug, DDCA_TRC_API, "library_initialized = %s", SBOOL(library_initialized)); if (library_initialized) { if (debug) dbgrpt_display_locks(2); if (dsa2_is_enabled()) dsa2_save_persistent_stats(); if (display_caching_enabled) ddc_store_displays_cache(); ddc_discard_detected_displays(); if (requested_stats) ddc_report_stats_main(requested_stats, per_display_stats, dsa_detail_stats, false, 0); DDCA_Display_Event_Class active_classes; if (dw_is_watch_displays_executing()) dw_stop_watch_displays(/*wait=*/ true, &active_classes); // in case it was started DBGTRC_NOPREFIX(debug, DDCA_TRC_API, "After ddc_stop_watch_displays"); // sleep(5); // still needed? terminate_dw_services(); terminate_ddc_services(); terminate_base_services(); free_regex_hash_table(); library_initialized = false; if (flog) fclose(flog); DBGTRC_DONE(debug, DDCA_TRC_API, "library termination complete"); } else { DBGTRC_DONE(debug, DDCA_TRC_API, "library was already terminated"); // should be impossible } // Frees the traced function stack for the main thread. // For created threads, is called at time of thread termination free_current_traced_function_stack(); // must come after last DBG... call // special handling for termination msg if (syslog_level > DDCA_SYSLOG_NEVER) syslog(LOG_NOTICE, "libddcutil terminating."); if (syslog_level > DDCA_SYSLOG_NEVER && !client_opened_syslog) closelog(); } Error_Info * set_master_errinfo_from_init_errors( GPtrArray * errs) // array of Error_Info * { bool debug = false; DBGF(debug, "Starting. errs=%p", errs); Error_Info * master_error = NULL; if (errs && errs->len > 0) { master_error = errinfo_new(DDCRC_BAD_DATA, __func__, "Invalid configuration options"); for (int ndx = 0; ndx < errs->len; ndx++) { Error_Info * cur = g_ptr_array_index(errs, ndx); errinfo_add_cause(master_error, cur); } g_ptr_array_free(errs, false); } DBGF(debug, "Done. Returning %p"); return master_error; } DDCA_Status set_ddca_error_detail_from_init_errors( GPtrArray * errs) // array of Error_Info * { bool debug = false; DDCA_Status ddcrc = 0; if (errs && errs->len > 0) { Error_Info * master_error = errinfo_new(DDCRC_BAD_DATA, __func__, "Invalid configuration options"); ddcrc = DDCRC_BAD_DATA; for (int ndx = 0; ndx < errs->len; ndx++) { Error_Info * cur = g_ptr_array_index(errs, ndx); errinfo_add_cause(master_error, cur); } DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(master_error); errinfo_free_with_report(master_error, debug, __func__); save_thread_error_detail(public_error_detail); } // clear if no errors? return ddcrc; } DDCA_Syslog_Level ddca_syslog_level_from_name(const char * name) { return syslog_level_name_to_value(name); } void report_parse_errors0(Error_Info * erec, int depth, int max_depth) { char * edesc = psc_text(erec->status_code); if (depth == 0) { rpt_vstring(depth, "%s: %s", edesc, erec->detail); } else { rpt_vstring(depth, "%s", erec->detail); } if (depth < max_depth) { if (erec->cause_ct > 0) { for (int ndx = 0; ndx < erec->cause_ct; ndx++) { Error_Info * cur = erec->causes[ndx]; report_parse_errors0(cur, depth+1, max_depth); } } } } void report_parse_errors(Error_Info * erec) { if (erec) { rpt_push_output_dest(ferr()); report_parse_errors0(erec, 0, 3); rpt_pop_output_dest(); } } DDCA_Status ddci_init(const char * libopts, DDCA_Syslog_Level syslog_level_arg, DDCA_Init_Options opts, char*** infomsg_loc) { bool debug = false; char * s = getenv("DDCUTIL_DEBUG_LIBINIT"); if (s && strlen(s) > 0) debug = true; DBGF(debug, "Starting. library built %s at %s, library_initialized=%s", BUILD_DATE, BUILD_TIME, sbool(library_initialized)); if (infomsg_loc) *infomsg_loc = NULL; Parsed_Cmd * parsed_cmd = NULL; Error_Info * master_error = NULL; DDCA_Status ddcrc = 0; enable_init_msgs = opts & DDCA_INIT_OPTIONS_ENABLE_INIT_MSGS; // enable_init_msgs = true; // *** TEMP *** DBGF(debug, "enable_init_msgs=%s", SBOOL(enable_init_msgs)); if (library_initialized) { master_error = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "libddcutil already initialized"); syslog(LOG_ERR, "libddcutil already initialized"); goto bye; } client_opened_syslog = opts & DDCA_INIT_OPTIONS_CLIENT_OPENED_SYSLOG; DBGF(debug, "client_opened_syslog=%s, enable_syslog=%s", sbool(client_opened_syslog), sbool(enable_syslog)); if (syslog_level_arg == DDCA_SYSLOG_NOT_SET) syslog_level_arg = DEFAULT_LIBDDCUTIL_SYSLOG_LEVEL; enable_syslog = (syslog_level_arg == DDCA_SYSLOG_NEVER) ? false : true; // global in core.c if (enable_syslog) { if (!client_opened_syslog) { openlog("libddcutil", // prepended to every log message LOG_CONS | LOG_PID, // write to system console if error sending to system logger // include caller's process id LOG_USER); // generic user program, syslogger can use to determine how to handle } // special handling for start and termination msgs // always output if syslog is opened syslog(LOG_NOTICE, "Initializing libddcutil. ddcutil version: %s, shared library: %s", get_full_ddcutil_version(), ddca_libddcutil_filename()); syslog_level = syslog_level_arg; // global in trace_control.h } DBGF(debug, "syslog_level_arg = %s, syslog_level=%s, enable_syslog=%s", syslog_level_name(syslog_level_arg), syslog_level_name(syslog_level), sbool(enable_syslog)); GPtrArray* infomsgs = g_ptr_array_new_with_free_func(g_free); if ((opts & DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE) && !libopts) { parsed_cmd = new_parsed_cmd(); } else { master_error = get_parsed_libmain_config( libopts, opts & DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE, infomsgs, &parsed_cmd); ASSERT_IFF(master_error, !parsed_cmd); if (infomsgs && infomsgs->len > 0) { DBGF(debug, "emit infomsgs starting. enable_init_msgs=%s, stdout_stderr_redirected=%s, infomsgs->len=%d", sbool(enable_init_msgs), sbool(stdout_stderr_redirected), infomsgs->len); for (int ndx = 0; ndx < infomsgs->len; ndx++) { if (enable_init_msgs && !stdout_stderr_redirected) fprintf(fout(), "%s\n", (char*) g_ptr_array_index(infomsgs, ndx)); // already done in emit_parse_info_msg(): // syslog(LOG_NOTICE, "%s", (char*) g_ptr_array_index(infomsgs, ndx)); } DBGF(debug, "emit infomsgs done"); if (infomsg_loc) { *infomsg_loc = g_ptr_array_to_ntsa(infomsgs, /*duplicate=*/true); } g_ptr_array_free(infomsgs, true); } } DBGF(debug, "parsing complete"); if (!master_error) { if (parsed_cmd->trace_destination) { DBGF(debug, "Setting library trace file: %s", parsed_cmd->trace_destination); init_library_trace_file(parsed_cmd->trace_destination, debug); } master_error = init_tracing(parsed_cmd); if (master_error) { DBGF(debug, "init_tracing failed"); free_parsed_cmd(parsed_cmd); } else DBGF(debug, "init_tracing succeeded"); } if (!master_error) { requested_stats = parsed_cmd->stats_types; ptd_api_profiling_enabled = parsed_cmd->flags & CMD_FLAG_PROFILE_API; per_display_stats = parsed_cmd->flags & CMD_FLAG_VERBOSE_STATS; dsa_detail_stats = parsed_cmd->flags & CMD_FLAG_INTERNAL_STATS; Error_Info * submaster_status = submaster_initializer(parsed_cmd); if (submaster_status) { master_error = ERRINFO_NEW(DDCRC_UNINITIALIZED, "Initialization failed"); errinfo_add_cause(master_error, submaster_status); } } assert(master_error || parsed_cmd); // avoid null-dereference warning if (master_error) { syslog(LOG_CRIT, "Library initialization failed: %s", psc_desc(master_error->status_code)); for (int ndx = 0; ndx < master_error->cause_ct; ndx++) { syslog(LOG_CRIT, "%s", master_error->causes[ndx]->detail); } if (enable_init_msgs) { DBGF(debug, "Calling report_parse_errors()", __func__); report_parse_errors(master_error); } // errinfo_free(master_error); library_initialization_failed = true; } else if (library_disabled) { DBGF(debug, "libddcutil disabled"); master_error = ERRINFO_NEW(DDCRC_INVALID_OPERATION, "libddcutil disabled"); syslog(LOG_ERR, "libddcutil disabled"); library_initialization_failed = true; } else { DBGF(debug, "performing display detection ..."); i2c_detect_buses(); ddc_ensure_displays_detected(); #ifdef OUT if (parsed_cmd->flags&CMD_FLAG_WATCH_DISPLAY_HOTPLUG_EVENTS) { dw_start_watch_displays(DDCA_EVENT_CLASS_DISPLAY_CONNECTION | DDCA_EVENT_CLASS_DPMS); SYSLOG2(DDCA_SYSLOG_NOTICE, "Started watch displays for DDCA_EVENT_CLASS_DISPLAY_CONNECTION | DDCA_EVENT_CLASS_DPMS"); } #endif library_initialized = true; library_initialization_failed = false; syslog(LOG_NOTICE, "Library initialization complete."); free_parsed_cmd(parsed_cmd); } bye: if (master_error) { ddcrc = master_error->status_code; DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(master_error); save_thread_error_detail(public_error_detail); errinfo_free(master_error); } DBGF(debug, "Done. Returning: %s", psc_desc(ddcrc)); return ddcrc; } DDCA_Status ddca_init(const char * libopts, DDCA_Syslog_Level syslog_level_arg, DDCA_Init_Options opts) { return ddci_init(libopts, syslog_level_arg, opts, NULL); } DDCA_Status ddca_init2(const char * libopts, DDCA_Syslog_Level syslog_level_arg, DDCA_Init_Options opts, char*** infomsg_loc ) { return ddci_init(libopts, syslog_level_arg, opts, infomsg_loc); } DDCA_Status ddca_start_watch_displays(DDCA_Display_Event_Class enabled_classes) { bool debug = false; API_PROLOGX(debug, RESPECT_QUIESCE, "enabled_classes=0x%02x", enabled_classes); DBGTRC_NOPREFIX(debug, DDCA_TRC_API, "all_video_adapters_implement_drm=%s", sbool(all_video_adapters_implement_drm)); if (enabled_classes == DDCA_EVENT_CLASS_ALL) enabled_classes = DDCA_EVENT_CLASS_DISPLAY_CONNECTION; DDCA_Error_Detail * edet = NULL; #ifdef ENABLE_UDEV if (!all_video_adapters_implement_drm) { edet = new_ddca_error_detail(DDCRC_INVALID_OPERATION, "Display hotplug detection requires DRM enabled video drivers"); } else if (enabled_classes == DDCA_EVENT_CLASS_NONE) { edet = new_ddca_error_detail(DDCRC_ARG, "No event class specified"); } else if (enabled_classes&DDCA_EVENT_CLASS_DPMS) { edet = new_ddca_error_detail(DDCRC_UNIMPLEMENTED, "Watching for DPMS state changes unimplemented"); } else if (enabled_classes != DDCA_EVENT_CLASS_DISPLAY_CONNECTION) { edet = new_ddca_error_detail (DDCRC_ARG, "Invalid event class specified"); } else { Error_Info * erec = dw_start_watch_displays(enabled_classes); edet = error_info_to_ddca_detail(erec); ERRINFO_FREE(erec); } #else edet = new_ddca_error_detail(DDCRC_INVALID_OPERATION, "Display change detection requires UDEV"); #endif DDCA_Status ddcrc = 0; if (edet) { ddcrc = edet->status_code; save_thread_error_detail(edet); } API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, ddcrc, ""); } DDCA_Status ddca_stop_watch_displays(bool wait) { bool debug = false; API_PROLOGX(debug, NORESPECT_QUIESCE, "wait=%s", SBOOL(wait)); DDCA_Display_Event_Class active_classes; DDCA_Status ddcrc = dw_stop_watch_displays(wait, &active_classes); API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, ddcrc, ""); } DDCA_Status ddca_get_active_watch_classes(DDCA_Display_Event_Class * classes_loc) { bool debug = false; API_PROLOGX(debug, NORESPECT_QUIESCE, "Starting classes_loc=%p", classes_loc); DDCA_Status ddcrc = dw_get_active_watch_classes(classes_loc); API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, ddcrc, "*classes_loc=0x%02x", *classes_loc); } DDCA_Status ddca_get_display_watch_settings(DDCA_DW_Settings * settings_buffer) { bool debug = false; API_PROLOGX(debug, NORESPECT_QUIESCE, "Starting"); DDCA_Status ddcrc = DDCRC_OK; if (!settings_buffer) ddcrc = DDCRC_ARG; else dw_get_display_watch_settings(settings_buffer); API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, ddcrc, "Done"); } DDCA_Status ddca_set_display_watch_settings(DDCA_DW_Settings * settings_buffer) { bool debug = false; API_PROLOGX(debug, NORESPECT_QUIESCE, "Starting"); DDCA_Status ddcrc = DDCRC_ARG; if (settings_buffer) ddcrc = dw_set_display_watch_settings(settings_buffer); API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, ddcrc, "Done"); } // // Error Detail // DDCA_Error_Detail * ddca_get_error_detail() { bool debug = false; DBGMSF(debug, "Starting"); DDCA_Error_Detail * result = dup_error_detail(get_thread_error_detail()); if (debug) { DBGMSG("Done. Returning: %p", result); if (result) report_error_detail(result, 2); } return result; } void ddca_free_error_detail(DDCA_Error_Detail * ddca_erec) { free_error_detail(ddca_erec); } void ddca_report_error_detail(DDCA_Error_Detail * ddca_erec, int depth) { report_error_detail(ddca_erec, depth); } // DDCA_Error_Detail * ddca_dup_error_detail(DDCA_Error_Detail * original) { // return dup_error_detail(original); // } // // Status Code Management // const char * ddca_rc_name(DDCA_Status status_code) { char * result = NULL; Status_Code_Info * code_info = find_status_code_info(status_code); if (code_info) result = code_info->name; return result; } const char * ddca_rc_desc(DDCA_Status status_code) { char * result = "unknown status code"; Status_Code_Info * code_info = find_status_code_info(status_code); if (code_info) result = code_info->description; return result; } // // Output redirection // // Redirects output that normally would go to STDOUT void ddca_set_fout(FILE * fout) { // DBGMSG("Starting. fout=%p", fout); set_fout(fout); } void ddca_set_fout_to_default(void) { set_fout_to_default(); } // Redirects output that normally would go to STDERR void ddca_set_ferr(FILE * ferr) { set_ferr(ferr); } void ddca_set_ferr_to_default(void) { set_ferr_to_default(); } // // Output capture - convenience functions // void ddca_start_capture(DDCA_Capture_Option_Flags flags) { bool debug = false; DBGF(debug, "flags=0x%02x", flags); start_capture(flags); } char * ddca_end_capture(void) { bool debug = false; char * result = end_capture(); DBGF(debug, "Returning %p", result); return result; } // // Message Control // DDCA_Output_Level ddca_get_output_level(void) { return get_output_level(); } DDCA_Output_Level ddca_set_output_level(DDCA_Output_Level newval) { return set_output_level(newval); } char * ddca_output_level_name(DDCA_Output_Level val) { return output_level_name(val); } // // Global Settings // #ifdef REMOVED int ddca_max_max_tries(void) { return MAX_MAX_TRIES; } // *** THIS IS FOR THE CURRENT THREAD // *** replace using function specifying display // *** for now, revert to old try_data_get_maxtries2() int ddca_get_max_tries(DDCA_Retry_Type retry_type) { // stats for multi part writes and reads are separate, but the // max tries for both are identical // #ifndef NDEBUG Retry_Op_Value result3 = try_data_get_maxtries2((Retry_Operation) retry_type); // #endif // // new way using retry_mgt // Retry_Op_Value result2 = trd_get_thread_max_tries((Retry_Operation) retry_type); // assert(result == result2); // assert(result2 == result3); return result3; } // ** THIS IS FOR CURRENT THREAD - FIX DDCA_Status ddca_set_max_tries( DDCA_Retry_Type retry_type, int max_tries) { DDCA_Status rc = 0; free_thread_error_detail(); if (max_tries < 1 || max_tries > MAX_MAX_TRIES) rc = DDCRC_ARG; else { try_data_set_maxtries2((Retry_Operation) retry_type, max_tries); // for DDCA_MULTI_PART_TRIES, set both MULTI_PART_WRITE_OP and MULTI_PART_READ_OP if (retry_type == DDCA_MULTI_PART_TRIES) try_data_set_maxtries2(MULTI_PART_WRITE_OP, max_tries); // new way, set in retry_mgt #ifdef TRD trd_set_thread_max_tries((Retry_Operation) retry_type, max_tries); if (retry_type == DDCA_MULTI_PART_TRIES) trd_set_thread_max_tries(MULTI_PART_WRITE_OP, max_tries); #endif } return rc; } #endif bool ddca_enable_verify(bool onoff) { return ddc_set_verify_setvcp(onoff); } bool ddca_is_verify_enabled() { return ddc_get_verify_setvcp(); } #ifdef REMOVED // *** FOR CURRENT THREAD double ddca_set_default_sleep_multiplier(double multiplier) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, "Setting multiplier = %6.3f", multiplier); double old_value = -1.0; if (multiplier >= 0.0 && multiplier <= 10.0) { // #ifdef TSD old_value = pdd_get_default_sleep_multiplier_factor(); pdd_set_default_sleep_multiplier_factor(multiplier, Reset); // #endif } DBGTRC_DONE(debug, DDCA_TRC_API, "Returning: %6.3f", old_value); return old_value; } double ddca_get_default_sleep_multiplier() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, ""); double result = pdd_get_default_sleep_multiplier_factor(); DBGTRC(debug, DDCA_TRC_API, "Returning %6.3f", result); return result; } void ddca_set_global_sleep_multiplier(double multiplier) { ddca_set_default_sleep_multiplier(multiplier); return; } double ddca_get_global_sleep_multiplier() { return ddca_get_default_sleep_multiplier(); } #endif // for display on current thread double ddca_set_sleep_multiplier(double multiplier) { bool debug = false; reset_current_traced_function_stack(); DBGTRC_STARTING(debug, DDCA_TRC_API, "Setting multiplier = %6.3f", multiplier); double old_value = -1.0; if (multiplier >= 0.0 && multiplier <= 10.0) { Per_Thread_Data * ptd = ptd_get_per_thread_data(); if (ptd->cur_dh) { Per_Display_Data * pdd = ptd->cur_dh->dref->pdd; old_value = pdd->user_sleep_multiplier; pdd_reset_multiplier(pdd, multiplier); } } DBGTRC_DONE(debug, DDCA_TRC_API, "Returning: %6.3f", old_value); return old_value; } double ddca_get_sleep_multiplier() { bool debug = false; reset_current_traced_function_stack(); DBGTRC(debug, DDCA_TRC_API, ""); Per_Thread_Data * ptd = ptd_get_per_thread_data(); double result = -1.0f; if (ptd->cur_dh) { Per_Display_Data * pdd = ptd->cur_dh->dref->pdd; result = pdd->user_sleep_multiplier; } #ifdef TSD double result = tsd_get_sleep_multiplier_factor(); #endif DBGTRC(debug, DDCA_TRC_API, "Returning %6.3f", result); return result; } #ifdef RELEASE_2_1_0 double ddca_set_sleep_multiplier(double multiplier) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, "Setting multiplier = %6.3f", multiplier); double old_value = -1.0; if (multiplier >= 0.0 && multiplier <= 10.0) { Per_Thread_Data * ptd = ptd_get_per_thread_data(); old_value = ptd->sleep_multiplier; ptd->sleep_multiplier = multiplier; } DBGTRC_DONE(debug, DDCA_TRC_API, "Returning: %6.3f", old_value); return old_value; } double ddca_get_sleep_multiplier() { bool debug = false; DBGTRC(debug, DDCA_TRC_API, ""); Per_Thread_Data * ptd = ptd_get_per_thread_data(); double result = ptd->sleep_multiplier; DBGTRC(debug, DDCA_TRC_API, "Returning %6.3f", result); return result; } #endif #ifdef FUTURE /** Gets the I2C timeout in milliseconds for the specified timeout class. * @param timeout_type timeout type * @return timeout in milliseconds */ int ddca_get_timeout_millis( DDCA_Timeout_Type timeout_type) { return 0; // *** UNIMPLEMENTED *** } /** Sets the I2C timeout in milliseconds for the specified timeout class * @param timeout_type timeout class * @param millisec timeout to set, in milliseconds */ void ddca_set_timeout_millis( DDCA_Timeout_Type timeout_type, int millisec) { // *** UNIMPLEMENTED } #endif #ifdef REMOVED /** Controls the force I2C slave address setting. * * Normally, ioctl operation I2C_SLAVE is used to set the I2C slave address. * If that returns EBUSY and this setting is in effect, slave address setting * is retried using operation I2C_SLAVE_FORCE. * * @param[in] onoff true/false * @return prior value * @since 1.2.2 */ bool ddca_enable_force_slave_address(bool onoff); /** Query the force I2C slave address setting. * * @return true/false * @since 1.2.2 */ bool ddca_is_force_slave_address_enabled(void); #endif #ifdef REMOVED bool ddca_enable_force_slave_address(bool onoff) { bool old = i2c_forceable_slave_addr_flag; i2c_forceable_slave_addr_flag = onoff; return old; } bool ddca_is_force_slave_address_enabled(void) { return i2c_forceable_slave_addr_flag; } #endif // // Statistics // // TODO: Add functions to access ddcutil's runtime error statistics void ddca_reset_stats(void) { DBGMSG("Executing"); g_mutex_lock(&api_quiesced_mutex); g_mutex_lock(&active_calls_mutex); ddc_reset_stats_main(); max_active_calls = 0; g_mutex_unlock(&active_calls_mutex); g_mutex_unlock(&api_quiesced_mutex); } // TODO: Functions that return stats in data structures void ddca_show_stats( DDCA_Stats_Type stats_types, bool per_display_stats, int depth) { bool debug = false; API_PROLOG_NO_DISPLAY_IO(debug, "stats_types=0x%02x, per_display_stats=%s", stats_types, SBOOL(per_display_stats) ); if (stats_types) { ddc_report_stats_main( stats_types, per_display_stats, per_display_stats, false, depth); rpt_nl(); } rpt_vstring(0, "Max concurrent API calls: %d", max_active_calls); #ifdef REDUNDANT if (stats_types & DDCA_STATS_API) { if (ptd_api_profiling_enabled) { rpt_nl(); profile_report(NULL, false); // redundant } } #endif API_EPILOG_NO_RETURN(debug, NORESPECT_QUIESCE, ""); } void ddca_report_locks( int depth) { dbgrpt_display_locks(depth); } void init_api_base() { // DBGMSG("Executing"); RTTI_ADD_FUNC(_ddca_terminate); RTTI_ADD_FUNC(ddca_start_watch_displays); RTTI_ADD_FUNC(ddca_stop_watch_displays); RTTI_ADD_FUNC(ddca_get_active_watch_classes); RTTI_ADD_FUNC(ddca_start_capture); RTTI_ADD_FUNC(ddca_end_capture); RTTI_ADD_FUNC(quiesce_api); RTTI_ADD_FUNC(unquiesce_api); #ifdef REMOVED RTTI_ADD_FUNC(ddca_set_sleep_multiplier); RTTI_ADD_FUNC(ddca_set_default_sleep_multiplier); #endif } ddcutil-2.2.0/src/libmain/api_displays.c0000644000175000001440000013660714754153540013674 /** @file api_displays.c */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include #include #include "public/ddcutil_types.h" #include "public/ddcutil_status_codes.h" #include "public/ddcutil_c_api.h" #include "util/linux_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #include "base/core.h" #include "base/dsa2.h" #include "base/displays.h" #include "base/monitor_model_key.h" #include "base/per_display_data.h" #include "base/rtti.h" #include "sysfs/sysfs_conflicting_drivers.h" #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "ddc/ddc_display_ref_reports.h" #include "ddc/ddc_display_selection.h" #include "ddc/ddc_displays.h" #include "ddc/ddc_packet_io.h" #include "ddc/ddc_vcp_version.h" #include "dw/dw_main.h" #include "dw/dw_status_events.h" #include "dw/dw_udev.h" #include "libmain/api_base_internal.h" #include "libmain/api_error_info_internal.h" #include "libmain/api_displays_internal.h" static inline bool valid_display_handle(Display_Handle * dh) { return (dh && memcmp(dh->marker, DISPLAY_HANDLE_MARKER, 4) == 0); } #ifdef UNUSED static inline bool valid_display_ref(Display_Ref * dref) { return (dref && memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0); } #endif #ifdef OLD DDCA_Status ddci_validate_ddca_display_ref( DDCA_Display_Ref ddca_dref, bool basic_only, bool require_not_asleep, Display_Ref** dref_loc) { if (dref_loc) *dref_loc = NULL; Display_Ref * dref = (Display_Ref *) ddca_dref; DDCA_Status result = ddc_validate_display_ref(dref, basic_only, require_not_asleep); if (result == DDCRC_OK && dref_loc) *dref_loc = dref; return result; } #endif /** Validates an opaque #DDCA_Display_Ref, returning the corresponding * #Display_Ref if successful. * * @param ddca_dref DDCA_Display_Ref * @param dh_loc address at which to return the underlying Display_Handle. * @return */ DDCA_Status ddci_validate_ddca_display_ref2( DDCA_Display_Ref ddca_dref, Dref_Validation_Options validation_options, Display_Ref** dref_loc) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "ddca_dref=%p=%d, validation_options=0x%02x, dref_loc=%p", ddca_dref, ddca_dref, validation_options, dref_loc); DDCA_Status result = DDCRC_OK; if (dref_loc) *dref_loc = NULL; if (debug) dbgrpt_published_dref_hash("published_dref_hash", 1); Display_Ref * dref = dref_from_published_ddca_dref(ddca_dref); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "dref_from_ddca_dref() returned %s", dref_reprx_t(dref)); if (!dref) { result = DDCRC_ARG; } else { // should be redundant with ddc_validate_display_ref2(), but something not being caught if (dref->flags & DREF_REMOVED) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "DREF_REMOVED set!"); SYSLOG2(DDCA_SYSLOG_WARNING, "DREF_REMOVED set for %s", dref_reprx_t(dref)); result = DDCRC_DISCONNECTED; } else if ( !(dref->flags & DREF_DDC_COMMUNICATION_WORKING) && !(validation_options & DREF_VALIDATE_DDC_COMMUNICATION_FAILURE_OK) ) { DBGTRC_NOPREFIX(true, DDCA_TRC_NONE, "DREF_DDC_COMMUNICATION_WORKING not set!"); result = DDCRC_INVALID_DISPLAY; } else { result = ddc_validate_display_ref2(dref, validation_options); } } if (result == DDCRC_OK && dref_loc) { *dref_loc = dref; DBGTRC_RET_DDCRC(debug, DDCA_TRC_NONE, result, "ddca_dref=%p=%d. *dref_loc=%p -> %s", ddca_dref, ddca_dref, *dref_loc, dref_reprx_t(*dref_loc)); } else DBGTRC_RET_DDCRC(debug, DDCA_TRC_NONE, result, "ddca_dref=%p=%d", ddca_dref, ddca_dref); return result; } #ifdef UNUSED Display_Handle * validated_ddca_display_handle(DDCA_Display_Handle ddca_dh) { Display_Handle * dh = (Display_Handle *) ddca_dh; if (dh) { if (memcmp(dh->marker, DISPLAY_HANDLE_MARKER, 4) != 0 || !ddc_is_valid_display_handle(dh) ) dh=NULL; } return dh; } #endif /** Validates an opaque #DDCA_Display_Handle, returning the corresponding * #Display_Handle if successful. * * @param ddca_dh DDCA_Display_Handle * @param dh_loc address at which to return the underlying Display_Handle. * @return */ DDCA_Status validate_ddca_display_handle(DDCA_Display_Handle ddca_dh, Display_Handle** dh_loc) { if (dh_loc) *dh_loc = NULL; Display_Handle * dh = (Display_Handle *) ddca_dh; DDCA_Status result = DDCRC_ARG; if (dh && memcmp(dh->marker, DISPLAY_HANDLE_MARKER,4) == 0) { result = ddc_validate_display_handle2(dh); } if (result == DDCRC_OK && dh_loc) *dh_loc = dh; return result; } // forward declarations STATIC void dbgrpt_display_info(DDCA_Display_Info * dinfo, int depth); STATIC void dbgrpt_display_info_list(DDCA_Display_Info_List * dlist, int depth); #ifdef REMOVED DDCA_Status ddca_enable_usb_display_detection(bool onoff) { return ddc_enable_usb_display_detection(onoff); } bool ddca_ddca_is_usb_display_detection_enabled() { return ddc_is_usb_display_detection_enabled(); } #endif // // Display Identifiers // DDCA_Status ddca_create_dispno_display_identifier( int dispno, DDCA_Display_Identifier* did_loc) { free_thread_error_detail(); reset_current_traced_function_stack(); // assert(did_loc); API_PRECOND(did_loc); Display_Identifier* did = create_dispno_display_identifier(dispno); *did_loc = did; assert(*did_loc); return 0; } DDCA_Status ddca_create_busno_display_identifier( int busno, DDCA_Display_Identifier* did_loc) { free_thread_error_detail(); // assert(did_loc); reset_current_traced_function_stack(); API_PRECOND(did_loc); Display_Identifier* did = create_busno_display_identifier(busno); *did_loc = did; assert(*did_loc); return 0; } DDCA_Status ddca_create_mfg_model_sn_display_identifier( const char* mfg_id, const char* model_name, const char* serial_ascii, DDCA_Display_Identifier* did_loc) { free_thread_error_detail(); reset_current_traced_function_stack(); // assert(did_loc); API_PRECOND(did_loc); *did_loc = NULL; DDCA_Status rc = 0; // break up the invalid argument tests for clarity // At least 1 argument must be specified if ( ( !mfg_id || strlen(mfg_id) == 0) && ( !model_name || strlen(model_name) == 0) && ( !serial_ascii || strlen(serial_ascii) == 0) ) rc = DDCRC_ARG; // check if any arguments are too long else if ( (model_name && strlen(model_name) >= EDID_MODEL_NAME_FIELD_SIZE) || (mfg_id && strlen(mfg_id) >= EDID_MFG_ID_FIELD_SIZE) || (serial_ascii && strlen(serial_ascii) >= EDID_SERIAL_ASCII_FIELD_SIZE) ) rc = DDCRC_ARG; else { *did_loc = create_mfg_model_sn_display_identifier( mfg_id, model_name, serial_ascii); } assert( (rc==0 && *did_loc) || (rc!=0 && !*did_loc)); return rc; } DDCA_Status ddca_create_edid_display_identifier( const Byte * edid, DDCA_Display_Identifier * did_loc) // 128 byte EDID { // assert(did_loc); free_thread_error_detail(); reset_current_traced_function_stack(); API_PRECOND(did_loc); *did_loc = NULL; DDCA_Status rc = 0; if (edid == NULL) { rc = DDCRC_ARG; *did_loc = NULL; } else { *did_loc = create_edid_display_identifier(edid); } assert( (rc==0 && *did_loc) || (rc!=0 && !*did_loc)); return rc; } DDCA_Status ddca_create_usb_display_identifier( int bus, int device, DDCA_Display_Identifier* did_loc) { // assert(did_loc); free_thread_error_detail(); reset_current_traced_function_stack(); API_PRECOND(did_loc); Display_Identifier* did = create_usb_display_identifier(bus, device); *did_loc = did; assert(*did_loc); return 0; } DDCA_Status ddca_create_usb_hiddev_display_identifier( int hiddev_devno, DDCA_Display_Identifier* did_loc) { // assert(did_loc); free_thread_error_detail(); reset_current_traced_function_stack(); API_PRECOND(did_loc); Display_Identifier* did = create_usb_hiddev_display_identifier(hiddev_devno); *did_loc = did; assert(*did_loc); return 0; } DDCA_Status ddca_free_display_identifier( DDCA_Display_Identifier did) { free_thread_error_detail(); DDCA_Status rc = 0; Display_Identifier * pdid = (Display_Identifier *) did; if (pdid) { if ( memcmp(pdid->marker, DISPLAY_IDENTIFIER_MARKER, 4) != 0 ) rc = DDCRC_ARG; else free_display_identifier(pdid); } return rc; } const char * ddca_did_repr(DDCA_Display_Identifier ddca_did) { // DBGMSG("Starting. ddca_did=%p", ddca_did); char * result = NULL; Display_Identifier * pdid = (Display_Identifier *) ddca_did; if (pdid != NULL && memcmp(pdid->marker, DISPLAY_IDENTIFIER_MARKER, 4) == 0 ) { result = did_repr(pdid); } // DBGMSG("Done. Returning: %p", result); return result; } // // Display References // DDCA_Status ddca_get_display_ref( DDCA_Display_Identifier did, DDCA_Display_Ref* dref_loc) { free_thread_error_detail(); bool debug = false; API_PROLOGX(debug, NORESPECT_QUIESCE, "did=%p, dref_loc=%p", did, dref_loc); assert(library_initialized); API_PRECOND_W_EPILOG(dref_loc); *dref_loc = NULL; DDCA_Status rc = 0; ddc_ensure_displays_detected(); Display_Identifier * pdid = (Display_Identifier *) did; if (!pdid || memcmp(pdid->marker, DISPLAY_IDENTIFIER_MARKER, 4) != 0 ) { rc = DDCRC_ARG; } else { Display_Ref* dref = get_display_ref_for_display_identifier(pdid, CALLOPT_NONE); if (debug) DBGMSG("get_display_ref_for_display_identifier() returned %p", dref); if (dref) *dref_loc = dref; else rc = DDCRC_INVALID_DISPLAY; } API_EPILOG_BEFORE_RETURN(debug, NORESPECT_QUIESCE, rc, "*dref_loc=%p", psc_name_code(rc), *dref_loc); TRACED_ASSERT( (rc==0 && *dref_loc) || (rc!=0 && !*dref_loc) ); return rc; } // deprecated DDCA_Status ddca_create_display_ref( DDCA_Display_Identifier did, DDCA_Display_Ref* dref_loc) { return ddca_get_display_ref(did, dref_loc); } #ifdef REMOVED /** @deprecated All display references are persistent * * Frees a display reference. * * Use this function to safely release a #DDCA_Display_Ref. * If the display reference was dynamically created, it is freed. * If the display reference was permanently allocated (normal case), does nothing. * * @param[in] dref display reference to free * @retval DDCRC_OK success, or dref == NULL * @retval DDCRC_ARG dref does not point to a valid display reference * @retval DDCRC_LOCKED dref is to a transient instance, and it is referenced * by an open display handle * * @ingroup api_display_spec */ // __attribute__ ((deprecated ("DDCA_Display_Refs are always persistent"))) DDCA_Status ddca_free_display_ref( DDCA_Display_Ref dref); #endif #ifdef REMOVED // deprecated, not needed, in library there are no transient display refs DDCA_Status ddca_free_display_ref(DDCA_Display_Ref ddca_dref) { bool debug = false; API_PROLOG(debug, "ddca_dref=%p", ddca_dref); DDCA_Status psc = 0; free_thread_error_detail(); if (ddca_dref) { WITH_VALIDATED_DR3(ddca_dref, psc, { if (dref->flags & DREF_TRANSIENT) psc = free_display_ref(dref); } ); } API_EPILOG_BEFORE_RETURN(debug, psc, ""); return psc; } #endif DDCA_Status ddca_redetect_displays() { bool debug = false; API_PROLOGX(debug, NORESPECT_QUIESCE, ""); quiesce_api(); dw_redetect_displays(); unquiesce_api(); API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, 0, ""); } const char * ddca_dref_repr(DDCA_Display_Ref ddca_dref) { bool debug = false; reset_current_traced_function_stack(); DBGTRC_STARTING(debug, DDCA_TRC_NONE, "ddca_dref=%p", ddca_dref); Display_Ref * dref = dref_from_published_ddca_dref(ddca_dref); char * result = (dref) ? dref_reprx_t(dref) : "Invalid DDCA_Display_Ref"; DBGTRC_DONE(debug, DDCA_TRC_NONE, "ddca_dref=%p, returning: %s", ddca_dref, result); return result; } void ddca_dbgrpt_display_ref( DDCA_Display_Ref ddca_dref, int depth) { bool debug = false; reset_current_traced_function_stack(); DBGMSF(debug, "Starting. ddca_dref = %p, depth=%d", ddca_dref, depth); Display_Ref * dref = ddca_dref; if (dref && memcmp(dref->marker, DISPLAY_REF_MARKER, 4) == 0) { rpt_vstring(depth, "DDCA_Display_Ref at %p:", dref); dbgrpt_display_ref(dref, true, depth+1); } else { rpt_vstring(depth, "Not a display ref: %p", dref); } } DDCA_Status ddca_report_display_by_dref( DDCA_Display_Ref ddca_dref, int depth) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dref=%p", ddca_dref); assert(library_initialized); Display_Ref * dref = NULL; // DDCA_Status rc = ddci_validate_ddca_display_ref(ddca_dref, /* basic_only*/ true, /*require_not_asleep*/ false, &dref); DDCA_Status rc = ddci_validate_ddca_display_ref2(ddca_dref, DREF_VALIDATE_EDID, &dref); if (rc == 0) ddc_report_display_by_dref(dref, depth); API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, rc, ""); return rc; } DDCA_Status ddca_validate_display_ref(DDCA_Display_Ref ddca_dref, bool require_not_asleep) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dref = %p", ddca_dref); assert(library_initialized); Display_Ref * dref = NULL; DDCA_Status rc = DDCRC_ARG; if (ddca_dref) { // rc = ddci_validate_ddca_display_ref(ddca_dref, /* basic_only*/ false, require_not_asleep, &dref); Dref_Validation_Options opts = DREF_VALIDATE_EDID; if (require_not_asleep) opts |= DREF_VALIDATE_AWAKE; rc = ddci_validate_ddca_display_ref2(ddca_dref, opts, &dref); } #ifdef REDUNDANT Error_Info * errinfo = NULL; if (rc != 0) errinfo = ERRINFO_NEW(rc, ""); else { assert(sys_drm_connectors); if (!dref->drm_connector) { errinfo = ERRINFO_NEW(DDCRC_INTERNAL_ERROR, "dref->drm_connector == NULL"); } else { int d = (debug) ? 1 : -1; bool edid_exists = RPT_ATTR_EDID(d, NULL, "/sys/class/drm", dref->drm_connector, "edid"); if (!edid_exists) { errinfo = ERRINFO_NEW(DDCRC_DISCONNECTED, "/dev/i2c-%d", dref->io_path.path.i2c_busno); } else { if (dpms_check_drm_asleep_by_dref(dref)) errinfo = ERRINFO_NEW(DDCRC_DPMS_ASLEEP, "/dev/i2c-%d", dref->io_path.path.i2c_busno); } } } DDCA_Status ddcrc = ERRINFO_STATUS(errinfo); DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(errinfo); errinfo_free_with_report(errinfo, debug, __func__); save_thread_error_detail(public_error_detail); #endif API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, rc, ""); return rc; } // // Open and close display // #ifdef DEPRECATED /** \deprecated Use #ddca_open_display2() * Open a display * @param[in] ddca_dref display reference for display to open * @param[out] ddca_dh_loc where to return display handle * @return status code * * Fails if display is already opened by another thread. * \ingroup api_display_spec */ // __attribute__ ((deprecated ("use ddca_open_display2()"))) DDCA_Status ddca_open_display( DDCA_Display_Ref ddca_dref, DDCA_Display_Handle * ddca_dh_loc); DDCA_Status ddca_open_display( DDCA_Display_Ref ddca_dref, DDCA_Display_Handle * dh_loc) { return ddca_open_display2(ddca_dref, false, dh_loc); } #endif // unpublished extension /** Options for opening a DDCA_Display_Ref */ typedef enum { DDCA_OPENOPT_NONE = 0, DDCA_OPENOPT_WAIT = 1, DDCA_OPENOPT_FORCE_SLAVE_ADDR = 2 } DDCA_Open_Options; STATIC DDCA_Status ddca_open_display3( DDCA_Display_Ref ddca_dref, DDCA_Open_Options options, DDCA_Display_Handle * dh_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dref=%p, options=0x%02x, dh_loc=%p, on thread %d", ddca_dref, options, dh_loc, get_thread_id()); DBGTRC_NOPREFIX(debug, DDCA_TRC_API, "library_initialized=%s, ddc_displays_already_detected() = %ld", sbool(library_initialized), ddc_displays_already_detected()); TRACED_ASSERT(library_initialized); TRACED_ASSERT(ddc_displays_already_detected()); API_PRECOND_W_EPILOG(dh_loc); Display_Ref * dref = NULL; *dh_loc = NULL; // in case of error DDCA_Status rc = 0; Error_Info * err = NULL; Display_Ref * dref0 = dref_from_published_ddca_dref(ddca_dref); if (dref0) { // rc = ddci_validate_ddca_display_ref(ddca_dref, /* basic_only*/ false, /* require_not_asleep */ true, &dref); rc = ddci_validate_ddca_display_ref2(ddca_dref, DREF_VALIDATE_EDID | DREF_VALIDATE_AWAKE, &dref); if (!rc) { Display_Handle* dh = NULL; Call_Options callopts = CALLOPT_NONE; if (options & DDCA_OPENOPT_WAIT) callopts |= CALLOPT_WAIT; if (options & DDCA_OPENOPT_FORCE_SLAVE_ADDR) callopts |= CALLOPT_FORCE_SLAVE_ADDR; err = ddc_open_display(dref, callopts, &dh); if (!err) *dh_loc = dh; else { rc = err->status_code; char * detail2 = g_strdup_printf("%s, Internal display ref: %s", err->detail, dref_reprx_t(dref)); free(err->detail); err->detail = detail2; DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(err); errinfo_free_with_report(err, debug, __func__); save_thread_error_detail(public_error_detail); } } else { Error_Info * err = ERRINFO_NEW(DDCRC_INVALID_DISPLAY, "Invalid display ref"); DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(err); errinfo_free_with_report(err, debug, __func__); save_thread_error_detail(public_error_detail); } } else { Error_Info * err = ERRINFO_NEW(DDCRC_INVALID_DISPLAY, "Unknown display ref"); DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(err); errinfo_free_with_report(err, debug, __func__); save_thread_error_detail(public_error_detail); } API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, rc, "*dh_loc=%p -> %s", *dh_loc, dh_repr(*dh_loc)); TRACED_ASSERT_IFF(rc==0, *dh_loc); return rc; } DDCA_Status ddca_open_display2( DDCA_Display_Ref ddca_dref, bool wait, DDCA_Display_Handle * dh_loc) { return ddca_open_display3(ddca_dref, (wait) ? DDCA_OPENOPT_WAIT : DDCA_OPENOPT_NONE, dh_loc); } DDCA_Status ddca_close_display(DDCA_Display_Handle ddca_dh) { bool debug = false; free_thread_error_detail(); DDCA_Status rc = 0; Error_Info * err = NULL; Display_Handle * dh = (Display_Handle *) ddca_dh; API_PROLOGX(debug, RESPECT_QUIESCE, "dh = %s", dh_repr(dh)); if (dh) { if (memcmp(dh->marker, DISPLAY_HANDLE_MARKER, 4) != 0 ) { err = ERRINFO_NEW(DDCRC_ARG, "Invalid display handle"); } else { // TODO: ddc_close_display() needs an action if failure parm, err = ddc_close_display(dh); } } if (err) { rc = err->status_code; DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(err); errinfo_free_with_report(err, debug, __func__); save_thread_error_detail(public_error_detail); } API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, rc, ""); return rc; } // // Display Handle // const char * ddca_dh_repr(DDCA_Display_Handle ddca_dh) { char * repr = NULL; Display_Handle * dh = (Display_Handle *) ddca_dh; if (valid_display_handle(dh)) repr = dh_repr(dh); return repr; } DDCA_Display_Ref ddca_display_ref_from_handle( DDCA_Display_Handle ddca_dh) { DDCA_Display_Ref result = NULL; Display_Handle * dh = (Display_Handle *) ddca_dh; if (valid_display_handle(dh)) result = dh->dref; return result; } DDCA_Status ddca_get_mccs_version_by_dh( DDCA_Display_Handle ddca_dh, DDCA_MCCS_Version_Spec* p_spec) { bool debug = false; API_PROLOGX(debug, true, ""); free_thread_error_detail(); assert(library_initialized); DDCA_Status rc = 0; Display_Handle * dh = (Display_Handle *) ddca_dh; if (dh == NULL || memcmp(dh->marker, DISPLAY_HANDLE_MARKER, 4) != 0 ) { rc = DDCRC_ARG; p_spec->major = 0; p_spec->minor = 0; } else { // need to call function, may not yet be set DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); p_spec->major = vspec.major; p_spec->minor = vspec.minor; rc = 0; } API_EPILOG_BEFORE_RETURN(debug, true, rc, ""); return rc; } #ifdef NOT_PUBLISHED // not published DDCA_Status ddca_get_mccs_version_with_default( DDCA_Display_Handle ddca_dh, DDCA_MCCS_Version_Spec default_spec, DDCA_MCCS_Version_Spec* p_spec) { DDCA_Status rc = ddca_get_mccs_version_by_dh(ddca_dh, p_spec); if (rc == 0 && vcp_version_eq(*p_spec, DDCA_VSPEC_UNKNOWN)) *p_spec = default_spec; return rc; } #endif #ifdef MCCS_VERSION_ID // // DDCA_MCCS_Version_Id functions - Deprecated // DDCA_Status ddca_get_mccs_version_id( DDCA_Display_Handle ddca_dh, DDCA_MCCS_Version_Id* p_id) { DDCA_MCCS_Version_Spec vspec; DDCA_Status rc = ddca_get_mccs_version_by_dh(ddca_dh, &vspec); if (rc == 0) { DDCA_MCCS_Version_Id version_id = mccs_version_spec_to_id(vspec); *p_id = version_id; } else { *p_id = DDCA_MCCS_VNONE; } return rc; } char * ddca_mccs_version_id_name(DDCA_MCCS_Version_Id version_id) { return vcp_version_id_name(version_id); } #ifdef DEFINED_BUT_NOT_RELEASED /** Returns the descriptive name of a #DDCA_MCCS_Version_Id, * e.g. "2.0". * * @param[in] version_id version id value * @return descriptive name (do not free) * * @remark added to replace ddca_mccs_version_id_desc() during 0.9 * development, but then use of DDCA_MCCS_Version_Id deprecated */ char * ddca_mccs_version_id_string(DDCA_MCCS_Version_Id version_id) { return format_vcp_version_id(version_id); } #endif char * ddca_mccs_version_id_desc(DDCA_MCCS_Version_Id version_id) { return format_vcp_version_id(version_id); } #endif // // Monitor Model Identifier // #ifdef REMOVED const Monitor_Model_Key UNDEFINED_MONITOR_MODEL_KEY = {{0}}; Monitor_Model_Key ddca_mmk( const char * mfg_id, const char * model_name, uint16_t product_code) { Monitor_Model_Key result = UNDEFINED_MONITOR_MODEL_KEY; if (mfg_id && strlen(mfg_id) < DDCA_EDID_MFG_ID_FIELD_SIZE && model_name && strlen(model_name) < DDCA_EDID_MODEL_NAME_FIELD_SIZE) { result = monitor_model_key_value(mfg_id, model_name, product_code); } return result; } bool ddca_mmk_eq( Monitor_Model_Key mmk1, Monitor_Model_Key mmk2) { return monitor_model_key_eq(mmk1, mmk2); } bool ddca_mmk_is_defined( Monitor_Model_Key mmk) { return mmk.defined; } Monitor_Model_Key ddca_mmk_from_dref( DDCA_Display_Ref ddca_dref) { Monitor_Model_Key result = UNDEFINED_MONITOR_MODEL_KEY; Display_Ref * dref = (Display_Ref *) ddca_dref; if (valid_display_ref(dref) && dref->mmid) result = *dref->mmid; return result; } Monitor_Model_Key ddca_mmk_from_dh( DDCA_Display_Handle ddca_dh) { Monitor_Model_Key result = UNDEFINED_MONITOR_MODEL_KEY; Display_Handle * dh = (Display_Handle *) ddca_dh; if (valid_display_handle(dh) && dh->dref->mmid) result = *dh->dref->mmid; return result; } #endif // // Display Info // #ifdef DEPRECATED /** @deprecated use #ddca_get_display_info_list2() * Gets a list of the detected displays. * * Displays that do not support DDC are not included. * * @return list of display summaries */ __attribute__ ((deprecated ("use ddca_get_display_info_list2()"))) DDCA_Display_Info_List * ddca_get_display_info_list(void) { DDCA_Display_Info_List * result = NULL; ddca_get_display_info_list2(false, &result); return result; } #endif STATIC void ddci_init_display_info(Display_Ref * dref, DDCA_Display_Info * curinfo) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, "dref=%s, curinfo=%p", dref_reprx_t(dref),curinfo); memcpy(curinfo->marker, DDCA_DISPLAY_INFO_MARKER, 4); curinfo->dispno = dref->dispno; curinfo->path = dref->io_path; if (dref->io_path.io_mode == DDCA_IO_USB) { curinfo->usb_bus = dref->usb_bus; curinfo->usb_device = dref->usb_device; } DDCA_MCCS_Version_Spec vspec = DDCA_VSPEC_UNKNOWN; if (dref->dispno > 0 && (dref->flags&DREF_DDC_COMMUNICATION_WORKING)) { vspec = get_vcp_version_by_dref(dref); } memcpy(curinfo->edid_bytes, dref->pedid->bytes, 128); #if __GNUC__ >= 8 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstringop-truncation" STRLCPY(curinfo->mfg_id, dref->pedid->mfg_id, EDID_MFG_ID_FIELD_SIZE); STRLCPY(curinfo->model_name, dref->pedid->model_name, EDID_MODEL_NAME_FIELD_SIZE); STRLCPY(curinfo->sn, dref->pedid->serial_ascii, DDCA_EDID_SN_ASCII_FIELD_SIZE); #pragma GCC diagnostic pop #else STRLCPY(curinfo->mfg_id, dref->pedid->mfg_id, EDID_MFG_ID_FIELD_SIZE); STRLCPY(curinfo->model_name, dref->pedid->model_name, EDID_MODEL_NAME_FIELD_SIZE); STRLCPY(curinfo->sn, dref->pedid->serial_ascii, DDCA_EDID_SN_ASCII_FIELD_SIZE); #endif curinfo->product_code = dref->pedid->product_code; curinfo->vcp_version = vspec; curinfo->dref = dref_to_ddca_dref(dref); #ifdef MMID curinfo->mmid = monitor_model_key_value( dref->pedid->mfg_id, dref->pedid->model_name, dref->pedid->product_code); // #ifdef OLD assert(streq(curinfo->mfg_id, curinfo->mmid.mfg_id)); assert(streq(curinfo->model_name, curinfo->mmid.model_name)); assert(curinfo->product_code == curinfo->mmid.product_code); // #endif #endif DBGTRC_DONE(debug, DDCA_TRC_API, "dref=%s", dref_reprx_t(dref)); } DDCA_Status ddca_get_display_info( DDCA_Display_Ref ddca_dref, DDCA_Display_Info ** dinfo_loc) { bool debug = false; Display_Ref * dref0 = dref_from_published_ddca_dref(ddca_dref); // causes return DDCRC_UNINTIALIZED: called after explicit ddca_init()/init2() call failed API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dref=%p, dref0=%s", ddca_dref, dref_reprx_t(dref0)); // causes return DDCRC_ARG if dinfo_loc == NULL API_PRECOND_W_EPILOG(dinfo_loc); DDCA_Status ddcrc = 0; // if ddc_validate_display_ref() fails, returns its status code WITH_VALIDATED_DR4( ddca_dref, ddcrc, DREF_VALIDATE_EDID | DREF_VALIDATE_DDC_COMMUNICATION_FAILURE_OK, { DDCA_Display_Info * info = calloc(1, sizeof(DDCA_Display_Info)); ddci_init_display_info(dref, info); *dinfo_loc = info; } ) API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, ddcrc, "ddca_dref=%p, dref=%s", ddca_dref, dref_reprx_t(dref0)); return ddcrc; } STATIC void set_ddca_error_detail_from_open_errors() { bool debug = false; GPtrArray * errs = ddc_get_bus_open_errors(); // DDCA_Status master_rc = 0; if (errs && errs->len > 0) { Error_Info * master_error = ERRINFO_NEW(DDCRC_OTHER, "Error(s) opening ddc devices"); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Error(s) opening ddc devices"); for (int ndx = 0; ndx < errs->len; ndx++) { Bus_Open_Error * cur = g_ptr_array_index(errs, ndx); Error_Info * errinfo = NULL; if (cur->io_mode == DDCA_IO_I2C) { errinfo = ERRINFO_NEW(cur->error, "Error %s opening /dev/i2c-%d", psc_desc(cur->error), cur->devno); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Error %s opening /dev/i2c-%d", psc_desc(cur->error), cur->devno); } else { errinfo = ERRINFO_NEW(cur->error, "Error %s opening /dev/usb/hiddev%d %s", psc_desc(cur->error), cur->devno, (cur->detail) ? cur->detail : ""); MSG_W_SYSLOG(DDCA_SYSLOG_ERROR, "Error %s opening /dev/usb/hiddev%d %s", psc_desc(cur->error), cur->devno, (cur->detail) ? cur->detail : ""); } errinfo_add_cause(master_error, errinfo); } // master_rc = master_error->status_code; DDCA_Error_Detail * public_error_detail = error_info_to_ddca_detail(master_error); errinfo_free_with_report(master_error, debug, __func__); save_thread_error_detail(public_error_detail); } // return master_rc; } DDCA_Status ddca_get_display_refs( bool include_invalid_displays, DDCA_Display_Ref** drefs_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "include_invalid_displays=%s", SBOOL(include_invalid_displays)); API_PRECOND_W_EPILOG(drefs_loc); int dref_ct = 0; DDCA_Status ddcrc = 0; ddc_ensure_displays_detected(); GPtrArray * filtered_displays = ddc_get_filtered_display_refs( include_invalid_displays, false); // include_removed_drefs DDCA_Display_Ref * result_list = calloc(filtered_displays->len + 1,sizeof(DDCA_Display_Ref)); DDCA_Display_Ref * cur_ddca_dref = result_list; for (int ndx = 0; ndx < filtered_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(filtered_displays, ndx); *cur_ddca_dref = dref_to_ddca_dref(dref); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "%p -> %p", cur_ddca_dref, *cur_ddca_dref); add_published_dref_id_by_dref(dref); cur_ddca_dref++; } *cur_ddca_dref = NULL; // terminating NULL ptr, redundant since calloc() dref_ct = filtered_displays->len; g_ptr_array_free(filtered_displays, true); if (IS_DBGTRC(debug, DDCA_TRC_API|DDCA_TRC_DDC )) { DBGMSG(" *drefs_loc=%p", drefs_loc); DDCA_Display_Ref * cur_ddca_dref = result_list; while (*cur_ddca_dref) { Display_Ref * dref = dref_from_published_ddca_dref(*cur_ddca_dref); DBGMSG(" DDCA_Display_Ref %p -> display %d", *cur_ddca_dref, dref->dispno); cur_ddca_dref++; } dbgrpt_published_dref_hash(__func__, 1); } *drefs_loc = result_list; assert(*drefs_loc); set_ddca_error_detail_from_open_errors(); ddcrc = 0; API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, ddcrc, "*drefs_loc=%p, returned list has %d displays", *drefs_loc, dref_ct); } DDCA_Status ddca_get_display_info_list2( bool include_invalid_displays, DDCA_Display_Info_List** dlist_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, ""); int filtered_ct = 0; API_PRECOND_W_EPILOG(dlist_loc); DDCA_Status ddcrc = 0; ddc_ensure_displays_detected(); GPtrArray * filtered_displays = ddc_get_filtered_display_refs( include_invalid_displays, false); // include_removed_drefs filtered_ct = filtered_displays->len; int reqd_size = offsetof(DDCA_Display_Info_List,info) + filtered_ct * sizeof(DDCA_Display_Info); DBGMSF(debug, "reqd_size=%d", reqd_size); DDCA_Display_Info_List * result_list = calloc(1,reqd_size); result_list->ct = filtered_ct; DBGMSF(debug, "sizeof(DDCA_Display_Info) = %zu," " sizeof(Display_Info_List) = %zu, reqd_size=%d, filtered_ct=%d, offsetof(DDCA_Display_Info_List,info) = %zu", sizeof(DDCA_Display_Info), sizeof(DDCA_Display_Info_List), reqd_size, filtered_ct, offsetof(DDCA_Display_Info_List,info)); DDCA_Display_Info * curinfo = &result_list->info[0]; for (int ndx = 0; ndx < filtered_displays->len; ndx++) { Display_Ref * dref = g_ptr_array_index(filtered_displays, ndx); // DDCA_Display_Info * curinfo = &result_list->info[ndx++]; DBGMSF(debug, "dref=%p, curinfo=%p", dref, curinfo); ddci_init_display_info(dref, curinfo); add_published_dref_id_by_dref(dref); curinfo++; } g_ptr_array_free(filtered_displays, true); if (IS_DBGTRC(debug, DDCA_TRC_API|DDCA_TRC_DDC )) { DBGMSG("Final result list %p", result_list); dbgrpt_display_info_list(result_list, 2); dbgrpt_published_dref_hash(__func__, 1); } set_ddca_error_detail_from_open_errors(); ddcrc = 0; *dlist_loc = result_list; assert(*dlist_loc); API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, ddcrc, "Returned list has %d displays", filtered_ct); } void ddca_free_display_info(DDCA_Display_Info * info_rec) { bool debug = false; API_PROLOG(debug, "info_rec->%p", info_rec); // DDCA_Display_Info contains no pointers, can simply be free'd // data structures. Nothing to free. if (info_rec && memcmp(info_rec->marker, DDCA_DISPLAY_INFO_MARKER, 4) == 0) { info_rec->marker[3] = 'x'; free(info_rec); } API_EPILOG_NO_RETURN(debug, false, ""); // DBGTRC_DONE(debug, DDCA_TRC_API,""); DISABLE_API_CALL_TRACING(); } void ddca_free_display_info_list(DDCA_Display_Info_List * dlist) { bool debug = false; API_PROLOG_NO_DISPLAY_IO(debug, "dlist=%p", dlist); if (dlist) { // n. DDCA_Display_Info contains no pointers, // DDCA_Display_Info_List can simply be free'd. for (int ndx = 0; ndx < dlist->ct; ndx++) { DDCA_Display_Info * info_rec = &dlist->info[ndx]; if (memcmp(info_rec->marker, DDCA_DISPLAY_INFO_MARKER, 4) == 0) info_rec->marker[3] = 'x'; } free(dlist); } API_EPILOG_NO_RETURN(debug, false, ""); // DBGTRC_DONE(debug, DDCA_TRC_API, ""); DISABLE_API_CALL_TRACING(); } DDCA_Status ddca_report_display_info( DDCA_Display_Info * dinfo, int depth) { bool debug = false; API_PROLOGX(debug, NORESPECT_QUIESCE, "dinfo=%p, dinfo->dispno=%d, depth=%d", dinfo, dinfo->dispno, depth); DDCA_Status rc = 0; API_PRECOND_W_EPILOG(dinfo); API_PRECOND_W_EPILOG(memcmp(dinfo->marker, DDCA_DISPLAY_INFO_MARKER, 4) == 0); if (rc == 0) { int d0 = depth; int d1 = depth+1; int d2 = depth+2; if (dinfo->dispno > 0) rpt_vstring(d0, "Display number: %d", dinfo->dispno); else if (dinfo->dispno == DISPNO_BUSY) rpt_vstring(d0, "Busy display - Cannot communicate DDC"); else rpt_label( d0, "Invalid display - Does not support DDC"); // rpt_vstring( d1, "Display ref: %p -> %s", dinfo->dref, dref_repr_t(dinfo->dref) ); // rpt_vstring(d1, "IO mode: %s", io_mode_name(dinfo->path.io_mode)); switch(dinfo->path.io_mode) { case (DDCA_IO_I2C): rpt_vstring(d1, "I2C bus: /dev/i2c-%d", dinfo->path.path.i2c_busno); break; case (DDCA_IO_USB): rpt_vstring(d1, "USB bus.device: %d.%d", dinfo->usb_bus, dinfo->usb_device); rpt_vstring(d1, "USB hiddev device: /dev/usb/hiddev%d", dinfo->path.path.hiddev_devno); break; } // workaround, including drm_connector in DDCA_Display_Info would break API Display_Ref * dref = dref_from_published_ddca_dref(dinfo->dref); if (dref) { // should never fail, but just in case if (dref->drm_connector_id > 0) // rpt_vstring(d1, "DRM connector id: %d", dref->drm_connector_id); rpt_vstring(d1, "DRM connector: %s (id: %d)", dref->drm_connector, dref->drm_connector_id); else rpt_vstring(d1, "DRM connector: %s", dref->drm_connector); } rpt_vstring(d1, "Mfg Id: %s", dinfo->mfg_id); rpt_vstring(d1, "Model: %s", dinfo->model_name); rpt_vstring(d1, "Product code: %u", dinfo->product_code); rpt_vstring(d1, "Serial number: %s", dinfo->sn); // binary SN is not part of DDCA_Display_Info Parsed_Edid * edid = create_parsed_edid(dinfo->edid_bytes); if (edid) { // should never fail, but being ultra-cautious // Binary serial number is typically 0x00000000 or 0x01010101, but occasionally // useful for differentiating displays that share a generic ASCII "serial number" rpt_vstring(d1,"Binary serial number: %"PRIu32" (0x%08x)", edid->serial_binary, edid->serial_binary); free_parsed_edid(edid); } #ifdef NOT_WORKING if (dinfo->path.io_mode == DDCA_IO_I2C) { I2C_Sys_Info * info = get_i2c_sys_info(dinfo->path.path.i2c_busno, -1); rpt_vstring(d1, "DRM Connector: %s", (info->connector) ? info->connector : ""); } #endif // rpt_label( d1, "Monitor Model Id:"); // rpt_vstring(d2, "Mfg Id: %s", dinfo->mmid.mfg_id); // rpt_vstring(d2, "Model name: %s", dinfo->mmid.model_name); // rpt_vstring(d2, "Product code: %d", dinfo->mmid.product_code); rpt_vstring(d1, "EDID:"); GPtrArray * edid_lines = g_ptr_array_new_with_free_func(g_free); hex_dump_indented_collect(edid_lines, dinfo->edid_bytes, 128, 0); for (int ndx = 0; ndx < edid_lines->len; ndx++) { rpt_vstring(d2, "%s", (char *) g_ptr_array_index(edid_lines, ndx)); } g_ptr_array_free(edid_lines, true); // OLD: rpt_hex_dump(dinfo->edid_bytes, 128, d2); // rpt_vstring(d1, "dref: %p", dinfo->dref); rpt_vstring(d1, "VCP Version: %s", format_vspec(dinfo->vcp_version)); // rpt_vstring(d1, "VCP Version Id: %s", format_vcp_version_id(dinfo->vcp_version_id) ); if (dinfo->dispno == DISPNO_BUSY) { #ifdef OLD rpt_nl(); char fn[20]; int busno = dinfo->path.path.i2c_busno; g_snprintf(fn, 20, "/dev/bus/ddcci/%d", busno); struct stat statrec; if (stat(fn, &statrec) == 0 ) rpt_vstring(d1, "Driver ddcci is hogging I2C slave address x37 (DDC) on /dev/i2c-%d", busno); #endif Display_Ref * dref = (Display_Ref *) dinfo->dref; int busno = dref->io_path.path.i2c_busno; GPtrArray * conflicts = collect_conflicting_drivers(busno, -1); if (conflicts && conflicts->len > 0) { rpt_vstring(d1, "I2C bus is busy. Likely conflicting driver(s): %s", conflicting_driver_names_string_t(conflicts)); free_conflicting_drivers(conflicts); } else { struct stat stat_buf; char buf[20]; g_snprintf(buf, 20, "/dev/bus/ddcci/%d", busno); // DBGMSG("buf: %s", buf); int rc = stat(buf, &stat_buf); // DBGMSG("stat returned %d", rc); if (rc == 0) rpt_label(d1, "I2C bus is busy. Likely conflict with driver ddcci."); } rpt_vstring(d1, "Consider using option --force-slave-address."); } } API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, rc, ""); } STATIC void dbgrpt_display_info( DDCA_Display_Info * dinfo, int depth) { bool debug = false; DBGMSF(debug, "Starting. dinfo=%p"); ddca_report_display_info(dinfo, depth); int d1 = depth+1; rpt_vstring(d1, "dref: %s", dref_repr_t(dinfo->dref)); if (dinfo->dref) { // paranoid, should never be NULL rpt_vstring(d1, "VCP Version (dref xdf): %s", format_vspec_verbose(((Display_Ref*)dinfo->dref)->vcp_version_xdf)); } DBGMSF(debug, "Done."); } void ddca_report_display_info_list( DDCA_Display_Info_List * dlist, int depth) { bool debug = false; API_PROLOG_NO_DISPLAY_IO(debug, ""); DBGMSF(debug, "Starting. dlist=%p, depth=%d", dlist, depth); int d1 = depth+1; rpt_vstring(depth, "Found %d displays", dlist->ct); for (int ndx=0; ndxct; ndx++) { ddca_report_display_info(&dlist->info[ndx], d1); } API_EPILOG_NO_RETURN(debug, false, ""); } STATIC void dbgrpt_display_info_list( DDCA_Display_Info_List * dlist, int depth) { bool debug = false; DBGMSF(debug, "Starting. dlist=%p, depth=%d", dlist, depth); int d1 = depth+1; rpt_vstring(depth, "Found %d displays", dlist->ct); for (int ndx=0; ndxct; ndx++) { dbgrpt_display_info(&dlist->info[ndx], d1); } DBGMSF(debug, "Done."); } // // Miscellaneous // #ifdef DEPRECATED // /** \deprecated */ __attribute__ ((deprecated)) DDCA_Status ddca_get_edid_by_dref( DDCA_Display_Ref ddca_dref, uint8_t ** pbytes_loc); // pointer into ddcutil data structures, do not free // deprecated DDCA_Status ddca_get_edid_by_dref( DDCA_Display_Ref ddca_dref, uint8_t** p_bytes) { DDCA_Status rc = 0; *p_bytes = NULL; free_thread_error_detail(); assert(library_initialized); Display_Ref * dref = (Display_Ref *) ddca_dref; // if (dref == NULL || memcmp(dref->marker, DISPLAY_REF_MARKER, 4) != 0 ) { if ( !valid_display_ref(dref) ) { rc = DDCRC_ARG; goto bye; } // Parsed_Edid* edid = ddc_get_parsed_edid_by_dref(dref); Parsed_Edid * edid = dref->pedid; assert(edid); *p_bytes = edid->bytes; bye: return rc; } #endif #ifdef UNIMPLEMENTED // Use ddca_get_edid_by_dref() instead // n. edid_buffer must be >= 128 bytes DDCA_Status ddca_get_edid(DDCA_Display_Handle * dh, uint8_t* edid_buffer); #endif // // Reports // #ifdef DEPRECATED /** \deprecated use #ddca_report_displays() * Reports on all active displays. * This function hooks into the code used by command "ddcutil detect" * * @param[in] depth logical indentation depth * @return number of MCCS capable displays */ __attribute__ ((deprecated ("use ddca_report_displays()"))) int ddca_report_active_displays( int depth); // deprecated, use ddca_report_displays() int ddca_report_active_displays(int depth) { bool debug = false; API_PROLOG(debug, ""); int display_ct = ddc_report_displays(false, depth); DBGTRC_DONE(debug, DDCA_TRC_API, "Returning %d", display_ct); DISABLE_API_CALL_TRACING(); return display_ct; } #endif // TODO: deprecate, does not respect quiesced int ddca_report_displays(bool include_invalid_displays, int depth) { bool debug = false; API_PROLOG(debug, ""); int display_ct = 0; if (!library_initialization_failed) { display_ct = ddc_report_displays(include_invalid_displays, depth); } DBGTRC_NOPREFIX(debug, DDCA_TRC_API, "Returning: %d", display_ct); DISABLE_API_CALL_TRACING(); API_EPILOG_NO_RETURN(debug, false, ""); // hack return display_ct; } #ifdef DETAILED_DISPLAY_CHANGE_HANDLING typedef enum { DDCA_DISPLAY_ADDED = 0, DDCA_DISPLAY_REMOVED = 1, } DDCA_Display_Detection_Op; typedef struct { DDCA_Display_Ref dref; DDCA_Display_Detection_Op operation; } DDCA_Display_Detection_Report; typedef void (*DDCA_Display_Status_Callback_Func)(DDCA_Display_Detection_Report); DDCA_Status ddca_register_display_status_callback(DDCA_Display_Status_Callback_Func func); #endif // // Display Status Change Communication // DDCA_Status ddca_register_display_status_callback(DDCA_Display_Status_Callback_Func func) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "func=%p", func); DDCA_Status result = DDCRC_INVALID_OPERATION; #ifdef ENABLE_UDEV if (check_all_video_adapters_implement_drm()) result = dw_register_display_status_callback(func); #endif API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, result, "func=%p", func); return result; } DDCA_Status ddca_unregister_display_status_callback(DDCA_Display_Status_Callback_Func func) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "func=%p", func); DDCA_Status result = dw_unregister_display_status_callback(func); API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, result, "func=%p", func); return result; } const char * ddca_display_event_type_name(DDCA_Display_Event_Type event_type) { return dw_display_event_type_name(event_type); } // // Sleep Multiplier Control // DDCA_Status ddca_set_display_sleep_multiplier( DDCA_Display_Ref ddca_dref, DDCA_Sleep_Multiplier multiplier) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dref=%p", ddca_dref); assert(library_initialized); Display_Ref * dref = NULL; //DDCA_Status rc = ddci_validate_ddca_display_ref(ddca_dref, /* basic_only*/ true, /*require_not_asleep*/false, &dref); DDCA_Status rc = ddci_validate_ddca_display_ref2(ddca_dref, DREF_VALIDATE_EDID, &dref); if (rc == 0) { Per_Display_Data * pdd = dref->pdd; if (multiplier >= 0.0 && multiplier <= 10.0) { pdd_reset_multiplier(pdd, multiplier); } else rc = DDCRC_ARG; } API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, rc, ""); return rc; } DDCA_Status ddca_get_current_display_sleep_multiplier( DDCA_Display_Ref ddca_dref, DDCA_Sleep_Multiplier* multiplier_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, NORESPECT_QUIESCE, "ddca_dref=%p", ddca_dref); assert(library_initialized); Display_Ref * dref = NULL; // DDCA_Status rc = ddci_validate_ddca_display_ref(ddca_dref, true, false, &dref); DDCA_Status rc = ddci_validate_ddca_display_ref2(ddca_dref, DREF_VALIDATE_EDID, &dref); if (rc == 0) { Per_Display_Data * pdd = dref->pdd; *multiplier_loc = pdd->final_successful_adjusted_sleep_multiplier; } API_EPILOG_BEFORE_RETURN(debug, NORESPECT_QUIESCE, rc, ""); return rc; } bool ddca_enable_dynamic_sleep(bool onoff) { bool debug = false; API_PROLOG(debug, ""); free_thread_error_detail(); bool old = pdd_is_dynamic_sleep_enabled(); pdd_enable_dynamic_sleep_all(onoff); API_EPILOG_NO_RETURN(debug, false, "Returning %s", sbool(old)); return old; } bool ddca_is_dynamic_sleep_enabled() { bool debug = false; API_PROLOG(debug, ""); free_thread_error_detail(); bool result = pdd_is_dynamic_sleep_enabled(); API_EPILOG_NO_RETURN(debug, false, "Returning %s", sbool(result)); return result; } // // Module initialization // void init_api_displays() { RTTI_ADD_FUNC(ddca_close_display); RTTI_ADD_FUNC(ddca_get_display_info_list2); RTTI_ADD_FUNC(ddca_get_display_info); RTTI_ADD_FUNC(ddca_get_display_ref); RTTI_ADD_FUNC(ddca_get_display_refs); RTTI_ADD_FUNC(ddca_open_display2); RTTI_ADD_FUNC(ddca_open_display3); RTTI_ADD_FUNC(ddca_redetect_displays); RTTI_ADD_FUNC(ddca_report_display_by_dref); RTTI_ADD_FUNC(ddca_register_display_status_callback); RTTI_ADD_FUNC(ddca_unregister_display_status_callback); RTTI_ADD_FUNC(ddci_init_display_info); #ifdef OLD RTTI_ADD_FUNC(ddci_validate_ddca_display_ref); #endif RTTI_ADD_FUNC(ddci_validate_ddca_display_ref2); RTTI_ADD_FUNC(ddca_validate_display_ref); } ddcutil-2.2.0/src/libmain/api_error_info_internal.c0000644000175000001440000001277414754153540016102 /** @file api_error_info_internal.c */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "ddcutil_types.h" #include "util/error_info.h" #include "util/report_util.h" #include "base/core.h" #include "base/ddc_errno.h" #include "libmain/api_error_info_internal.h" // // DDCA_Error_Detail related functions // /** Frees a #DDCA_Error_Detail instance * * @param instance to free */ void free_error_detail(DDCA_Error_Detail * ddca_erec) { if (ddca_erec) { assert(memcmp(ddca_erec->marker, DDCA_ERROR_DETAIL_MARKER, 4) == 0); for (int ndx = 0; ndx < ddca_erec->cause_ct; ndx++) { free_error_detail(ddca_erec->causes[ndx]); } free(ddca_erec->detail); ddca_erec->marker[3] = 'x'; free(ddca_erec); } } /** Creates a new #DDCA_Error_Detail record with a given status code and * error detail string, but no causes. * * @param ddcrc status code * @param format format string for detail * @param ... arguments for detail * @return new #DDCA_Error_Detail record */ DDCA_Error_Detail * new_ddca_error_detail(DDCA_Status ddcrc, const char * format, ...) { DDCA_Error_Detail * errdet = calloc(1, sizeof(DDCA_Error_Detail)); memcpy(errdet->marker, DDCA_ERROR_DETAIL_MARKER, 4); errdet->status_code = ddcrc; va_list(args); va_start(args, format); // if (debug) // printf("(%s) &args=%p, args=%p\n", __func__, &args, args); errdet->detail = g_strdup_vprintf(format, args); va_end(args); return errdet; } /** Converts an internal #Error_Info instance to a publicly visible #DDCA_Error_Detail * * @param erec instance to convert * @return new #DDCA_Error_Detail instance */ DDCA_Error_Detail * error_info_to_ddca_detail(Error_Info * erec) { bool debug = false; DBGMSF(debug, "Starting. erec=%p", erec); if (debug && erec) errinfo_report(erec, 2); DDCA_Error_Detail * result = NULL; if (erec) { // ??? int reqd_size = sizeof(DDCA_Error_Detail) + erec->cause_ct * sizeof(DDCA_Error_Detail*); result = calloc(1, reqd_size); memcpy(result->marker, DDCA_ERROR_DETAIL_MARKER, 4); result->status_code = erec->status_code; if (erec->detail) result->detail = strdup(erec->detail); for (int ndx = 0; ndx < erec->cause_ct; ndx++) { DDCA_Error_Detail * cause = error_info_to_ddca_detail(erec->causes[ndx]); result->causes[ndx] = cause; } result->cause_ct = erec->cause_ct; } DBGMSF(debug, "Done. Returning: %p", result); if (debug) report_error_detail(result, 2); return result; } /** Makes a deep copy of a #DDC_Error_Detail instance. * * @param old instance to copy * @return new copy */ DDCA_Error_Detail * dup_error_detail(DDCA_Error_Detail * old) { bool debug = false; DBGMSF(debug, "Starting. old=%p", old); if (debug) report_error_detail(old, 2); DDCA_Error_Detail * result = NULL; if (old) { // ??? int reqd_size = sizeof(DDCA_Error_Detail) + old->cause_ct * sizeof(DDCA_Error_Detail*); result = calloc(1, reqd_size); memcpy(result->marker, DDCA_ERROR_DETAIL_MARKER, 4); result->status_code = old->status_code; if (old->detail) result->detail = g_strdup(old->detail); for (int ndx = 0; ndx < old->cause_ct; ndx++) { DDCA_Error_Detail * cause = dup_error_detail(old->causes[ndx]); result->causes[ndx] = cause; } result->cause_ct = old->cause_ct; } DBGMSF(debug, "Done. Returning: %p", result); if (debug) report_error_detail(result, 2); return result; } /** Emits a detailed report of a #DDCA_Error_Detail struct. * Output is written to the current report output destination. * * @param ddca_erec instance to report * @param depth logical indentation depth */ void report_error_detail(DDCA_Error_Detail * ddca_erec, int depth) { if (ddca_erec) { rpt_vstring(depth, "status_code=%s, detail=%s", ddcrc_desc_t(ddca_erec->status_code), ddca_erec->detail); if (ddca_erec->cause_ct > 0) { rpt_label(depth,"Caused by: "); for (int ndx = 0; ndx < ddca_erec->cause_ct; ndx++) { struct ddca_error_detail * cause = ddca_erec->causes[ndx]; report_error_detail(cause, depth+1); } } } } // Thread-specific functions /** Frees the #DDCA_Error_Detail (if any) for the current thread. */ void free_thread_error_detail() { Thread_Output_Settings * settings = get_thread_settings(); if (settings->error_detail) { free_error_detail(settings->error_detail); settings->error_detail = NULL; } } /** Gets the #DDCA_Error_Detail record for the current thread * * @return #DDCA_Error_Detail instance, NULL if none */ DDCA_Error_Detail * get_thread_error_detail() { Thread_Output_Settings * settings = get_thread_settings(); return settings->error_detail; } /** Set the #DDCA_Error_Detail record for the current thread. * * @param error_detail #DDCA_Error_Detail record to set */ void save_thread_error_detail(DDCA_Error_Detail * error_detail) { bool debug = false; DBGMSF(debug, "Starting. error_detail=%p", error_detail); if (debug) report_error_detail(error_detail, 2); Thread_Output_Settings * settings = get_thread_settings(); if (settings->error_detail) free_error_detail(settings->error_detail); settings->error_detail = error_detail; DBGMSF(debug, "Done"); } ddcutil-2.2.0/src/libmain/api_metadata.c0000644000175000001440000007562514754153540013626 // api_metadata.c // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include "public/ddcutil_status_codes.h" #include "public/ddcutil_c_api.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/displays.h" #include "base/feature_lists.h" #include "base/feature_set_ref.h" #include "base/monitor_model_key.h" #include "base/rtti.h" #include "vcp/vcp_feature_codes.h" #include "ddc/ddc_vcp_version.h" #include "dynvcp/dyn_feature_codes.h" #include "dynvcp/dyn_feature_files.h" #include "dynvcp/dyn_feature_set.h" #include "libmain/api_error_info_internal.h" #include "libmain/api_base_internal.h" #include "libmain/api_displays_internal.h" #include "libmain/api_metadata_internal.h" // // Feature Lists // // TODO: Move most functions into directory src/base // static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_API; const DDCA_Feature_List DDCA_EMPTY_FEATURE_LIST = {{0}}; void ddca_feature_list_clear(DDCA_Feature_List* vcplist) { feature_list_clear(vcplist); } DDCA_Feature_List ddca_feature_list_add(DDCA_Feature_List * vcplist, uint8_t vcp_code) { feature_list_add(vcplist, vcp_code); return *vcplist; } bool ddca_feature_list_contains(DDCA_Feature_List vcplist, uint8_t vcp_code) { return feature_list_contains(&vcplist, vcp_code); } const char * ddca_feature_list_id_name( DDCA_Feature_Subset_Id feature_subset_id) { char * result = NULL; switch (feature_subset_id) { case DDCA_SUBSET_KNOWN: result = "DDCA_SUBSET_KNOWN"; break; case DDCA_SUBSET_COLOR: result = "DDCA_SUBSET_COLOR"; break; case DDCA_SUBSET_PROFILE: result = "DDCA_SUBSET_PROFILE"; break; case DDCA_SUBSET_MFG: result = "DDCA_SUBSET_MFG"; break; case DDCA_SUBSET_UNSET: result = "DDCA_SUBSET_NONE"; break; case DDCA_SUBSET_CAPABILITIES: result = "DDCA_SUBSET_CAPABILITIES"; // ??? break; case DDCA_SUBSET_SCAN: result = "DDCA_SUBSET_SCAN"; break; case DDCA_SUBSET_CUSTOM: result = "DDCA_SUBSET_CUSTOM"; // or VCP_SUBSET_NONE? break; } return result; } #ifdef NEVER_PUBLISHED DDCA_Status ddca_get_feature_list( DDCA_Feature_Subset_Id feature_subset_id, DDCA_MCCS_Version_Spec vspec, bool include_table_features, DDCA_Feature_List* p_feature_list) // location to fill in { bool debug = false; DBGMSF(debug, "Starting. feature_subset_id=%d, vcp_version=%d.%d, include_table_features=%s, p_feature_list=%p", feature_subset_id, vspec.major, vspec.minor, sbool(include_table_features), p_feature_list); DDCA_Status ddcrc = 0; // Whether a feature is a table feature can vary by version, so can't // specify VCP_SPEC_ANY to request feature ids in any version if (!vcp_version_is_valid(vspec, /* allow unknown */ false)) { ddcrc = -EINVAL; ddca_feature_list_clear(p_feature_list); goto bye; } VCP_Feature_Subset subset = VCP_SUBSET_NONE; // pointless initialization to avoid compile warning switch (feature_subset_id) { case DDCA_SUBSET_KNOWN: subset = VCP_SUBSET_KNOWN; break; case DDCA_SUBSET_COLOR: subset = VCP_SUBSET_COLOR; break; case DDCA_SUBSET_PROFILE: subset = VCP_SUBSET_PROFILE; break; case DDCA_SUBSET_MFG: subset = VCP_SUBSET_MFG; break; case DDCA_SUBSET_UNSET: subset = VCP_SUBSET_NONE; break; } Feature_Set_Flags feature_flags = 0x00; if (!include_table_features) feature_flags |= FSF_NOTABLE; VCP_Feature_Set fset = create_feature_set(subset, vspec, feature_flags); // VCP_Feature_Set fset = create_feature_set(subset, vspec, !include_table_features); // TODO: function variant that takes result location as a parm, avoid memcpy DDCA_Feature_List result = feature_list_from_feature_set(fset); memcpy(p_feature_list, &result, 32); free_vcp_feature_set(fset); #ifdef NO DBGMSG("feature_subset_id=%d, vspec=%s, returning:", feature_subset_id, format_vspec(vspec)); rpt_hex_dump(result.bytes, 32, 1); for (int ndx = 0; ndx <= 255; ndx++) { uint8_t code = (uint8_t) ndx; if (ddca_feature_list_test(&result, code)) printf("%02x ", code); } printf("\n"); #endif bye: DBGMSF(debug, "Done. Returning: %s", psc_desc(ddcrc)); if (debug) rpt_hex_dump((Byte*) p_feature_list, 32, 1); return ddcrc; } #endif DDCA_Feature_List feature_list_from_dyn_feature_set(Dyn_Feature_Set * fset) { bool debug = false; if (debug || IS_TRACING()) { DBGMSG("Starting. feature_set = %p -> %s", (void*)fset, feature_subset_name(fset->subset)); // show_backtrace(2); dbgrpt_dyn_feature_set(fset, false, 1); } DDCA_Feature_List vcplist = {{0}}; assert( fset && memcmp(fset->marker, DYN_FEATURE_SET_MARKER, 4) == 0); int ndx = 0; for (; ndx < fset->members_dfm->len; ndx++) { Display_Feature_Metadata * vcp_entry = g_ptr_array_index(fset->members_dfm,ndx); feature_list_add(&vcplist, vcp_entry->feature_code); #ifdef OLD uint8_t vcp_code = vcp_entry->feature_code; // DBGMSG("Setting feature: 0x%02x", vcp_code); int flagndx = vcp_code >> 3; int shiftct = vcp_code & 0x07; Byte flagbit = 0x01 << shiftct; // printf("(%s) vcp_code=0x%02x, flagndx=%d, shiftct=%d, flagbit=0x%02x\n", // __func__, vcp_code, flagndx, shiftct, flagbit); vcplist.bytes[flagndx] |= flagbit; // uint8_t bval = vcplist.bytes[flagndx]; // printf("(%s) vcplist.bytes[%d] = 0x%02x\n", __func__, flagndx, bval); #endif } if (debug || IS_TRACING()) { DBGMSG("Returning: %s", feature_list_string(&vcplist, "", ",")); // rpt_hex_dump(vcplist.bytes, 32, 1); } return vcplist; } DDCA_Status ddca_get_feature_list_by_dref( DDCA_Feature_Subset_Id feature_set_id, DDCA_Display_Ref ddca_dref, bool include_table_features, DDCA_Feature_List* feature_list_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_subset_id=%d=0x%08x=%s, ddca_dref=%p, " "include_table_features=%s, feature_list_loc=%p", feature_set_id, feature_set_id, ddca_feature_list_id_name(feature_set_id), ddca_dref, sbool(include_table_features), feature_list_loc); assert(feature_list_loc); DDCA_Status psc = 0; VCP_Feature_Subset subset = VCP_SUBSET_NONE; // pointless initialization to avoid compile warning WITH_VALIDATED_DR4( ddca_dref, psc, DREF_VALIDATE_BASIC_ONLY, { DDCA_MCCS_Version_Spec vspec = // dref->vcp_version; get_vcp_version_by_dref(dref); DBGMSF(debug, "vspec=%%", format_vspec_verbose(vspec) ); // redundant: // assert( !vcp_version_eq( vspec, DDCA_VSPEC_UNQUERIED) ); // Whether a feature is a table feature can vary by version, so can't // specify VCP_SPEC_ANY to request feature ids in any version assert(vcp_version_is_valid(vspec, /* allow unknown */ false)); switch (feature_set_id) { case DDCA_SUBSET_KNOWN: subset = VCP_SUBSET_KNOWN; break; case DDCA_SUBSET_COLOR: subset = VCP_SUBSET_COLOR; break; case DDCA_SUBSET_PROFILE: subset = VCP_SUBSET_PROFILE; break; case DDCA_SUBSET_MFG: subset = VCP_SUBSET_MFG; break; case DDCA_SUBSET_UNSET: subset = VCP_SUBSET_NONE; break; case DDCA_SUBSET_CAPABILITIES: subset = VCP_SUBSET_NONE; // Currently handled in ddcui DBGMSG("DDCA_SUBSET_CAPABILITIES -> VCP_SUBSET_NONE"); break; case DDCA_SUBSET_SCAN: subset = VCP_SUBSET_SCAN; break; case DDCA_SUBSET_CUSTOM: subset = VCP_SUBSET_NONE; // handled in ddcui DBGMSG("DDCA_SUBSET_CUSTOM -> VCP_SUBSET_NONE"); break; } DBGMSF(debug, "subset=%d=%s", subset, feature_subset_name( subset)); Feature_Set_Flags flags = 0x00; if (!include_table_features) flags |= FSF_NOTABLE; Dyn_Feature_Set * fset = dyn_create_feature_set(subset, dref, flags); // VCP_Feature_Set fset = create_feature_set(subset, vspec, !include_table_features); // TODO: function variant that takes result location as a parm, avoid memcpy DDCA_Feature_List result = feature_list_from_dyn_feature_set(fset); memcpy(feature_list_loc, &result, 32); dyn_free_feature_set(fset); } ); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Feature list: %s", feature_list_string(feature_list_loc, "", ",")); // rpt_hex_dump((Byte*) p_feature_list, 32, 1); API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, psc, "feature_set_id=%d=0x%08x=%s, subset=%d=%s", feature_set_id, feature_set_id, ddca_feature_list_id_name(feature_set_id), subset, feature_subset_name(subset)); } bool ddca_feature_list_eq( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2) { return memcmp(&vcplist1, &vcplist2, sizeof(DDCA_Feature_List)) == 0; } DDCA_Feature_List ddca_feature_list_or( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2) { return feature_list_or(&vcplist1, &vcplist2); } DDCA_Feature_List ddca_feature_list_and( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2) { return feature_list_and(&vcplist1, &vcplist2); } DDCA_Feature_List ddca_feature_list_and_not( DDCA_Feature_List vcplist1, DDCA_Feature_List vcplist2) { return feature_list_and_not(&vcplist1, &vcplist2); } #ifdef UNPUBLISHED // no real savings in client code // sample use: // int codect; // uint8_t feature_codes[256]; // ddca_feature_list_to_codes(&vcplist2, &codect, feature_codes); // printf("\nFeatures in feature set COLOR: "); // for (int ndx = 0; ndx < codect; ndx++) { // printf(" 0x%02x", feature_codes[ndx]); // } // puts(""); /** Converts a feature list into an array of feature codes. * * @param[in] vcplist pointer to feature list * @param[out] p_codect address where to return count of feature codes * @param[out] vcp_codes address of 256 byte buffer to receive codes */ void ddca_feature_list_to_codes( DDCA_Feature_List* vcplist, int* codect, uint8_t vcp_codes[256]) { int ctr = 0; for (int ndx = 0; ndx < 256; ndx++) { if (ddca_feature_list_contains(vcplist, ndx)) { vcp_codes[ctr++] = ndx; } } *codect = ctr; } #endif int ddca_feature_list_count( DDCA_Feature_List feature_list) { return feature_list_count(&feature_list); } const char * ddca_feature_list_string( DDCA_Feature_List feature_list, const char * value_prefix, const char * sepstr) { return feature_list_string(&feature_list, value_prefix, sepstr); } // // Feature Metadata // #ifdef NEVER_RELEASED DDCA_Status ddca_get_simplified_feature_info( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, // DDCA_MCCS_Version_Id mccs_version_id, DDCA_Feature_Metadata * info) { DDCA_Status psc = DDCRC_ARG; DDCA_Version_Feature_Info * full_info = get_version_feature_info_by_vspec( feature_code, vspec, false, // with_default true); // false => version specific, true=> version sensitive if (full_info) { info->feature_code = feature_code; info->vspec = vspec; info->version_id = full_info->version_id; // keep? info->feature_flags = full_info->feature_flags; free_version_feature_info(full_info); psc = 0; } return psc; } #endif // UNPUBLISHED /** * Gets characteristics of a VCP feature. * * VCP characteristics (C vs NC, RW vs RO, etc) can vary by MCCS version. * * @param[in] feature_code VCP feature code * @param[in] vspec MCCS version (may be DDCA_VSPEC_UNKNOWN) * @param[out] p_feature_flags address of flag field to fill in * @return status code * @retval DDCRC_ARG invalid MCCS version * @retval DDCRC_UNKNOWN_FEATURE unrecognized feature * * @since 0.9.0 */ DDCA_Status ddca_get_feature_flags_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, DDCA_Feature_Flags * feature_flags) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, NORESPECT_QUIESCE, ""); DDCA_Status psc = DDCRC_ARG; // assert(feature_flags); API_PRECOND_W_EPILOG(feature_flags); if (vcp_version_is_valid(vspec, /*unknown_ok*/ true)) { // DDCA_Version_Feature_Info * full_info = get_version_feature_info_by_vspec( Display_Feature_Metadata * dfm = get_version_feature_info_by_vspec_dfm( feature_code, vspec, false, // with_default true); // false => version specific, true=> version sensitive if (dfm) { *feature_flags = dfm->version_feature_flags; // if (dfm->global_feature_flags & DDCA_PERSISTENT_METADATA) // *feature_flags |= DDCA_PERSISTENT_METADATA; // free_version_feature_info(full_info); dfm_free(dfm); psc = 0; } else { psc = DDCRC_UNKNOWN_FEATURE; } } API_EPILOG_RET_DDCRC(debug, false, psc, ""); } #ifdef NEVER_RELEASED DDCA_Status ddca_get_feature_flags_by_version_id( DDCA_Vcp_Feature_Code feature_code, // DDCA_MCCS_Version_Spec vspec, DDCA_MCCS_Version_Id mccs_version_id, DDCA_Feature_Flags * feature_flags) { free_thread_error_detail(); DDCA_Status psc = DDCRC_ARG; DDCA_Version_Feature_Info * full_info = get_version_feature_info_by_version_id( feature_code, mccs_version_id, false, // with_default true); // false => version specific, true=> version sensitive if (full_info) { *feature_flags = full_info->feature_flags; free_version_feature_info(full_info); psc = 0; } return psc; } #endif #ifdef NO DDCA_Status ddca_get_highest_version_sl_values( DDCA_Vcp_Feature_Code feature_code, DDCA_Feature_Value_Entry ** sl_table_loc) { DDCA_Status rc = DDCRC_NOT_FOUND; DDCA_Feature_Value_Entry * result = NULL; VCP_Feature_Table_Entry * vfte = vcp_find_feature_by_hexid(feature_code); if (vfte) { result = get_highest_version_sl_values(vfte); rc = DDCRC_OK; } *sl_table_loc = result; return rc; } #endif DDCA_Status ddca_get_feature_metadata_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, bool create_default_if_not_found, DDCA_Feature_Metadata ** info_loc) // { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, NORESPECT_QUIESCE, "feature_code=0x%02x, vspec=%s, create_default_if_not_found=%s, info_loc=%p", feature_code, format_vspec_verbose(vspec), sbool(create_default_if_not_found), info_loc); assert(info_loc); DDCA_Feature_Metadata * meta = NULL; DDCA_Status psc = DDCRC_ARG; Display_Feature_Metadata * dfm = get_version_feature_info_by_vspec_dfm( feature_code, vspec, create_default_if_not_found, true); // false => version specific, true=> version sensitive if (dfm) { // DBGMSG("Reading full_info"); meta = dfm_to_ddca_feature_metadata(dfm); dfm_free(dfm); psc = 0; } if (debug) { DBGMSG("Returning: %s", psc_desc(psc)); if (psc == 0) dbgrpt_ddca_feature_metadata(meta, 2); } *info_loc = meta; ASSERT_IFF(psc==0, *info_loc); API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, psc, ""); } DDCA_Status ddca_get_feature_metadata_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, bool create_default_if_not_found, DDCA_Feature_Metadata ** metadata_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_code=0x%02x, ddca_dref=%p, create_default_if_not_found=%s, meta_loc=%p", feature_code, ddca_dref, sbool(create_default_if_not_found), metadata_loc); assert(metadata_loc); DDCA_Status psc = 0; WITH_VALIDATED_DR4( ddca_dref, psc, DREF_VALIDATE_BASIC_ONLY, { DDCA_Feature_Metadata * external_metadata = NULL; Display_Feature_Metadata * internal_metadata = dyn_get_feature_metadata_by_dref(feature_code, dref, true, create_default_if_not_found); if (!internal_metadata) { psc = DDCRC_NOT_FOUND; } else { external_metadata = dfm_to_ddca_feature_metadata(internal_metadata); dfm_free(internal_metadata); } *metadata_loc = external_metadata; } ); ASSERT_IFF(psc==0, *metadata_loc); API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, psc, ""); return psc; } DDCA_Status ddca_get_feature_metadata_by_dh( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Handle ddca_dh, bool create_default_if_not_found, DDCA_Feature_Metadata ** metadata_loc) { bool debug = false; // if (feature_code == 0xca) // debug = true; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_code=0x%02x, ddca_dh=%p->%s, create_default_if_not_found=%s, metadata_loc=%p", feature_code, ddca_dh, dh_repr(ddca_dh), sbool(create_default_if_not_found), metadata_loc); API_PRECOND_W_EPILOG(metadata_loc); DDCA_Status psc = 0; WITH_VALIDATED_DH3( ddca_dh, psc, { if (debug) dbgrpt_display_ref(dh->dref, true, 1); DDCA_Feature_Metadata * external_metadata = NULL; Display_Feature_Metadata * internal_metadata = dyn_get_feature_metadata_by_dh(feature_code, dh, /*check_udf=*/ true, create_default_if_not_found); if (!internal_metadata) { psc = DDCRC_NOT_FOUND; } else { external_metadata = dfm_to_ddca_feature_metadata(internal_metadata); dfm_free(internal_metadata); } *metadata_loc = external_metadata; ASSERT_IFF(psc == 0, *metadata_loc); if (psc == 0 && IS_DBGTRC(debug,TRACE_GROUP)) { dbgrpt_ddca_feature_metadata(external_metadata, 5); } } ); API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, psc, ""); } #ifdef OLD // frees the contents of info, not info itself DDCA_Status ddca_free_feature_metadata_contents(DDCA_Feature_Metadata info) { if ( memcmp(info.marker, DDCA_FEATURE_METADATA_MARKER, 4) == 0) { if (info.feature_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { free(info.feature_name); free(info.feature_desc); } info.marker[3] = 'x'; } return 0; } #endif void ddca_free_feature_metadata(DDCA_Feature_Metadata* metadata) { bool debug = false; API_PROLOG(debug, "metadata=%p", metadata); if (metadata) { // Internal DDCA_Feature_Metadata instances (DDCA_PERSISTENT_METADATA) should never make it out into the wild if ( (memcmp(metadata->marker, DDCA_FEATURE_METADATA_MARKER, 4) == 0) && (!(metadata->feature_flags & DDCA_PERSISTENT_METADATA)) ) { free_ddca_feature_metadata(metadata); } } API_EPILOG_BEFORE_RETURN(debug, false, 0, ""); } // returns pointer into permanent internal data structure, caller should not free const char * ddca_get_feature_name(DDCA_Vcp_Feature_Code feature_code) { // do we want get_feature_name()'s handling of mfg specific and unrecognized codes? char * result = get_feature_name_by_id_only(feature_code); return result; } #ifdef DEPRECATED // deprecated char * ddca_feature_name_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, DDCA_Monitor_Model_Key * p_mmid) // currently ignored { char * result = get_feature_name_by_id_and_vcp_version(feature_code, vspec); return result; } #endif #ifdef NEVER_RELEASED /** \deprecated */ char * ddca_feature_name_by_version_id( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Id mccs_version_id) { DDCA_MCCS_Version_Spec vspec = mccs_version_id_to_spec(mccs_version_id); char * result = get_feature_name_by_id_and_vcp_version(feature_code, vspec); return result; } #endif #ifdef DEPRECATED /** Gets the VCP feature name, which may vary by MCCS version and monitor model. * * @param[in] feature_code feature code * @param[in] dref display reference * @param[out] name_loc where to return pointer to feature name (do not free) * @return status code * * @since 0.9.2 */ __attribute__ ((deprecated ("use ddca_get_feature_metadata_by_dref()"))) DDCA_Status ddca_get_feature_name_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref dref, char ** name_loc); // deprecated DDCA_Status ddca_get_feature_name_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, char ** name_loc) { bool debug = false; API_PROLOG(debug, "feature_code = 0x%02x", feature_code); DDCA_Status psc = 0; WITH_VALIDATED_DR3(ddca_dref, psc, { //*name_loc = ddca_feature_name_by_vspec(feature_code, dref->vcp_version, dref->mmid); *name_loc = get_feature_name_by_id_and_vcp_version(feature_code, get_vcp_version_by_dref(dref) //dref->vcp_version ); if (!*name_loc) psc = DDCRC_ARG; } ) API_EPILOG_RET_DDCRC(debug, psc, ""); } #endif // // Display Inquiry // #ifdef UNUSED // unpublished DDCA_Status ddca_get_simple_sl_value_table_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, const DDCA_Monitor_Model_Key * p_mmid, // currently ignored DDCA_Feature_Value_Entry** value_table_loc) { bool debug = false; DDCA_Status rc = 0; *value_table_loc = NULL; DBGMSF(debug, "feature_code = 0x%02x, vspec=%d.%d", feature_code, vspec.major, vspec.minor); assert(value_table_loc); free_thread_error_detail(); if (!vcp_version_is_valid(vspec, /* unknown_ok */ true)) { rc = DDCRC_ARG; goto bye; } VCP_Feature_Table_Entry * pentry = vcp_find_feature_by_hexid(feature_code); if (!pentry) { *value_table_loc = NULL; rc = DDCRC_UNKNOWN_FEATURE; } else { DDCA_Version_Feature_Flags vflags = get_version_sensitive_feature_flags(pentry, vspec); if (!(vflags & DDCA_SIMPLE_NC)) { *value_table_loc = NULL; rc = DDCRC_INVALID_OPERATION; } else { DDCA_Feature_Value_Entry * table = get_version_sensitive_sl_values(pentry, vspec); // DDCA_Feature_Value_Entry * table = get_highest_version_sl_values(pentry); DDCA_Feature_Value_Entry * table2 = (DDCA_Feature_Value_Entry*) table; // identical definitions *value_table_loc = table2; rc = 0; DDCA_Feature_Value_Entry * cur = table2; if (debug) { while (cur->value_name) { DBGMSG(" 0x%02x - %s", cur->value_code, cur->value_name); cur++; } } } } bye: DBGMSF(debug, "Done. *pvalue_table=%p, returning %s", *value_table_loc, psc_desc(rc)); assert ( (rc==0 && *value_table_loc) || (rc!=0 && !*value_table_loc) ); return rc; } #endif #ifdef UNUSED // for now, just gets SL value table based on the vspec of the display ref, // eventually handle dynamically assigned monitor specs DDCA_Status ddca_get_simple_sl_value_table_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, DDCA_Feature_Value_Entry** value_table_loc) { WITH_DR(ddca_dref, { assert(value_table_loc); psc = ddca_get_simple_sl_value_table_by_vspec( feature_code, dref->vcp_version_old, dref->mmid, value_table_loc); assert ( (psc==0 && *value_table_loc) || (psc!=0 && !*value_table_loc) ); } ) } #endif #ifdef UNUSED DDCA_Status ddca_get_simple_sl_value_table( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Id mccs_version_id, DDCA_Feature_Value_Entry** value_table_loc) { bool debug = false; DDCA_Status rc = 0; assert(value_table_loc); *value_table_loc = NULL; DDCA_MCCS_Version_Spec vspec = mccs_version_id_to_spec(mccs_version_id); DBGMSF(debug, "feature_code = 0x%02x, mccs_version_id=%d, vspec=%d.%d", feature_code, mccs_version_id, vspec.major, vspec.minor); rc = ddca_get_simple_sl_value_table_by_vspec( feature_code, vspec, &DDCA_UNDEFINED_MONITOR_MODEL_KEY, value_table_loc); DBGMSF(debug, "Done. *value_table_loc=%p, returning %s", *value_table_loc, psc_desc(rc)); assert ( (rc==0 && *value_table_loc) || (rc!=0 && !*value_table_loc) ); return rc; } #endif // typedef void * Feature_Value_Table; // temp DDCA_Status ddca_get_simple_nc_feature_value_name_by_table( DDCA_Feature_Value_Entry * feature_value_table, uint8_t feature_value, char** value_name_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, NORESPECT_QUIESCE, "feature_value_table = %p, feature_value = 0x%02x", feature_value_table, feature_value); // DBGMSG("feature_value_table=%p", feature_value_table); // DBGMSG("*feature_value_table=%p", *feature_value_table); DDCA_Status rc = 0; assert(value_name_loc); DDCA_Feature_Value_Entry * feature_value_entries = feature_value_table; *value_name_loc = sl_value_table_lookup(feature_value_entries, feature_value); if (!*value_name_loc) rc = DDCRC_NOT_FOUND; // correct handling for value not found? assert ( (rc==0 && *value_name_loc) || (rc!=0 && !*value_name_loc) ); API_EPILOG_RET_DDCRC(debug, NORESPECT_QUIESCE, rc, ""); } #ifdef UNUSED DDCA_Status ddca_get_simple_nc_feature_value_name_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, // needed because value lookup mccs version dependent const DDCA_Monitor_Model_Key * p_mmid, uint8_t feature_value, char** feature_name_loc) { assert(feature_name_loc); free_thread_error_detail(); DDCA_Feature_Value_Entry * feature_value_entries = NULL; // this should be a function in vcp_feature_codes: DDCA_Status rc = ddca_get_simple_sl_value_table_by_vspec( feature_code, vspec, p_mmid, &feature_value_entries); if (rc == 0) { // DBGMSG("&feature_value_entries = %p", &feature_value_entries); rc = ddca_get_simple_nc_feature_value_name_by_table(feature_value_entries, feature_value, feature_name_loc); } assert ( (rc==0 && *feature_name_loc) || (rc!=0 && !*feature_name_loc) ); return rc; } #endif #ifdef UNUSED // deprecated DDCA_Status ddca_get_simple_nc_feature_value_name_by_display( DDCA_Display_Handle ddca_dh, // needed because value lookup mccs version dependent DDCA_Vcp_Feature_Code feature_code, uint8_t feature_value, char** feature_name_loc) { WITH_DH(ddca_dh, { DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); DDCA_Monitor_Model_Key * p_mmid = dh->dref->mmid; return ddca_get_simple_nc_feature_value_name_by_vspec( feature_code, vspec, p_mmid, feature_value, feature_name_loc); } ); } #endif void ddca_dbgrpt_feature_metadata( DDCA_Feature_Metadata * md, int depth) { bool debug = false; reset_current_traced_function_stack(); DBGTRC_STARTING(debug, TRACE_GROUP, ""); // rpt_push_output_dest(stdout); dbgrpt_ddca_feature_metadata(md, depth); // rpt_pop_output_dest(); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Dynamic // bool ddca_enable_udf(bool onoff) { bool oldval = enable_dynamic_features; enable_dynamic_features = onoff; return oldval; } bool ddca_is_udf_enabled(void) { return enable_dynamic_features; } DDCA_Status ddca_dfr_check_by_dref(DDCA_Display_Ref ddca_dref) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dref=%p", ddca_dref); DDCA_Status psc = 0; WITH_VALIDATED_DR4(ddca_dref, psc, DREF_VALIDATE_BASIC_ONLY, { Error_Info * ddc_excp = dfr_check_by_dref(dref); if (ddc_excp) { if (ddc_excp->status_code != DDCRC_NOT_FOUND) { psc = ddc_excp->status_code; save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); } errinfo_free(ddc_excp); } } ); API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, psc, ""); } DDCA_Status ddca_dfr_check_by_dh(DDCA_Display_Handle ddca_dh) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dh=%p", ddca_dh); DDCA_Status psc = 0; WITH_VALIDATED_DH3(ddca_dh, psc, { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "dh=%s", dh_repr_p(dh)); Error_Info * ddc_excp = dfr_check_by_dh(dh); if (ddc_excp) { if (ddc_excp->status_code != DDCRC_NOT_FOUND) { psc = ddc_excp->status_code; save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); } errinfo_free(ddc_excp); } } ); API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, psc, "ddca_dh=%p->%s.", ddca_dh, dh_repr(ddca_dh) ); } void init_api_metadata() { RTTI_ADD_FUNC(ddca_free_feature_metadata); RTTI_ADD_FUNC(ddca_get_feature_list_by_dref); RTTI_ADD_FUNC(ddca_get_feature_metadata_by_vspec); RTTI_ADD_FUNC(ddca_get_feature_metadata_by_dref); RTTI_ADD_FUNC(ddca_get_feature_metadata_by_dh); // RTTI_ADD_FUNC(ddca_get_feature_name_by_dref); // error because deprecated RTTI_ADD_FUNC(ddca_get_simple_nc_feature_value_name_by_table); RTTI_ADD_FUNC(ddca_dfr_check_by_dref); // error because deprecated RTTI_ADD_FUNC(ddca_dfr_check_by_dh); } ddcutil-2.2.0/src/libmain/api_feature_access.c0000644000175000001440000012431614754153540015012 /** @file api_feature_access.c * * Get, set, and format feature values */ // Copyright (C) 2015-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include #include "public/ddcutil_c_api.h" #include "public/ddcutil_status_codes.h" #include "public/ddcutil_types.h" #include "util/error_info.h" #include "util/report_util.h" #include "base/core.h" #include "base/displays.h" #include "base/monitor_model_key.h" #include "base/rtti.h" #include "vcp/vcp_feature_values.h" #include "dynvcp/dyn_feature_codes.h" #include "ddc/ddc_dumpload.h" #include "ddc/ddc_vcp_version.h" #include "ddc/ddc_vcp.h" #include "libmain/api_error_info_internal.h" #include "libmain/api_base_internal.h" #include "libmain/api_displays_internal.h" #include "libmain/api_feature_access_internal.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_API; // // Get and Set Feature Values // #ifdef OLD // Was public, but eliminated from API due to problems in Python API caused by overlay. // Retained for impedance matching. Retained for historical interest. /** Represents a single non-table VCP value */ typedef struct { DDCA_Vcp_Feature_Code feature_code; union { struct { uint16_t max_val; /**< maximum value (mh, ml bytes) for continuous value */ uint16_t cur_val; /**< current value (sh, sl bytes) for continuous value */ } c; /**< continuous (C) value */ struct { // Ensure proper overlay of ml/mh on max_val, sl/sh on cur_val #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ uint8_t ml; /**< ML byte for NC value */ uint8_t mh; /**< MH byte for NC value */ uint8_t sl; /**< SL byte for NC value */ uint8_t sh; /**< SH byte for NC value */ #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ uint8_t mh; uint8_t ml; uint8_t sh; uint8_t sl; #else #error "Unexpected byte order value: __BYTE_ORDER__" #endif } nc; /**< non-continuous (NC) value */ } val; } Non_Table_Value_Response; #endif DDCA_Status ddca_get_non_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Non_Table_Vcp_Value* valrec) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, true, "ddca_dh=%p, feature_code=0x%02x, valrec=%p", ddca_dh, feature_code, valrec ); DDCA_Status psc = API_PRECOND_RVALUE(valrec); if (psc != 0) goto bye; WITH_VALIDATED_DH3(ddca_dh, psc, { Error_Info * ddc_excp = NULL; Parsed_Nontable_Vcp_Response * code_info; ddc_excp = ddc_get_nontable_vcp_value( dh, feature_code, &code_info); if (!ddc_excp) { valrec->mh = code_info->mh; valrec->ml = code_info->ml;; valrec->sh = code_info->sh; valrec->sl = code_info->sl; // DBGMSG("valrec: mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", // valrec->mh, valrec->ml, valrec->sh, valrec->sl); free(code_info); // DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, // "valrec: mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", // valrec->mh, valrec->ml, valrec->sh, valrec->sl); } else { psc = ddc_excp->status_code; save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); ERRINFO_FREE_WITH_REPORT(ddc_excp, IS_DBGTRC(debug, DDCA_TRC_API)); // DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, ""); } } ); bye: if (psc == 0) API_EPILOG_BEFORE_RETURN(debug, true, psc, "valrec: mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", valrec->mh, valrec->ml, valrec->sh, valrec->sl); else API_EPILOG_BEFORE_RETURN(debug, true, psc, ""); return psc; } // untested DDCA_Status ddca_get_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Table_Vcp_Value ** table_value_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, true, "ddca_dh=%p, feature_code=0x%02x, table_value_loc=%p", ddca_dh, feature_code, table_value_loc); DDCA_Status psc = API_PRECOND_RVALUE(table_value_loc); if (psc != 0) goto bye; WITH_VALIDATED_DH3(ddca_dh, psc, { assert(table_value_loc); Error_Info * ddc_excp = NULL; Buffer * p_table_bytes = NULL; ddc_excp = ddc_get_table_vcp_value(dh, feature_code, &p_table_bytes); psc = (ddc_excp) ? ddc_excp->status_code : 0; save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); errinfo_free(ddc_excp); if (psc == 0) { assert(p_table_bytes); // avoid coverity warning int len = p_table_bytes->len; DDCA_Table_Vcp_Value * tv = calloc(1,sizeof(DDCA_Table_Vcp_Value)); tv->bytect = len; if (len > 0) { tv->bytes = malloc(len); memcpy(tv->bytes, p_table_bytes->bytes, len); } *table_value_loc = tv; buffer_free(p_table_bytes, __func__); } TRACED_ASSERT_IFF(psc==0, *table_value_loc); // DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, // "ddca_dh=%p->%s, feature_code=0x%02x, *table_value_loc=%p", // ddca_dh, dh_repr(ddca_dh), feature_code, *table_value_loc); } ); bye: API_EPILOG_BEFORE_RETURN(debug, true, psc, "ddca_dh=%p->%s, feature_code=0x%02x, *table_value_loc=%p", ddca_dh, dh_repr(ddca_dh), feature_code, *table_value_loc); return psc; } static DDCA_Status ddci_get_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Vcp_Value_Type call_type, // why is this needed? look it up from dh and feature_code DDCA_Any_Vcp_Value ** pvalrec) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, "ddca_dh=%p, feature_code=0x%02x, call_type=%d, pvalrec=%p", ddca_dh, feature_code, call_type, pvalrec); Error_Info * ddc_excp = NULL; DDCA_Status psc = 0; WITH_VALIDATED_DH3(ddca_dh, psc, { *pvalrec = NULL; ddc_excp = ddc_get_vcp_value(dh, feature_code, call_type, pvalrec); psc = (ddc_excp) ? ddc_excp->status_code : 0; save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); errinfo_free(ddc_excp); DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, "*pvalrec=%p", *pvalrec); } ); DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, ""); return psc; } static DDCA_Status get_value_type( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Vcp_Value_Type * p_value_type) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "ddca_dh=%p, feature_code=0x%02x", ddca_dh, feature_code); DDCA_Status ddcrc = DDCRC_NOT_FOUND; DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(ddca_dh); VCP_Feature_Table_Entry * pentry = vcp_find_feature_by_hexid(feature_code); if (pentry) { DDCA_Version_Feature_Flags flags = get_version_sensitive_feature_flags(pentry, vspec); // Version_Feature_Flags flags = feature_info->internal_feature_flags; // n. will default to NON_TABLE_VCP_VALUE if not a known code *p_value_type = (flags & DDCA_TABLE) ? DDCA_TABLE_VCP_VALUE : DDCA_NON_TABLE_VCP_VALUE; ddcrc = 0; } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, ""); return ddcrc; } STATIC DDCA_Status ddci_get_any_vcp_value_using_explicit_type( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Vcp_Value_Type call_type, DDCA_Any_Vcp_Value ** valrec_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "ddca_dh=%p, feature_code=0x%02x, call_type=%d, valrec_loc=%p", ddca_dh, feature_code, call_type, valrec_loc); assert(valrec_loc); *valrec_loc = NULL; DDCA_Any_Vcp_Value * valrec2 = NULL; DDCA_Status rc = ddci_get_vcp_value(ddca_dh, feature_code, call_type, &valrec2); if (rc == 0) { *valrec_loc = valrec2; } DBGTRC_RET_DDCRC(debug, TRACE_GROUP, rc, "*valrec_loc=%p", *valrec_loc); ASSERT_IFF(rc == 0, *valrec_loc); return rc; } DDCA_Status ddca_get_any_vcp_value_using_explicit_type( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Vcp_Value_Type call_type, DDCA_Any_Vcp_Value ** valrec_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, true, "Starting. ddca_dh=%p, feature_code=0x%02x, call_type=%d, valrec_loc=%p", ddca_dh, feature_code, call_type, valrec_loc); assert(valrec_loc); *valrec_loc = NULL; DDCA_Status ddcrc = ddci_get_any_vcp_value_using_explicit_type( ddca_dh, feature_code, call_type, valrec_loc); API_EPILOG_BEFORE_RETURN(debug, true, ddcrc, "*valrec_loc=%p", *valrec_loc); ASSERT_IFF(ddcrc == 0, *valrec_loc); return ddcrc; } #ifdef ALT DDCA_Status ddca_get_any_vcp_value_using_explicit_type_new( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Vcp_Value_Type_Parm call_type, DDCA_Any_Vcp_Value ** pvalrec) { bool debug = false; DBGMSF(debug, "Starting. ddca_dh=%p, feature_code=0x%02x, call_type=%d, pvalrec=%p", ddca_dh, feature_code, call_type, pvalrec); *pvalrec = NULL; DDCA_Status rc = DDCRC_ARG; if (call_type == DDCA_UNSET_VCP_VALUE_TYPE_PARM) { call_type = get_value_type_parm(ddca_dh, feature_code, DDCA_UNSET_VCP_VALUE_TYPE_PARM); } if (call_type != DDCA_UNSET_VCP_VALUE_TYPE_PARM) { Single_Vcp_Value * valrec2 = NULL; rc = ddca_get_vcp_value(ddca_dh, feature_code, call_type, &valrec2); if (rc == 0) { DDCA_Any_Vcp_Value * valrec = single_vcp_value_to_any_vcp_value(valrec2); free(valrec2); // n. does not free table bytes, which are now pointed to by valrec *pvalrec = valrec; } } DBGMSF(debug, "Done. Returning %s, *pvalrec=%p", psc_desc(rc), *pvalrec); return rc; } #endif DDCA_Status ddca_get_any_vcp_value_using_implicit_type( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Any_Vcp_Value ** valrec_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, true, "feature_code = 0x%02x", feature_code); assert(valrec_loc); DDCA_Vcp_Value_Type call_type; DDCA_Status ddcrc = get_value_type(ddca_dh, feature_code, &call_type); if (ddcrc == 0) { ddcrc = ddci_get_any_vcp_value_using_explicit_type( ddca_dh, feature_code, call_type, valrec_loc); } ASSERT_IFF(ddcrc==0, *valrec_loc); API_EPILOG_BEFORE_RETURN(debug, true, ddcrc, ""); return ddcrc; } void ddca_free_table_vcp_value( DDCA_Table_Vcp_Value * table_value) { if (table_value) { free(table_value->bytes); free(table_value); } } void ddca_free_any_vcp_value( DDCA_Any_Vcp_Value * valrec) { if (valrec) { if (valrec->value_type == DDCA_TABLE_VCP_VALUE) { free(valrec->val.t.bytes); } free(valrec); } } // not published /** Produces a debugging report of a #DDCA_Any_Vcp_Value instance. * The report is written to the current FOUT device. * @param[in] valrec instance to report * @param[in] depth logical indentation depth * @since 0.9.0 */ void dbgrpt_any_vcp_value( DDCA_Any_Vcp_Value * valrec, int depth) { int d1 = depth+1; rpt_vstring(depth, "DDCA_Any_Vcp_Value at %p:", valrec); rpt_vstring(d1, "opcode=0x%02x, value_type=%s (0x%02x)", valrec->opcode, vcp_value_type_name(valrec->value_type), valrec->value_type); if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { rpt_vstring(d1, "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", valrec->val.c_nc.mh, valrec->val.c_nc.ml, valrec->val.c_nc.sh, valrec->val.c_nc.sl); uint16_t max_val = valrec->val.c_nc.mh << 8 | valrec->val.c_nc.ml; uint16_t cur_val = valrec->val.c_nc.sh << 8 | valrec->val.c_nc.sl; rpt_vstring(d1, "max_val=%d (0x%04x), cur_val=%d (0x%04x)", max_val, max_val, cur_val, cur_val); } else if (valrec->value_type == DDCA_TABLE_VCP_VALUE) { rpt_hex_dump(valrec->val.t.bytes, valrec->val.t.bytect, d1); } else { rpt_vstring(d1, "Unrecognized value type: %d", valrec->value_type); } } #ifdef DEPRECATED // deprecated, does not support user defined features /** Returns a string containing a formatted representation of the VCP value * of a feature. It is the responsibility of the caller to free this value. * * @param[in] ddca_dh Display handle * @param[in] feature_code VCP feature code * @param[out] formatted_value_loc Address at which to return the formatted value * @return status code, 0 if success * @since 0.9.0 * @deprecated Does not support user-supplied feature definitions */ DDCA_Status ddca_get_formatted_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, char** formatted_value_loc) { bool debug = false; API_PROLOG(debug, "feature_code=0x%02x, formatted_value_loc=%p", feature_code, formatted_value_loc); DDCA_Status psc = API_PRECOND_RVALUE(formatted_value_loc); Error_Info * ddc_excp = NULL; if (psc != 0) goto bye; WITH_VALIDATED_DH3(ddca_dh, psc, { *formatted_value_loc = NULL; DDCA_MCCS_Version_Spec vspec = get_vcp_version_by_dh(dh); // DDCA_MCCS_Version_Id version_id = mccs_version_spec_to_id(vspec); VCP_Feature_Table_Entry * pentry = vcp_find_feature_by_hexid(feature_code); if (!pentry) { #ifdef ALT DDCA_Version_Feature_Info * feature_info = get_version_specific_feature_info( feature_code, true, // with_default version_id); assert(feature_info); if (!feature_info) { #endif psc = DDCRC_ARG; } else { DDCA_Version_Feature_Flags flags = get_version_sensitive_feature_flags(pentry, vspec); if (!(flags & DDCA_READABLE)) { if (flags & DDCA_DEPRECATED) *formatted_value_loc = g_strdup_printf("Feature %02x is deprecated in MCCS %d.%d\n", feature_code, vspec.major, vspec.minor); else *formatted_value_loc = g_strdup_printf("Feature %02x is not readable\n", feature_code); DBGMSF(debug, "%s", *formatted_value_loc); psc = DDCRC_INVALID_OPERATION; } else { // Version_Feature_Flags flags = feature_info->internal_feature_flags; // n. will default to NON_TABLE_VCP_VALUE if not a known code DDCA_Vcp_Value_Type call_type = (flags & DDCA_TABLE) ? DDCA_TABLE_VCP_VALUE : DDCA_NON_TABLE_VCP_VALUE; DDCA_Any_Vcp_Value * pvalrec; ddc_excp = ddc_get_vcp_value(dh, feature_code, call_type, &pvalrec); psc = (ddc_excp) ? ddc_excp->status_code : 0; errinfo_free(ddc_excp); if (psc == 0) { bool ok = vcp_format_feature_detail( pentry, vspec, pvalrec, formatted_value_loc ); if (!ok) { psc = DDCRC_OTHER; // ** WRONG CODE *** assert(!formatted_value_loc); } } } } // DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, ""); } ) bye: API_EPILOG_BEFORE_RETURN(debug, psc, ""); return psc; } #endif /** Returns a formatted representation of a VCP value of any type * It is the responsibility of the caller to free the returned string. * * @param[in] feature_code VCP feature code * @param[in] vspec MCCS version * @param[in] valrec non-table VCP value * @param[out] formatted_value_loc address at which to return the formatted value. * @return status code, 0 if success * * @remark * If the returned status code is != 0, the string returned will * contain an explanation of the error. * * @since 0.9.0 */ static DDCA_Status ddci_format_any_vcp_value( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, Monitor_Model_Key * mmid, DDCA_Any_Vcp_Value * anyval, char ** formatted_value_loc) { bool debug = false; free_thread_error_detail(); DBGTRC_STARTING(debug, TRACE_GROUP, "feature_code=0x%02x, vspec=%d.%d, mmid=%p -> %s", feature_code, vspec.major, vspec.minor, mmid, (mmid) ? mmk_repr(*mmid) : "NULL" ); assert(formatted_value_loc); DDCA_Status ddcrc = 0; *formatted_value_loc = NULL; Display_Feature_Metadata * dfm = NULL; if (!mmid) { *formatted_value_loc = g_strdup("Programming error. mmid not specified"); ddcrc = DDCRC_ARG; goto bye; } dfm = dyn_get_feature_metadata_by_mmk_and_vspec( feature_code, *mmid, vspec, /* use_udf=*/ true, /*with_default=*/ true); if (!dfm) { ddcrc = DDCRC_ARG; *formatted_value_loc = g_strdup_printf("Unrecognized feature code 0x%02x", feature_code); goto bye; } DDCA_Version_Feature_Flags version_flags = dfm->version_feature_flags; if (!(version_flags & DDCA_READABLE)) { if (version_flags & DDCA_DEPRECATED) *formatted_value_loc = g_strdup_printf("Feature %02x is deprecated in MCCS %d.%d", feature_code, vspec.major, vspec.minor); else *formatted_value_loc = g_strdup_printf("Feature %02x is not readable", feature_code); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s", *formatted_value_loc); ddcrc = DDCRC_INVALID_OPERATION; goto bye; } // Version_Feature_Flags flags = feature_info->internal_feature_flags; // n. will default to NON_TABLE_VCP_VALUE if not a known code DDCA_Vcp_Value_Type call_type = (version_flags & DDCA_TABLE) ? DDCA_TABLE_VCP_VALUE : DDCA_NON_TABLE_VCP_VALUE; if (call_type != anyval->value_type) { *formatted_value_loc = g_strdup_printf( "Feature type in value does not match feature code"); ddcrc = DDCRC_ARG; goto bye; } bool ok = dyn_format_feature_detail(dfm, vspec, anyval,formatted_value_loc); if (!ok) { ddcrc = DDCRC_ARG; // ?? assert(!*formatted_value_loc); *formatted_value_loc = g_strdup_printf("Unable to format value for feature 0x%02x", feature_code); } bye: if (dfm) dfm_free(dfm); // API_EPILOG_BEFORE_RETURN(debug, NORESPECT_QUIESCE, ddcrc, "formatted_value_loc -> %s", *formatted_value_loc); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, "formatted_value_loc -> %s", *formatted_value_loc); // 7/2019: wrong, *formatted_value_loc always set, why did this ever work? // assert( (ddcrc==0 && *formatted_value_loc) || (ddcrc!=0 &&!*formatted_value_loc) ); return ddcrc; } DDCA_Status ddca_format_any_vcp_value_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, DDCA_Any_Vcp_Value * valrec, char ** formatted_value_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, NORESPECT_QUIESCE, "feature_code=0x%02x, ddca_dref=%p, valrec=%s", feature_code, ddca_dref, summarize_single_vcp_value(valrec) ); assert(formatted_value_loc); DDCA_Status ddcrc = 0; WITH_VALIDATED_DR4(ddca_dref, ddcrc, DREF_VALIDATE_BASIC_ONLY, { if (debug || IS_TRACING()) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dref = %s", dref_repr_t(dref)); dbgrpt_display_ref(dref,true, 1); } ddcrc = ddci_format_any_vcp_value( feature_code, get_vcp_version_by_dref(dref), // dref->vcp_version, dref->mmid, valrec, formatted_value_loc); // no, if psc != 0, ddca_format_any_vcp_value() returns an error message // assert( (psc==0 && *formatted_value_loc) || (psc!=0 &&!*formatted_value_loc) ); } ) API_EPILOG_BEFORE_RETURN(debug, NORESPECT_QUIESCE, ddcrc, "*formatted_value_loc = %p -> |%s|", *formatted_value_loc, *formatted_value_loc); return ddcrc; } /** Returns a formatted representation of a non-table VCP value. * It is the responsibility of the caller to free the returned string. * * @param[in] feature_code VCP feature code * @param[in] vspec MCCS version * @param[in] valrec non-table VCP value * @param[out] formatted_value_loc address at which to return the formatted value. * @return status code, 0 if success */ static DDCA_Status ddci_format_non_table_vcp_value( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, Monitor_Model_Key * mmid, DDCA_Non_Table_Vcp_Value * valrec, char ** formatted_value_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "feature_code=0x%02x, vspec=%d.%d, mmid=%s, formatted_value_loc=%p", feature_code, vspec.major, vspec.minor, (mmid) ? mmk_repr(*mmid) : "NULL", formatted_value_loc); DDCA_Status ddcrc = API_PRECOND_RVALUE(formatted_value_loc); if (ddcrc != 0) { // DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, ddcrc, ""); goto bye; } *formatted_value_loc = NULL; // free_thread_error_detail(); // unnecessary, done by ddca_format_any_vcp_value(); DDCA_Any_Vcp_Value anyval; anyval.opcode = feature_code; anyval.value_type = DDCA_NON_TABLE_VCP_VALUE; anyval.val.c_nc.mh = valrec->mh; anyval.val.c_nc.ml = valrec->ml; anyval.val.c_nc.sh = valrec->sh; anyval.val.c_nc.sl = valrec->sl; ddcrc = ddci_format_any_vcp_value( feature_code, vspec, mmid, &anyval, formatted_value_loc); // assert( (ddcrc==0 &&*formatted_value_loc) || (ddcrc!=0 && !*formatted_value_loc) ); #ifdef OUT if (ddcrc == 0) API_EPILOG_BEFORE_RETURN(debug, false, ddcrc, "*formatted_value_loc=%p->%s", *formatted_value_loc, *formatted_value_loc); else API_EPILOG_BEFORE_RETURN(debug, false, ddcrc, "*formatted_value_loc=%p", *formatted_value_loc); #endif // if (ddcrc == 0) // DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, ddcrc, // "*formatted_value_loc=%p->%s", *formatted_value_loc, *formatted_value_loc); // else // DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, ddcrc, "*formatted_value_loc=%p", *formatted_value_loc); bye: // DISABLE_API_CALL_TRACING(); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, ""); return ddcrc; } DDCA_Status ddca_format_non_table_vcp_value_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, DDCA_Non_Table_Vcp_Value * valrec, char ** formatted_value_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_code=0x%02x, ddca_dref=%p", feature_code, ddca_dref); assert(formatted_value_loc); DDCA_Status ddcrc = 0; WITH_VALIDATED_DR4(ddca_dref, ddcrc, DREF_VALIDATE_BASIC_ONLY, { if (debug || IS_TRACING()) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dref = %s", dref_repr_t(dref)); dbgrpt_display_ref(dref, true, 1); } ddcrc = ddci_format_non_table_vcp_value( feature_code, // dref->vcp_version, get_vcp_version_by_dref(dref), dref->mmid, valrec, formatted_value_loc); // assert( (psc==0 &&*formatted_value_loc) || (psc!=0 && !*formatted_value_loc) ); } ) API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, ddcrc, "*formatted_value_loc = %p -> |%s|", *formatted_value_loc, *formatted_value_loc); return ddcrc; } // NEVER PUBLISHED, USED INTERNALLY /** Returns a formatted representation of a table VCP value. * It is the responsibility of the caller to free the returned string. * * @param[in] feature_code VCP feature code * @param[in] vspec MCCS version * @param[in] table_value table VCP value * @param[out] formatted_value_loc address at which to return the formatted value. * @return status code, 0 if success */ static DDCA_Status ddci_format_table_vcp_value( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, Monitor_Model_Key * mmid, DDCA_Table_Vcp_Value * table_value, char ** formatted_value_loc) { // free_thread_error_detail(); // unnecessary, done by ddca_format_any_vcp_value(); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); // API_PROLOG(debug, ""); DDCA_Any_Vcp_Value anyval; anyval.opcode = feature_code; anyval.value_type = DDCA_TABLE_VCP_VALUE; anyval.val.t.bytect = table_value->bytect; anyval.val.t.bytes = table_value->bytes; // n. copying pointer, not duplicating bytes DDCA_Status ddcrc = ddci_format_any_vcp_value( feature_code, vspec, mmid, &anyval, formatted_value_loc); // API_EPILOG_BEFORE_RETURN(debug, false, ddcrc, ""); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, ddcrc, ""); return ddcrc; } DDCA_Status ddca_format_table_vcp_value_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref ddca_dref, DDCA_Table_Vcp_Value * table_value, char ** formatted_value_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_code=0x%02x, ddca_dref=%p", feature_code, ddca_dref); assert(formatted_value_loc); DDCA_Status ddcrc = 0; WITH_VALIDATED_DR4(ddca_dref, ddcrc, DREF_VALIDATE_BASIC_ONLY, { if (debug || IS_TRACING()) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "dref = %s", dref_repr_t(dref)); dbgrpt_display_ref(dref,true,1); } ddcrc = ddci_format_table_vcp_value( feature_code, // dref->vcp_version, get_vcp_version_by_dref(dref), dref->mmid, table_value, formatted_value_loc); } ) API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, ddcrc, "*formatted_value_loc = %p -> |%s|", *formatted_value_loc, *formatted_value_loc); return ddcrc; } static DDCA_Status ddci_set_single_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Any_Vcp_Value * valrec, DDCA_Any_Vcp_Value ** verified_value_loc) // NULL => do not return value { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, "ddca_dh=%p, valrec=%p, verified_value_loc = %p", ddca_dh, valrec, verified_value_loc); DDCA_Status psc = 0; free_thread_error_detail(); WITH_VALIDATED_DH3(ddca_dh, psc, { Error_Info * ddc_excp = ddc_set_verified_vcp_value_with_retry(dh, valrec, verified_value_loc); psc = (ddc_excp) ? ddc_excp->status_code : 0; save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); ERRINFO_FREE_WITH_REPORT(ddc_excp, IS_DBGTRC(debug, DDCA_TRC_API)); } ); DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, ""); return psc; } // UNPUBLISHED /** Sets a Continuous VCP value. * * @param[in] ddca_dh display_handle * @param[in] feature_code VCP feature code * @param[in] new_value value to set (sign?) * @param[out] verified_value_loc if non-null, return verified value here * @return status code * * @remark * Verification is performed if **verified_value_loc** is non-NULL and * verification has been enabled (see #ddca_enable_verify()). * @remark * If verification is performed, the value of the feature is read after being * written. If the returned status code is either DDCRC_OK (0) or DDCRC_VERIFY, * the verified value is returned in **verified_value_loc**. * @remark * This is essentially a convenience function, since a Continuous value can be * set by passing its high and low bytes to #ddca_set_non_table_vcp_value_verify(). */ static DDCA_Status ddci_set_continuous_vcp_value_verify( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, uint16_t new_value, uint16_t * verified_value_loc) { DDCA_Status rc = 0; DDCA_Any_Vcp_Value valrec; valrec.opcode = feature_code; valrec.value_type = DDCA_NON_TABLE_VCP_VALUE; valrec.val.c_nc.sh = (new_value >> 8) & 0xff; valrec.val.c_nc.sl = new_value & 0xff; if (verified_value_loc) { DDCA_Any_Vcp_Value * verified_single_value; rc = ddci_set_single_vcp_value(ddca_dh, &valrec, &verified_single_value); if (verified_single_value) *verified_value_loc = VALREC_CUR_VAL(verified_single_value); } else { rc = ddci_set_single_vcp_value(ddca_dh, &valrec, NULL); } return rc; } #ifdef REMOVED // DEPRECATED AS OF 0.9.0 /** Sets a Continuous VCP value. * * @param[in] ddca_dh display_handle * @param[in] feature_code VCP feature code * @param[in] new_value value to set (sign?) * @return status code * * @remark * This is essentially a convenience function, since a Continuous value * can be set by passing its high and low bytes to #ddca_set_non_table_vcp_value(). */ DDCA_Status ddca_set_continuous_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, uint16_t new_value) { bool debug = false; API_PROLOG(debug, "feature_code=0x%02x", feature_code); DDCA_Status ddcrc = ddci_set_continuous_vcp_value_verify(ddca_dh, feature_code, new_value, NULL); API_EPILOG_BEFORE_RETURN(debug, ddcrc, ""); return ddcrc; } #endif #ifdef REMOVED /** \deprecated */ DDCA_Status ddca_set_simple_nc_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, Byte new_value) { bool debug = false; API_PROLOG(debug, "feature_code=0x%02x", feature_code); DDCA_Status ddcrc = ddci_set_continuous_vcp_value_verify(ddca_dh, feature_code, new_value, NULL); API_EPILOG_BEFORE_RETURN(debug, ddcrc, ""); return ddcrc; } #endif // UNPUBLISHED /** Sets a non-table VCP value by specifying it's high and low bytes individually. * Optionally returns the values set by reading the feature code after writing. * * @param[in] ddca_dh display handle * @param[in] feature_code feature code * @param[in] hi_byte high byte of new value * @param[in] lo_byte low byte of new value * @param[out] p_verified_hi_byte where to return high byte of verified value * @param[out] p_verified_lo_byte where to return low byte of verified value * @return status code * * @remark * Either both **verified_hi_byte_loc** and **verified_lo_byte_loc** should be * set, or neither. Otherwise, status code **DDCRC_ARG** is returned. * @remark * Verification is performed only it has been enabled (see #ddca_enable_verify()) and * both **verified_hi_byte** and **verified_lo_byte** are set. * @remark * Verified values are returned if the status code is either 0 (success), * or **DDCRC_VERIFY**, i.e. the write succeeded but verification failed. */ static DDCA_Status ddci_set_non_table_vcp_value_verify( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, Byte hi_byte, Byte lo_byte, Byte * verified_hi_byte_loc, Byte * verified_lo_byte_loc) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, "ddca_dh=%p, feature_code=0x%02x, hi_byte=0x%02x, lo_byte=0x%02x", ddca_dh, feature_code, hi_byte, lo_byte); DDCA_Status rc = 0; free_thread_error_detail(); if ( ( verified_hi_byte_loc && !verified_lo_byte_loc) || (!verified_hi_byte_loc && verified_lo_byte_loc ) ) { rc = DDCRC_ARG; } else { // unwrap into 2 cases to clarify logic and avoid compiler warning if (verified_hi_byte_loc) { uint16_t verified_c_value = 0; rc = ddci_set_continuous_vcp_value_verify( ddca_dh, feature_code, hi_byte << 8 | lo_byte, &verified_c_value); *verified_hi_byte_loc = verified_c_value >> 8; *verified_lo_byte_loc = verified_c_value & 0xff; } else { rc = ddci_set_continuous_vcp_value_verify( ddca_dh, feature_code, hi_byte << 8 | lo_byte, NULL); } } DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, rc, ""); return rc; } DDCA_Status ddca_set_non_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, Byte hi_byte, Byte lo_byte) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_code=0x%02x", feature_code); DDCA_Status ddcrc = ddci_set_non_table_vcp_value_verify(ddca_dh, feature_code, hi_byte, lo_byte, NULL, NULL); API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, ddcrc, ""); return ddcrc; } // UNPUBLISHED /** Sets a table VCP value. * Optionally returns the value set by reading the feature code after writing. * * @param[in] ddca_dh display handle * @param[in] feature_code feature code * @param[in] new_value value to set * @param[out] verified_value_loc where to return verified value * @return status code * * @remark * Verification is performed only it has been enabled (see #ddca_enable_verify()) and * **verified_value** is set. * @remark * A verified value is returned if either the status code is either 0 (success), * or **DDCRC_VERIFY**, i.e. the write succeeded but verification failed. */ // untested static DDCA_Status ddci_set_table_vcp_value_verify( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Table_Vcp_Value * table_value, DDCA_Table_Vcp_Value ** verified_value_loc) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_API, "feature_code=0x%02x", feature_code); DDCA_Status rc = 0; DDCA_Any_Vcp_Value valrec; valrec.opcode = feature_code; valrec.value_type = DDCA_TABLE_VCP_VALUE; valrec.val.t.bytect = table_value->bytect; valrec.val.t.bytes = table_value->bytes; // copies pointer, not bytes if (verified_value_loc) { DDCA_Any_Vcp_Value * verified_single_value = NULL; rc = ddci_set_single_vcp_value(ddca_dh, &valrec, &verified_single_value); if (verified_single_value) { DDCA_Table_Vcp_Value * verified_table_value = calloc(1,sizeof(DDCA_Table_Vcp_Value)); verified_table_value->bytect = verified_single_value->val.t.bytect; verified_table_value->bytes = verified_single_value->val.t.bytes; free(verified_single_value); // n. does not free bytes *verified_value_loc = verified_table_value; } } else { rc = ddci_set_single_vcp_value(ddca_dh, &valrec, NULL); } DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, rc, ""); return rc; } DDCA_Status ddca_set_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Table_Vcp_Value * table_value) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_code=0x%02x", feature_code); DDCA_Status ddcrc = ddci_set_table_vcp_value_verify(ddca_dh, feature_code, table_value, NULL); API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, ddcrc, ""); return ddcrc; } // UNPUBLISHED /** Sets a VCP value of any type. * Optionally returns the values se by reading the feature code after writing. * * @param[in] ddca_dh display handle * @param[in] feature_code feature code * @param[in] new_value value to set * @param[out] verified_value where to return verified value * @return status code * * @remark * Verification is performed only it has been enabled (see #ddca_enable_verify()) and * **verified_value** is set. * @remark * A verified value is returned if either the status code is either 0 (success), * or **DDCRC_VERIFY**, i.e. the write succeeded but verification failed. */ // untested for table values static DDCA_Status ddci_set_any_vcp_value_verify( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Any_Vcp_Value * new_value, DDCA_Any_Vcp_Value ** verified_value_loc) { DDCA_Status rc = 0; if (verified_value_loc) { DDCA_Any_Vcp_Value * verified_single_value = NULL; rc = ddci_set_single_vcp_value(ddca_dh, new_value, &verified_single_value); if (verified_single_value) { *verified_value_loc = verified_single_value; // do in need to make a copy for client? } } else { rc = ddci_set_single_vcp_value(ddca_dh, new_value, NULL); } return rc; } DDCA_Status ddca_set_any_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Any_Vcp_Value * new_value) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "feature_code=0x%02x", feature_code); DDCA_Status ddcrc = ddci_set_any_vcp_value_verify(ddca_dh, feature_code, new_value, NULL); API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, ddcrc, ""); return ddcrc; } DDCA_Status ddca_get_profile_related_values( DDCA_Display_Handle ddca_dh, char** profile_values_string_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dh=%p, profile_values_string_loc=%p", ddca_dh, profile_values_string_loc); DDCA_Status psc = API_PRECOND_RVALUE(profile_values_string_loc); if (psc != 0) goto bye; WITH_VALIDATED_DH3(ddca_dh, psc, { psc = dumpvcp_as_string(dh, profile_values_string_loc); TRACED_ASSERT_IFF(psc==0, *profile_values_string_loc); DBGTRC_RET_DDCRC(debug, TRACE_GROUP, psc, "*profile_values_string_loc=%p -> %s", *profile_values_string_loc, *profile_values_string_loc); } ); bye: API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, psc, ""); return psc; } DDCA_Status ddca_set_profile_related_values( DDCA_Display_Handle ddca_dh, char * profile_values_string) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_h=%p, profile_values_string = %s", ddca_dh, profile_values_string); DDCA_Status psc = 0; WITH_VALIDATED_DH3(ddca_dh, psc, { Error_Info * ddc_excp = loadvcp_by_string(profile_values_string, dh); psc = (ddc_excp) ? ddc_excp->status_code : 0; if (ddc_excp) { save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); errinfo_free(ddc_excp); } DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, ""); } ); API_EPILOG_BEFORE_RETURN(debug, RESPECT_QUIESCE, psc, ""); return psc; } #ifdef REMOVED // // Vestiges of old experimental async API. // Never published, retained for ABI compatibility. // DDCA_Status ddca_start_get_any_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code, DDCA_Vcp_Value_Type call_type, DDCA_Notification_Func callback_func) { return DDCRC_UNIMPLEMENTED; } DDCA_Status ddca_register_callback( DDCA_Notification_Func func, uint8_t callback_options) // type is a placeholder { return DDCRC_UNIMPLEMENTED; } DDCA_Status ddca_queue_get_non_table_vcp_value( DDCA_Display_Handle ddca_dh, DDCA_Vcp_Feature_Code feature_code) { return DDCRC_UNIMPLEMENTED; } #endif #ifdef REMOVED // // CFFI // DDCA_Status ddca_pass_callback( Simple_Callback_Func func, int parm) { DBGMSG("parm=%d", parm); int callback_rc = func(parm+2); DBGMSG("returning %d", callback_rc); return callback_rc; } #endif #ifdef FUTURE // which header file would this go in? void init_api_access_feature_codes() { rtti_func_name_table_add(ddci_format_any_vcp_value, "dyn_format_nontable_feature_detail_dfm"); // dbgrpt_func_name_table(0); } #endif void init_api_feature_access() { // DBGMSG("Executing"); RTTI_ADD_FUNC(ddca_get_non_table_vcp_value); RTTI_ADD_FUNC(ddca_set_non_table_vcp_value); RTTI_ADD_FUNC(ddci_set_single_vcp_value); } ddcutil-2.2.0/src/libmain/api_capabilities.c0000644000175000001440000004636014754153540014471 /** api_capabilities.c * * Capabilities related functions of the API */ // Copyright (C) 2015-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #include #include #include #include #include #include "public/ddcutil_c_api.h" #include "public/ddcutil_status_codes.h" #include "util/error_info.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/ddc_command_codes.h" #include "base/displays.h" #include "base/feature_metadata.h" #include "base/rtti.h" #include "base/vcp_version.h" #include "vcp/parse_capabilities.h" #include "vcp/parsed_capabilities_feature.h" #include "vcp/vcp_feature_codes.h" #include "dynvcp/dyn_feature_codes.h" #include "dynvcp/dyn_parsed_capabilities.h" #include "ddc/ddc_read_capabilities.h" #include "ddc/ddc_vcp_version.h" #include "libmain/api_base_internal.h" #include "libmain/api_displays_internal.h" #include "libmain/api_metadata_internal.h" #include "libmain/api_error_info_internal.h" #include "libmain/api_capabilities_internal.h" // // Monitor Capabilities // DDCA_Status ddca_get_capabilities_string( DDCA_Display_Handle ddca_dh, char** pcaps_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "ddca_dh=%s", dh_repr((Display_Handle *) ddca_dh ) ); API_PRECOND_W_EPILOG(pcaps_loc); *pcaps_loc = NULL; Error_Info * ddc_excp = NULL; DDCA_Status psc = 0; WITH_VALIDATED_DH3(ddca_dh, psc, { char * p_cap_string = NULL; ddc_excp = ddc_get_capabilities_string(dh, &p_cap_string); psc = (ddc_excp) ? ddc_excp->status_code : 0; save_thread_error_detail(error_info_to_ddca_detail(ddc_excp)); errinfo_free(ddc_excp); if (psc == 0) { // make copy to prevent caller from mucking around in ddcutil's // internal data structures *pcaps_loc = g_strdup(p_cap_string); } ASSERT_IFF(psc==0, *pcaps_loc); } ); #ifdef TMI API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, psc, "ddca_dh=%s, *pcaps_loc=%p -> |%s|", dh_repr((Display_Handle *) ddca_dh), *pcaps_loc, *pcaps_loc ); #endif API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, psc, "ddca_dh=%s, *pcaps_loc=%p", dh_repr((Display_Handle *) ddca_dh), *pcaps_loc ); } #ifdef UNUSED void dbgrpt_ddca_cap_vcp(DDCA_Cap_Vcp * cap, int depth) { rpt_structure_loc("DDCA_Cap_Vcp", cap, depth); int d1 = depth+1; int d2 = depth+2; rpt_vstring(d1, "feature code: 0x%02x", cap->feature_code); rpt_vstring(d1, "value_ct: %d", cap->value_ct); if (cap->value_ct > 0) { rpt_label(d1, "Values: "); for (int ndx = 0; ndx < cap->value_ct; ndx++) { rpt_vstring(d2, "Value: 0x%02x", cap->values[ndx]); } } } #endif #ifdef UNUSED void dbgrpt_ddca_capabilities(DDCA_Capabilities * p_caps, int depth) { rpt_structure_loc("DDCA_Capabilities", p_caps, depth); int d1 = depth+1; int d2 = depth+2; rpt_vstring(d1, "Unparsed string: %s", p_caps->unparsed_string); rpt_vstring(d1, "Version spec: %d.%d", p_caps->version_spec.major, p_caps->version_spec.minor); rpt_label(d1, "Command codes:"); for (int ndx = 0; ndx < p_caps->cmd_ct; ndx++) { rpt_vstring(d2, "0x%02x", p_caps->cmd_codes[ndx]); } rpt_vstring(d1, "Feature code count: %d", p_caps->vcp_code_ct); for (int ndx = 0; ndx < p_caps->vcp_code_ct; ndx++) { DDCA_Cap_Vcp * cur = &p_caps->vcp_codes[ndx]; dbgrpt_ddca_cap_vcp(cur, d2); } rpt_vstring(d1, "msg_ct: %d", p_caps->msg_ct); if (p_caps->msg_ct > 0) { rpt_label(d1, "messages: "); for (int ndx = 0; ndx < p_caps->msg_ct; ndx++) { rpt_vstring(d2, "Message: %s", p_caps->messages[ndx]); } } } #endif DDCA_Status ddca_parse_capabilities_string( char * capabilities_string, DDCA_Capabilities ** parsed_capabilities_loc) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, NORESPECT_QUIESCE, "parsed_capabilities_loc=%p, capabilities_string: |%s|", parsed_capabilities_loc, capabilities_string); API_PRECOND_W_EPILOG(parsed_capabilities_loc); DDCA_Status ddcrc = DDCRC_BAD_DATA; DDCA_Capabilities * result = NULL; // need to control messages? Parsed_Capabilities * pcaps = parse_capabilities_string(capabilities_string); if (pcaps) { if (debug) { DBGMSG("Parsing succeeded: "); dyn_report_parsed_capabilities(pcaps, NULL, NULL, 2); DBGMSG("Convert to DDCA_Capabilities..."); } result = calloc(1, sizeof(DDCA_Capabilities)); memcpy(result->marker, DDCA_CAPABILITIES_MARKER, 4); result->unparsed_string = g_strdup(capabilities_string); // needed? result->version_spec = pcaps->parsed_mccs_version; DBGMSF(debug, "version: %d.%d", result->version_spec.major, result->version_spec.minor); Byte_Value_Array bva = pcaps->commands; if (bva) { result->cmd_ct = bva_length(bva); result->cmd_codes = malloc(result->cmd_ct); memcpy(result->cmd_codes, bva_bytes(bva), result->cmd_ct); } // n. needen't set vcp_code_ct if !pcaps, calloc() has done it if (pcaps->vcp_features) { result->vcp_code_ct = pcaps->vcp_features->len; result->vcp_codes = calloc(result->vcp_code_ct, sizeof(DDCA_Cap_Vcp)); DBGMSF(debug, "allocate %d bytes at %p", result->vcp_code_ct * sizeof(DDCA_Cap_Vcp), result->vcp_codes); for (int ndx = 0; ndx < result->vcp_code_ct; ndx++) { DDCA_Cap_Vcp * cur_cap_vcp = &result->vcp_codes[ndx]; DBGMSF(debug, "cur_cap_vcp = %p", &result->vcp_codes[ndx]); memcpy(cur_cap_vcp->marker, DDCA_CAP_VCP_MARKER, 4); Capabilities_Feature_Record * cur_cfr = g_ptr_array_index(pcaps->vcp_features, ndx); DBGMSF(debug, "Capabilities_Feature_Record * cur_cfr = %p", cur_cfr); assert(memcmp(cur_cfr->marker, CAPABILITIES_FEATURE_MARKER, 4) == 0); if (debug) dbgrpt_capabilities_feature_record(cur_cfr, 2); // show_capabilities_feature(cur_cfr, result->version_spec); cur_cap_vcp->feature_code = cur_cfr->feature_id; DBGMSF(debug, "cur_cfr = %p, feature_code - 0x%02x", cur_cfr, cur_cfr->feature_id); // cur_cap_vcp->raw_values = g_strdup(cur_cfr->value_string); // TODO: get values from Byte_Bit_Flags cur_cfr->bbflags #ifdef CFR_BVA Byte_Value_Array bva = cur_cfr->values; if (bva) { cur_cap_vcp->value_ct = bva_length(bva); cur_cap_vcp->values = calloc( cur_cap_vcp->value_ct, sizeof(Byte)); memcpy(cur_cap_vcp->values, bva_bytes(bva), cur_cap_vcp->value_ct); } #endif #ifdef CFR_BBF if (cur_cfr->bbflags) { cur_cap_vcp->value_ct = bbf_count_set(cur_cfr->bbflags); cur_cap_vcp->values = calloc(1, cur_cap_vcp->value_ct); bbf_to_bytes(cur_cfr->bbflags, cur_cap_vcp->values, cur_cap_vcp->value_ct); } #endif } } // DBGMSG("pcaps->messages = %p", pcaps->messages); // if (pcaps->messages) { // DBGMSG("pcaps->messages->len = %d", pcaps->messages->len); // } if (pcaps->messages && pcaps->messages->len > 0) { result->msg_ct = pcaps->messages->len; result->messages = g_ptr_array_to_ntsa(pcaps->messages, /*duplicate=*/ true); } ddcrc = 0; free_parsed_capabilities(pcaps); } *parsed_capabilities_loc = result; API_EPILOG_BEFORE_RETURN(debug, NORESPECT_QUIESCE, ddcrc, "*parsed_capabilities_loc=%p", *parsed_capabilities_loc); ASSERT_IFF(ddcrc==0, *parsed_capabilities_loc); // if ( IS_DBGTRC(debug, DDCA_TRC_API) && *parsed_capabilities_loc) #ifdef TMI if (is_traced_api_call(__func__) && *parsed_capabilities_loc) dbgrpt_ddca_capabilities(*parsed_capabilities_loc, 2); #endif return ddcrc; } void ddca_free_parsed_capabilities( DDCA_Capabilities * pcaps) { bool debug = false; reset_current_traced_function_stack(); DBGTRC_STARTING(debug, DDCA_TRC_API, "pcaps=%p", pcaps); if (pcaps) { assert(memcmp(pcaps->marker, DDCA_CAPABILITIES_MARKER, 4) == 0); free(pcaps->unparsed_string); DBGMSF(debug, "vcp_code_ct = %d", pcaps->vcp_code_ct); for (int ndx = 0; ndx < pcaps->vcp_code_ct; ndx++) { DDCA_Cap_Vcp * cur_vcp = &pcaps->vcp_codes[ndx]; assert(memcmp(cur_vcp->marker, DDCA_CAP_VCP_MARKER, 4) == 0); cur_vcp->marker[3] = 'x'; free(cur_vcp->values); } free(pcaps->vcp_codes); free(pcaps->cmd_codes); ntsa_free(pcaps->messages, true); pcaps->marker[3] = 'x'; free(pcaps); } DBGTRC_DONE(debug, DDCA_TRC_API, ""); } #ifdef OLD DDCA_Status ddca_report_parsed_capabilities_by_dref( DDCA_Capabilities * p_caps, DDCA_Display_Ref ddca_dref, int depth) { bool debug = false; DDCA_Status ddcrc = 0; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "Starting. p_caps=%p", // ddca_dref=%s", p_caps); // , dref_repr_t((Display_Ref*) ddca_dref)); API_PRECOND_W_EPILOG(p_caps); // no need to check marker, DDCA_CAPABILITIES not opaque Display_Ref * dref = NULL; // dref may be NULL, but if not it must be valid if (ddca_dref) { dref = dref_from_published_ddca_dref(ddca_dref); // DREF_VALIDAT_BASIC_ONLY? ddcrc = (dref) ? ddc_validate_display_ref2(dref, DREF_VALIDATE_BASIC_ONLY) : DDCRC_ARG; if (ddcrc != 0) { goto bye; } } int d0 = depth; int d1 = depth+1; int d2 = depth+2; int d3 = depth+3; DDCA_Output_Level ol = get_output_level(); if (ol >= DDCA_OL_VERBOSE) rpt_vstring(d0, "Unparsed string: %s", p_caps->unparsed_string); char * s = NULL; if (vcp_version_eq(p_caps->version_spec, DDCA_VSPEC_UNQUERIED)) s = "Not present"; else if (vcp_version_eq(p_caps->version_spec, DDCA_VSPEC_UNKNOWN)) s = "Invalid value"; else s = format_vspec(p_caps->version_spec); rpt_vstring(d0, "VCP version: %s", s); if (ol >= DDCA_OL_VERBOSE) { rpt_label (d0, "Command codes: "); for (int cmd_ndx = 0; cmd_ndx < p_caps->cmd_ct; cmd_ndx++) { uint8_t cur_code = p_caps->cmd_codes[cmd_ndx]; char * cmd_name = ddc_cmd_code_name(cur_code); rpt_vstring(d1, "0x%02x (%s)", cur_code, cmd_name); } } rpt_vstring(d0, "VCP Feature codes:"); for (int code_ndx = 0; code_ndx < p_caps->vcp_code_ct; code_ndx++) { DDCA_Cap_Vcp * cur_vcp = &p_caps->vcp_codes[code_ndx]; assert( memcmp(cur_vcp->marker, DDCA_CAP_VCP_MARKER, 4) == 0); Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dref( cur_vcp->feature_code, dref, true, // check_udf true); // create_default_if_not_found); assert(dfm); // dbgrpt_display_feature_metadata(dfm, 3); rpt_vstring(d1, "Feature: 0x%02x (%s)", cur_vcp->feature_code, dfm->feature_name); if (cur_vcp->value_ct > 0) { if (ol > DDCA_OL_VERBOSE) rpt_vstring(d2, "Unparsed values: %s", hexstring_t(cur_vcp->values, cur_vcp->value_ct) ); DDCA_Feature_Value_Entry * feature_value_table = dfm->sl_values; rpt_label(d2, "Values:"); for (int ndx = 0; ndx < cur_vcp->value_ct; ndx++) { char * value_desc = "No lookup table"; if (feature_value_table) { value_desc = sl_value_table_lookup(feature_value_table, cur_vcp->values[ndx]); if (!value_desc) value_desc = "Unrecognized feature value"; } rpt_vstring(d3, "0x%02x: %s", cur_vcp->values[ndx], value_desc); } } dfm_free(dfm); } // one feature code if (p_caps->messages && *p_caps->messages) { rpt_nl(); rpt_label(d0, "Parsing errors:"); char ** m = p_caps->messages; while (*m) { rpt_label(d1, *m); m++; } } else { DBGMSF(debug, "No error messages"); } bye: API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, ddcrc, ""); } #endif DDCA_Status ddci_report_parsed_capabilities_by_dref( DDCA_Capabilities * p_caps, Display_Ref * dref, int depth) { bool debug = true; DBGTRC_STARTING(debug, DDCA_TRC_API, ""); int d0 = depth; int d1 = depth+1; int d2 = depth+2; int d3 = depth+3; DDCA_Status ddcrc = 0; DDCA_Output_Level ol = get_output_level(); if (ol >= DDCA_OL_VERBOSE) rpt_vstring(d0, "Unparsed string: %s", p_caps->unparsed_string); char * s = NULL; if (vcp_version_eq(p_caps->version_spec, DDCA_VSPEC_UNQUERIED)) s = "Not present"; else if (vcp_version_eq(p_caps->version_spec, DDCA_VSPEC_UNKNOWN)) s = "Invalid value"; else s = format_vspec(p_caps->version_spec); rpt_vstring(d0, "VCP version: %s", s); if (ol >= DDCA_OL_VERBOSE) { rpt_label (d0, "Command codes: "); for (int cmd_ndx = 0; cmd_ndx < p_caps->cmd_ct; cmd_ndx++) { uint8_t cur_code = p_caps->cmd_codes[cmd_ndx]; char * cmd_name = ddc_cmd_code_name(cur_code); rpt_vstring(d1, "0x%02x (%s)", cur_code, cmd_name); } } rpt_vstring(d0, "VCP Feature codes:"); for (int code_ndx = 0; code_ndx < p_caps->vcp_code_ct; code_ndx++) { DDCA_Cap_Vcp * cur_vcp = &p_caps->vcp_codes[code_ndx]; assert( memcmp(cur_vcp->marker, DDCA_CAP_VCP_MARKER, 4) == 0); Display_Feature_Metadata * dfm = dyn_get_feature_metadata_by_dref( cur_vcp->feature_code, dref, true, // check_udf true); // create_default_if_not_found); assert(dfm); // dbgrpt_display_feature_metadata(dfm, 3); rpt_vstring(d1, "Feature: 0x%02x (%s)", cur_vcp->feature_code, dfm->feature_name); if (cur_vcp->value_ct > 0) { if (ol > DDCA_OL_VERBOSE) rpt_vstring(d2, "Unparsed values: %s", hexstring_t(cur_vcp->values, cur_vcp->value_ct) ); DDCA_Feature_Value_Entry * feature_value_table = dfm->sl_values; rpt_label(d2, "Values:"); for (int ndx = 0; ndx < cur_vcp->value_ct; ndx++) { char * value_desc = "No lookup table"; if (feature_value_table) { value_desc = sl_value_table_lookup(feature_value_table, cur_vcp->values[ndx]); if (!value_desc) value_desc = "Unrecognized feature value"; } rpt_vstring(d3, "0x%02x: %s", cur_vcp->values[ndx], value_desc); } } dfm_free(dfm); } // one feature code if (p_caps->messages && *p_caps->messages) { rpt_nl(); rpt_label(d0, "Parsing errors:"); char ** m = p_caps->messages; while (*m) { rpt_label(d1, *m); m++; } } else { DBGMSF(debug, "No error messages"); } DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, ddcrc, ""); return ddcrc; } DDCA_Status ddca_report_parsed_capabilities_by_dref( DDCA_Capabilities * p_caps, DDCA_Display_Ref ddca_dref, int depth) { bool debug = false; DDCA_Status ddcrc = 0; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "Starting. p_caps=%p", // ddca_dref=%s", p_caps); // , dref_repr_t((Display_Ref*) ddca_dref)); API_PRECOND_W_EPILOG(p_caps); // no need to check marker, DDCA_CAPABILITIES not opaque Display_Ref * dref = NULL; // dref may be NULL, but if not it must be valid if (ddca_dref) { dref = dref_from_published_ddca_dref(ddca_dref); ddcrc = (dref) ? ddc_validate_display_ref2(dref, DREF_VALIDATE_BASIC_ONLY) : DDCRC_ARG; } if (ddcrc == 0) { ddcrc = ddci_report_parsed_capabilities_by_dref(p_caps, dref, depth); } API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, ddcrc, ""); } void ddca_report_parsed_capabilities( DDCA_Capabilities * p_caps, int depth) { ddci_report_parsed_capabilities_by_dref(p_caps, NULL, depth); } DDCA_Status ddca_report_parsed_capabilities_by_dh( DDCA_Capabilities * p_caps, DDCA_Display_Handle ddca_dh, int depth) { bool debug = false; free_thread_error_detail(); API_PROLOGX(debug, RESPECT_QUIESCE, "p_caps=%p, ddca_dh=%s, depth=%d", p_caps, ddca_dh_repr(ddca_dh), depth); DDCA_Status ddcrc = 0; Display_Handle * dh = (Display_Handle *) ddca_dh; if (dh == NULL || memcmp(dh->marker, DISPLAY_HANDLE_MARKER, 4) != 0 ) { ddcrc = DDCRC_ARG; goto bye; } // Ensure dh->dref->vcp_version is not unqueried, // ddca_report_parsed_capabilities_by_dref() will fail trying to lock the already open device get_vcp_version_by_dh(dh); DBGMSF(debug, "After get_vcp_version_by_dh(), dh->dref->vcp_version_df=%s", format_vspec_verbose(dh->dref->vcp_version_xdf)); ddci_report_parsed_capabilities_by_dref(p_caps, dh->dref, depth); bye: API_EPILOG_RET_DDCRC(debug, RESPECT_QUIESCE, ddcrc, ""); } #ifdef UNPUBLISHED // UNPUBLISHED /** Parses a capabilities string, and reports the parsed string * using the code of command "ddcutil capabilities". * * The report is written to the current FOUT location. * * The detail level written is sensitive to the current output level. * * @param[in] capabilities_string capabilities string * @param[in] dref display reference * @param[in] depth logical indentation depth * * @remark * This function exists as a development aide. Internally, ddcutil uses * a different data structure than DDCA_Parsed_Capabilities. That * data structure uses internal collections that are not exposed at the * API level. * @remark * Signature changed in 0.9.3 * @since 0.9.0 */ void ddca_parse_and_report_capabilities( char * capabilities_string, DDCA_Display_Ref dref, int depth); // UNPUBLISHED void ddca_parse_and_report_capabilities( char * capabilities_string, DDCA_Display_Ref dref, int depth) { Parsed_Capabilities* pcaps = parse_capabilities_string(capabilities_string); dyn_report_parsed_capabilities(pcaps, NULL, dref, 0); free_parsed_capabilities(pcaps); } #endif DDCA_Feature_List ddca_feature_list_from_capabilities( DDCA_Capabilities * parsed_caps) { DDCA_Feature_List result = {{0}}; for (int ndx = 0; ndx < parsed_caps->vcp_code_ct; ndx++) { DDCA_Cap_Vcp curVcp = parsed_caps->vcp_codes[ndx]; ddca_feature_list_add(&result, curVcp.feature_code); } return result; } void init_api_capabilities() { RTTI_ADD_FUNC(ddca_free_parsed_capabilities); RTTI_ADD_FUNC(ddca_get_capabilities_string); RTTI_ADD_FUNC(ddca_parse_capabilities_string); RTTI_ADD_FUNC(ddci_report_parsed_capabilities_by_dref); RTTI_ADD_FUNC(ddca_report_parsed_capabilities_by_dref); RTTI_ADD_FUNC(ddca_report_parsed_capabilities_by_dh); } ddcutil-2.2.0/src/libmain/api_services_internal.c0000644000175000001440000000101014607466566015552 /** @file api_services_internal.c */ // Copyright (C) 2021-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include "base/core.h" #include "api_capabilities_internal.h" #include "api_displays_internal.h" #include "api_feature_access_internal.h" #include "api_metadata_internal.h" #include "api_services_internal.h" void init_api_services() { init_api_capabilities(); init_api_displays(); init_api_feature_access(); init_api_metadata(); } ddcutil-2.2.0/src/libmain/api_feature_access_internal.h0000644000175000001440000000076114754576332016720 /** @file api_feature_access_internal.h * * Contains declarations of functions used only by other api_... files, * and of otherwise unpublished and archived functions. */ // Copyright (C) 2015-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef API_FEATURE_ACCESS_INTERNAL_H_ #define API_FEATURE_ACCESS_INTERNAL_H_ // here because there's no api_feature_access.h void init_api_feature_access(); #endif /* API_FEATURE_ACCESS_INTERNAL_H_ */ ddcutil-2.2.0/src/libmain/api_services_internal.h0000644000175000001440000000041614754576332015564 // api_services_intenral.h // Copyright (C) 2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef API_SERVICES_INTERNAL_H_ #define API_SERVICES_INTERNAL_H_ void init_api_services(); #endif /* API_SERVICES_INTERNAL_H_ */ ddcutil-2.2.0/src/libmain/api_error_info_internal.h0000644000175000001440000000144114754576332016104 // api_error_info_internal.h // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef API_ERROR_INFO_INTERNAL_H_ #define API_ERROR_INFO_INTERNAL_H_ #include "ddcutil_types.h" #include "util/error_info.h" DDCA_Error_Detail * new_ddca_error_detail(DDCA_Status ddcrc, const char * format, ...); DDCA_Error_Detail * error_info_to_ddca_detail(Error_Info * erec); DDCA_Error_Detail * dup_error_detail(DDCA_Error_Detail * old); void free_error_detail(DDCA_Error_Detail * ddca_erec); void report_error_detail(DDCA_Error_Detail * ddca_erec, int depth); void free_thread_error_detail(); DDCA_Error_Detail * get_thread_error_detail(); void save_thread_error_detail(DDCA_Error_Detail * error_detail); #endif /* API_ERROR_INFO_INTERNAL_H_ */ ddcutil-2.2.0/src/libmain/api_metadata_internal.h0000644000175000001440000001256314754576332015527 // api_metadata.h // Copyright (C) 2018-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef API_METADATA_INTERNAL_H_ #define API_METADATA_INTERNAL_H_ #include "ddcutil_status_codes.h" #include "ddcutil_types.h" // needed by api_capabilities.c: #ifdef DUPLICATE DDCA_Status ddca_get_simple_sl_value_table_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, const DDCA_Monitor_Model_Key * p_mmid, // currently ignored DDCA_Feature_Value_Entry** value_table_loc); #endif #ifdef UNUSED DDCA_Status ddca_get_simple_nc_feature_value_name_by_table( DDCA_Feature_Value_Entry * feature_value_table, uint8_t feature_value, char** value_name_loc); #endif // Feature Lists #ifdef NEVER_PUBLISHED // NEVER PUBLISHED, USED INTERNALLY /** Given a feature set id, returns a #DDCA_Feature_List specifying all the * feature codes in the set. * * @param[in] feature_set_id * @param[in] vcp_version * @param[in] include_table_features if true, Table type features are included * @param[out] points to feature list to be filled in * * @since 0.9.0 */ DDCA_Status ddca_get_feature_list( DDCA_Feature_Subset_Id feature_set_id, DDCA_MCCS_Version_Spec vcp_version, bool include_table_features, DDCA_Feature_List* p_feature_list); #endif #ifdef UNUSED // NEVER PUBLISHED /** Gets the value id/name table of the allowed values for a simple NC feature. * * @param[in] vspec MCCS version * @param[in] feature_code VCP feature code * @param[in] feature_value single byte feature value * @param[out] feature_name_loc where to return feature name * @return status code * * @remark * If the feature value cannot be found in the lookup table for * the specified MCCS version, tables for later versions, if they * exist, are checked as well. * * @since 0.9.0 */ DDCA_Status ddca_get_simple_nc_feature_value_name_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, const DDCA_Monitor_Model_Key * p_mmid, uint8_t feature_value, char** feature_name_loc); #endif #ifdef UNUSED // UNPUBLISHED, USED INTERNALLY /** Gets the value id/name table of the allowed values for a simple NC feature. * * @param[in] feature_code VCP feature code * @param[in] vspec MCCS version * @param[in] p_mmid pointer to monitor model identifier, may be NULL * @param[out] value_table_loc where to return pointer to array of DDCA_Feature_Value_Entry * @return status code * @retval 0 success * @retval DDCRC_UNKNOWN_FEATURE unrecognized feature code * @retval DDCRC_INVALID_OPERATION feature not simple NC * *@remark p_mmid currently ignored * @since 0.9.0 */ DDCA_Status ddca_get_simple_sl_value_table_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, const DDCA_Monitor_Model_Key * p_mmid, // currently ignored DDCA_Feature_Value_Entry** value_table_loc); #endif // // Metadata // #ifdef UNIMPLEMENTED // Unimplemented // alt: can check status code for ddca_get_feature_info_by_dh() DDCA_Status ddca_is_feature_supported( DDCA_Display_Handle dh, DDCA_Vcp_Feature_Code feature_code, bool * answer_loc); // or return status code? #endif #ifdef UNUSED // UNPUBLISHED /** Gets the value id/name table of the allowed values for a simple NC feature. * * @param[in] feature_code VCP feature code * @param[in] dref display reference * @param[out] value_table_loc where to return pointer to array of DDCA_Feature_Value_Entry * @return status code * @retval 0 success * @retval DDCRC_UNKNOWN_FEATURE unrecognized feature code * @retval DDCRC_INVALID_OPERATION feature not simple NC * * @since 0.9.0 */ DDCA_Status ddca_get_simple_sl_value_table_by_dref( DDCA_Vcp_Feature_Code feature_code, DDCA_Display_Ref dref, DDCA_Feature_Value_Entry** value_table_loc); #endif // New master functions for feature metadata // Granular functions for metadata #ifdef UNUSED // NEVER PUBLISHED // used in ddcui // returns pointer into permanent internal data structure, caller should not free /** Gets the VCP feature name, which may vary by MCCS version. * * @param[in] feature_code feature code * @param[in] vspec MCCS version * @param[in] p_mmid pointer to monitor model identifier, may be null * @return pointer to feature name (do not free), NULL if unknown feature code * * @remark **p_mmid** currently ignored * @since 0.9.0 */ char * ddca_feature_name_by_vspec( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, DDCA_Monitor_Model_Key * p_mmid); #endif // DEPRECATED IN 0.9.0 #ifdef UNUSED // /** \deprecated */ __attribute__ ((deprecated)) DDCA_Status ddca_get_simple_nc_feature_value_name_by_display( DDCA_Display_Handle ddca_dh, // needed because value lookup mccs version dependent DDCA_Vcp_Feature_Code feature_code, uint8_t feature_value, char** feature_name_loc); #endif void init_api_metadata(); #endif /* API_METADATA_INTERNAL_H_ */ ddcutil-2.2.0/src/libmain/api_base_internal.h0000644000175000001440000004677314754576332014673 /** @file api_base_internal.h * * For use only by other api_... files */ // Copyright (C) 2015-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef API_BASE_INTERNAL_H_ #define API_BASE_INTERNAL_H_ #include "config.h" #include #include #include // #include // requires glibc 2.28, header file apparently not used #include "public/ddcutil_status_codes.h" #include "public/ddcutil_c_api.h" #include "base/per_thread_data.h" #include "libmain/api_error_info_internal.h" extern bool library_initialized; extern bool library_initialization_failed; #define DDCI_PRECOND_STDERR 0x01 #define DDCI_PRECOND_RETURN 0x02 typedef enum { DDCI_PRECOND_STDERR_ABORT = DDCI_PRECOND_STDERR, DDCI_PRECOND_STDERR_RETURN = DDCI_PRECOND_STDERR | DDCI_PRECOND_RETURN, DDCI_PRECOND_RETURN_ONLY = DDCI_PRECOND_RETURN } DDCI_Api_Precondition_Failure_Mode; extern DDCI_Api_Precondition_Failure_Mode api_failure_mode; DDCA_Status ddci_init(const char * libopts, DDCA_Syslog_Level syslog_level_arg, DDCA_Init_Options opts, char*** infomsg_loc); #define API_PRECOND(expr) \ do { \ if (!(expr)) { \ SYSLOG2(DDCA_SYSLOG_ERROR, "Precondition failed: \"%s\" in file %s at line %d", \ #expr, __FILE__, __LINE__); \ if (api_failure_mode & DDCI_PRECOND_STDERR) { \ DBGTRC_NOPREFIX(true, DDCA_TRC_ALL, "Precondition failure (%s) in function %s at line %d of file %s", \ #expr, __func__, __LINE__, __FILE__); \ fprintf(stderr, "Precondition failure (%s) in function %s at line %d of file %s\n", \ #expr, __func__, __LINE__, __FILE__); \ } \ if (api_failure_mode & DDCI_PRECOND_RETURN) \ return DDCRC_ARG; \ /* __assert_fail(#expr, __FILE__, __LINE__, __func__); */ \ abort(); \ } \ } while (0) // The return value must be contained in variable result instead of // being passed as a constant to DBGTRC_RET_DDCRC() because, // if failure simulation is enabled, the fsim_int_injector() // function in macro DBGTRC_RET_DDCRC() assigns a (possibly new) // value to variable holding the return value. #define API_PRECOND_W_EPILOG(expr) \ do { \ if (!(expr)) { \ SYSLOG2(DDCA_SYSLOG_ERROR, "Precondition failed: \"%s\" in file %s at line %d", \ #expr, __FILE__, __LINE__); \ if (api_failure_mode & DDCI_PRECOND_STDERR) { \ DBGTRC_NOPREFIX(true, DDCA_TRC_ALL, "Precondition failure (%s) in function %s at line %d of file %s", \ #expr, __func__, __LINE__, __FILE__); \ fprintf(stderr, "Precondition failure (%s) in function %s at line %d of file %s\n", \ #expr, __func__, __LINE__, __FILE__); \ } \ if (!(api_failure_mode & DDCI_PRECOND_RETURN)) \ abort(); \ trace_api_call_depth--; \ int result = DDCRC_ARG; \ DBGTRC_RET_DDCRC(true, DDCA_TRC_ALL, result, "Precondition failure: %s=NULL", (expr)); \ return result; \ } \ } while (0) #define API_PRECOND_RVALUE(expr) \ ( { DDCA_Status ddcrc = 0; \ if (!(expr)) { \ SYSLOG2(DDCA_SYSLOG_ERROR, "Precondition failed: \"%s\" in file %s at line %d", \ #expr, __FILE__, __LINE__); \ if (api_failure_mode & DDCI_PRECOND_STDERR) { \ DBGTRC_NOPREFIX(true, DDCA_TRC_ALL, "Precondition failure (%s) in function %s at line %d of file %s", \ #expr, __func__, __LINE__, __FILE__); \ fprintf(stderr, "Precondition failure (%s) in function %s at line %d of file %s\n", \ #expr, __func__, __LINE__, __FILE__); \ } \ if (!(api_failure_mode & DDCI_PRECOND_RETURN)) \ abort(); \ ddcrc = DDCRC_ARG; \ } \ ddcrc; \ } ) #ifdef UNUSED #define API_PRECOND_NORC(expr) \ do { \ if (!(expr)) { \ SYSLOG(LOG_ERR, "Precondition failed: \"%s\" in file %s at line %d", \ #expr, __FILE__, __LINE__); \ if (api_failure_mode & DDCI_PRECOND_STDERR) \ fprintf(stderr, "Precondition failure (%s) in function %s at line %d of file %s\n", \ #expr, __func__, __LINE__, __FILE__); \ if (api_failure_mode & DDCI_PRECOND_RETURN) \ return; \ abort(); \ } \ } while (0) #endif // // Precondition Failure Mode // #ifdef OUT DDCA_Api_Precondition_Failure_Mode ddci_set_precondition_failure_mode( DDCA_Api_Precondition_Failure_Mode failure_mode); DDCA_Api_Precondition_Failure_Mode ddci_get_precondition_failure_mode(); #endif #ifdef UNUSED #define ENSURE_LIBRARY_INITIALIZED() \ do { \ if (!library_initialized) { \ ddca_init(DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE); \ } \ } while (0) #endif // // API Quiesce Management // bool increment_active_api_calls(const char * funcname); void decrement_active_api_calls(const char * funcname); void quiesce_api(); void unquiesce_api(); #define RESPECT_QUIESCE true #define NORESPECT_QUIESCE false // // Function prologs and epilogs // /** API function prolog for functions that don't return a status code. * * Similar to API_PROLOGX(), except that there is no test if explicit * library initialization failed. */ #define API_PROLOG(debug_flag, format, ...) \ do { \ if (!library_initialized) { \ syslog(LOG_WARNING, "%s called before ddca_init2() or ddca_init()", __func__); \ ddci_init(NULL, DEFAULT_LIBDDCUTIL_SYSLOG_LEVEL, DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE, NULL); \ } \ reset_current_traced_function_stack(); \ push_traced_function(__func__); \ if (trace_api_call_depth > 0 || is_traced_api_call(__func__) ) \ trace_api_call_depth++; \ dbgtrc( (debug_flag) ? DDCA_TRC_ALL : DDCA_TRC_API, DBGTRC_OPTIONS_STARTING, \ __func__, __LINE__, __FILE__, "Starting "format, ##__VA_ARGS__); \ if (ptd_api_profiling_enabled) ptd_profile_function_start(__func__); \ } while(0) /** Standard API function prolog * * @param debug_flag if true, always perform function tracing * if false, only trace if API tracing is enabled * @param format trace message format string * @param ... trace message arguments * * If explicit library initialization failed, write a message to the system log, * save an explanation in the thread error detail, and return from the function * immediately with status DDCRC_INITIALIZED. * * If the library is uninitialized, but ddca_init2() or ddca_init() was not called, * write a message to the system log and perform implicit library initialization. * * If this API function is being traced, or it was called by another API function * that is being traced, increment thread local variable trace_api_call_depth. * * Call dbgtrc() to perform function tracing, if enabled for this function. * * If profiling is enabled for this thread, start profiling for this function. */ #define API_PROLOGX(debug_flag, respect_quiesced, format, ...) \ do { \ if (library_initialization_failed) { \ syslog(LOG_CRIT, "%s called after ddca_init2() or ddca_init() failure", __func__); \ save_thread_error_detail( \ new_ddca_error_detail(DDCRC_UNINITIALIZED, \ "%s called after ddca_init2() or ddca_init() failure", __func__)); \ return DDCRC_UNINITIALIZED; \ } \ if (!library_initialized) { \ syslog(LOG_WARNING, "%s called before ddca_init2() or ddca_init(). Performing default initialization", __func__); \ ddci_init(NULL, DEFAULT_LIBDDCUTIL_SYSLOG_LEVEL, DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE, NULL); \ } \ if (respect_quiesced) { \ if (!increment_active_api_calls(__func__)) { \ syslog(LOG_ERR, "library quiesced, %s temporarily unavailable", __func__); \ save_thread_error_detail( \ new_ddca_error_detail(DDCRC_QUIESCED, \ "library quiesced, %s temporarily unavailable", __func__)); \ return DDCRC_QUIESCED; \ } \ } \ reset_current_traced_function_stack(); \ push_traced_function(__func__); \ if (trace_api_call_depth > 0 || is_traced_api_call(__func__) ) \ trace_api_call_depth++; \ dbgtrc( (debug_flag) ? DDCA_TRC_ALL : DDCA_TRC_API, DBGTRC_OPTIONS_STARTING, \ __func__, __LINE__, __FILE__, "Starting "format, ##__VA_ARGS__); \ if (ptd_api_profiling_enabled) ptd_profile_function_start(__func__); \ } while(0) #define API_PROLOG_NO_DISPLAY_IO(debug_flag, format, ...) \ do { \ reset_current_traced_function_stack(); \ push_traced_function(__func__); \ if (trace_api_call_depth > 0 || is_traced_api_call(__func__) ) \ trace_api_call_depth++; \ dbgtrc( (debug_flag) ? DDCA_TRC_ALL : DDCA_TRC_API, DBGTRC_OPTIONS_STARTING, \ __func__, __LINE__, __FILE__, "Starting "format, ##__VA_ARGS__); \ if (ptd_api_profiling_enabled) ptd_profile_function_start(__func__); \ } while(0) // Function epilog variants /** For functions that return a DDCA_Status. Perform the function return in * the macro. */ #define API_EPILOG_RET_DDCRC(_debug_flag, _respect_quiesced, _rc, _format, ...) \ do { \ dbgtrc_ret_ddcrc( \ (_debug_flag) ? DDCA_TRC_ALL : DDCA_TRC_API, DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, _rc, _format, ##__VA_ARGS__); \ if (trace_api_call_depth > 0) \ trace_api_call_depth--; \ if (ptd_api_profiling_enabled) ptd_profile_function_end(__func__); \ if (_respect_quiesced) decrement_active_api_calls(__func__); \ pop_traced_function(__func__); \ return _rc; \ } while(0) /** For functions that return a boolean. Perform the return in the macro. */ #define API_EPILOG_RET_BOOL(_debug_flag, _respect_quiesced, _result, _format, ...) \ do { \ dbgtrc_returning_expression( \ (_debug_flag) ? DDCA_TRC_ALL : DDCA_TRC_API, DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, sbool(_result), _format, ##__VA_ARGS__); \ if (trace_api_call_depth > 0) \ trace_api_call_depth--; \ if (ptd_api_profiling_enabled) ptd_profile_function_end(__func__); \ if (_respect_quiesced) decrement_active_api_calls(__func__); \ pop_traced_function(__func__); \ return _result; \ } while(0) /** For functions that return a DDCA_Status. This variant reports the status code * being returned, but leaves it to the caller to actually execute the return; */ #define API_EPILOG_BEFORE_RETURN(_debug_flag, _respect_quiesced, _rc, _format, ...) \ do { \ dbgtrc_ret_ddcrc( \ (_debug_flag) ? DDCA_TRC_ALL : DDCA_TRC_API, DBGTRC_OPTIONS_DONE, \ __func__, __LINE__, __FILE__, _rc, _format, ##__VA_ARGS__); \ if (trace_api_call_depth > 0) \ trace_api_call_depth--; \ if (ptd_api_profiling_enabled) ptd_profile_function_end(__func__); \ if (_respect_quiesced) decrement_active_api_calls(__func__); \ pop_traced_function(__func__); \ } while(0) /** Emits a trace message that contains no return status information, and leaves * it to the caller for execute the return. */ #define API_EPILOG_NO_RETURN(_debug_flag, _respect_quiesced, _format, ...) \ do { \ dbgtrc( \ (_debug_flag) ? DDCA_TRC_ALL : DDCA_TRC_API, DBGTRC_OPTIONS_NONE, \ __func__, __LINE__, __FILE__, _format, ##__VA_ARGS__); \ if (trace_api_call_depth > 0) \ trace_api_call_depth--; \ if (ptd_api_profiling_enabled) ptd_profile_function_end(__func__); \ if (_respect_quiesced) decrement_active_api_calls(__func__); \ pop_traced_function(__func__); \ } while(0) #ifdef UNUSED #define API_EPILOGX(_debug_flag, _trace_groups, _rc, _format, ...) \ do { \ dbgtrc_ret_ddcrc( \ (_debug_flag) ? DDCA_TRC_ALL : _trace_groups, DBGTRC_OPTIONS_NONE, \ __func__, __LINE__, __FILE__, _rc, _format, ##__VA_ARGS__); \ trace_api_call_depth--; \ return rc; \ } while(0) #endif #ifdef UNUSED #define ENABLE_API_CALL_TRACING() \ do { if (is_traced_api_call(__func__)) {\ tracing_cur_api_call = true; \ trace_api_call_depth++; \ /* printf("(%s) Setting tracing_cur_api_call = %s\n", __func__, sbool(tracing_cur_api_call) ); */ \ } \ } while(0) #endif #ifdef OLD #define DISABLE_API_CALL_TRACING() \ do { \ if (tracing_cur_api_call) { \ printf("(%s) Setting tracing_cur_api_call = false\n", __func__); \ tracing_cur_api_call = false; \ } \ trace_api_call_depth--; \ } while(0) #endif #define DISABLE_API_CALL_TRACING() \ do { \ if (trace_api_call_depth > 0) \ trace_api_call_depth--; \ } while(0) // // Unpublished // #ifdef UNNEEDED /** Turn on call stack tracing for a specific API function. * * @param[in] funcname function name * @return true if function is traceable, false if not * * @remark * The function must include trace calls. */ bool ddca_add_traced_api_call( const char * funcname); #endif #ifdef REMOVED /*** I2C is an inherently unreliable protocol. The application is responsible for retry management. The maximum number of retries can be tuned. There are 3 retry contexts: - An I2C write followed by a read. Most DDC operations are of this form. - An I2C write without a subsequent read. DDC operations to set a VCP feature value are in this category. - Some DDC operations, such as reading the capabilities string, reading table feature and writing table features require multiple write/read exchanges. These multi-part exchanges have a separate retry count for the entire operation. */ ///@{ /** Gets the upper limit on a max tries value that can be set. * * @return maximum max tries value allowed on set_max_tries() */ int ddca_max_max_tries(void); /** Gets the maximum number of I2C tries for the specified operation type. * @param[in] retry_type I2C operation type * @return maximum number of tries * * @remark * This setting is global, not thread-specific. */ int ddca_get_max_tries( DDCA_Retry_Type retry_type); /** Sets the maximum number of I2C retries for the specified operation type * @param[in] retry_type I2C operation type * @param[in] max_tries maximum count to set * @retval DDCRC_ARG max_tries < 1 or > #ddca_get_max_tries() * * @remark * This setting is global, not thread-specific. */ DDCA_Status ddca_set_max_tries( DDCA_Retry_Type retry_type, int max_tries); ///@} #endif #ifdef REMOVED // // Performance Options // /** Sets the sleep multiplier factor to be used for newly detected displays. * * @param[in] multiplier, must be >= 0 and <= 10 * @return old multiplier, -1.0f if invalid multiplier specified * * The semantics of this function has changed. Prior to release 1.5, * this function set the sleep multiplier for new threads. * As of release 1.5, the sleep multiplier is maintained per * display, not per thread. This function sets the sleep multiplier * for newly detected displays. * @remark * This function is intended for use only during program initialization, * typically from a value passed on the command line. * Consequently there are no associated lock/unlock functions for the value. */ double ddca_set_default_sleep_multiplier(double multiplier); /** Gets the sleep multiplier factor used for newly detected displays. * * The semantics of this function has changed. * See #ddca_set_default_sleep_multiplier(). * * @return multiplier */ double ddca_get_default_sleep_multiplier(); /** @deprecated use #ddca_set_default_sleep_multiplier() */ __attribute__ ((deprecated ("use ddca_set_default_sleep_multiplier"))) void ddca_set_global_sleep_multiplier(double multiplier); /** @deprecated use #ddca_get_default_sleep_multiplier() */ __attribute__ ((deprecated ("use ddca_get_default_sleep_multiplier"))) double ddca_get_global_sleep_multiplier(); #endif #ifdef RESERVED // Deprecated, has no effect __attribute__ ((deprecated ("has no effect"))) bool ddca_enable_sleep_suppression(bool newval); ; __attribute__ ((deprecated ("always returns false"))) bool ddca_is_sleep_suppression_enabled(); #endif #ifdef RESERVED // // Tracing // /** Turn on tracing for a specific function. * * @param[in] funcname function name * @return true if function is traceable, false if not * * @remark * * The function must include trace calls. */ bool ddca_add_traced_function( const char * funcname); /** Turn on all tracing in a specific source file. * * @param[in] filename simple file name, with or without the ".c" extension, * e.g. vcp_feature_set.c, vcp_feature_set */ void ddca_add_traced_file( const char * filename); /** Replaces the groups being traced * * @param[in] trace_flags bitfield indicating groups to trace */ void ddca_set_trace_groups( DDCA_Trace_Group trace_flags); /** Adds to the groups being traced * * @param[in] trace_flags bitfield indicating groups to trace * * @since 1.2.0 */ void ddca_add_trace_groups( DDCA_Trace_Group trace_flags); /** Given a trace group name, returns its identifier. * Case is ignored. * * @param[in] name trace group name * @return trace group identifier * @retval TRC_NEVER unrecognized name */ DDCA_Trace_Group ddca_trace_group_name_to_value(char * name); /** Sets tracing options * * @param[in] options enum that can be used as bit flags */ void ddca_set_trace_options(DDCA_Trace_Options options); #endif #ifdef REMOVED typedef enum { DDCA_TRCOPT_TIMESTAMP = 0x01, DDCA_TRCOPT_THREAD_ID = 0x02, DDCA_TRCOPT_WALLTIME = 0x04 } DDCA_Trace_Options; #endif #ifdef REMOVED /** Assigns a description to the the current thread. * * @param[in] description */ void ddca_set_thread_description(const char * description); /** Appends text to the current thread description. * * @param[in] description */ void ddca_append_thread_description(const char * description); const char * ddca_get_thread_descripton(); #endif #ifdef REMOVED /** Controls whether USB devices are checked during display detection * * Must be called before any API call that triggers display detection. * * @param[in] onoff * @retval DDCRC_OK success * @retval DDCRC_INVALID_OPERATION display detection has already occurred * @retval DDCRC_UNIMPLEMENTED ddcutil not built with USB monitor support * * @remark * The default is to check USB devices. * * This setting is global to all threads. */ DDCA_Status ddca_enable_usb_display_detection(bool onoff); /** Reports whether USB devices are checked as part of display detection * * @retval true USB devices are checked * @retval false USB devices are not checked */ bool ddca_ddca_is_usb_display_detection_enabled(); #endif #endif /* API_BASE_INTERNAL_H_ */ ddcutil-2.2.0/src/libmain/api_capabilities_internal.h0000644000175000001440000000213714754576332016374 /** @file api_capabilities_internal.h */ // Copyright (C) 2018-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef API_CAPABILITIES_INTERNAL_H_ #define API_CAPABILITIES_INTERNAL_H_ #include "public/ddcutil_types.h" #ifdef UNUSED // // MCCS Version Id // /** \deprecated * Returns the symbolic name of a #DDCA_MCCS_Version_Id, * e.g. "DDCA_MCCS_V20." * * @param[in] version_id version id value * @return symbolic name (do not free) */ __attribute__ ((deprecated)) char * ddca_mccs_version_id_name( DDCA_MCCS_Version_Id version_id); /** \deprecated * Returns the descriptive name of a #DDCA_MCCS_Version_Id, * e.g. "2.0". * * @param[in] version_id version id value * @return descriptive name (do not free) * * @remark added to replace ddca_mccs_version_id_desc() during 0.9 * development, but then use of DDCA_MCCS_Version_Id deprecated */ __attribute__ ((deprecated)) char * ddca_mccs_version_id_desc( DDCA_MCCS_Version_Id version_id) ; #endif void init_api_capabilities(); #endif /* API_CAPABILITIES_INTERNAL_H_ */ ddcutil-2.2.0/src/libmain/api_displays_internal.h0000644000175000001440000000557414754576332015603 /** @file api_displays_internal.h * * For use only by other api_... files. */ // Copyright (C) 2015-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef API_DISPLAYS_INTERNAL_H_ #define API_DISPLAYS_INTERNAL_H_ #include "public/ddcutil_types.h" #include "base/core.h" #include "base/displays.h" #include "ddc/ddc_displays.h" // for Dref_Validation_Options DDCA_Status ddci_validate_ddca_display_ref2( DDCA_Display_Ref ddca_dref, Dref_Validation_Options validation_options, Display_Ref** dref_loc); DDCA_Status validate_ddca_display_handle(DDCA_Display_Handle ddca_dh, Display_Handle** dh_loc); #ifdef UNUSED #define WITH_VALIDATED_DR3(_ddca_dref, _ddcrc, _action) \ do { \ assert(library_initialized); \ _ddcrc = 0; \ free_thread_error_detail(); \ Display_Ref * dref = NULL; \ _ddcrc = ddci_validate_ddca_display_ref(_ddca_dref, false, false, &dref); \ if (_ddcrc == 0) { \ (_action); \ } \ } while(0); #endif #ifdef OLD #define WITH_BASIC_VALIDATED_DR3(_ddca_dref, _ddcrc, _action) \ do { \ assert(library_initialized); \ _ddcrc = 0; \ free_thread_error_detail(); \ Display_Ref * dref = NULL; \ _ddcrc = ddci_validate_ddca_display_ref(_ddca_dref, /*basic_only*/ true, false, &dref); \ if (_ddcrc == 0) { \ (_action); \ } \ } while(0); #endif #define WITH_VALIDATED_DR4(_ddca_dref, _ddcrc, _validation_options, _action) \ do { \ assert(library_initialized); \ _ddcrc = 0; \ free_thread_error_detail(); \ Display_Ref * dref0 = dref_from_published_ddca_dref(ddca_dref); \ Display_Ref * dref = NULL; \ if (dref0) \ dref_lock(dref0); \ _ddcrc = ddci_validate_ddca_display_ref2(_ddca_dref, _validation_options, &dref); \ if (_ddcrc == 0) { \ (_action); \ } \ if (dref0) \ dref_unlock(dref0); \ } while(0); #ifdef UNUSED #define WITH_VALIDATED_DH2(ddca_dh, action) \ do { \ assert(library_initialized); \ DDCA_Status psc = 0; \ free_thread_error_detail(); \ Display_Handle * dh = validated_ddca_display_handle(ddca_dh); \ if (!dh) { \ psc = DDCRC_ARG; \ DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, "ddca_dh=%p", ddca_dh); \ } \ else { \ (action); \ } \ /* DBGTRC_RET_DDCRC(debug, DDCA_TRC_API, psc, ""); */ \ return psc; \ } while(0); #endif #define WITH_VALIDATED_DH3(ddca_dh, _ddcrc, action) \ do { \ assert(library_initialized); \ _ddcrc = 0; \ free_thread_error_detail(); \ Display_Handle * dh = NULL; \ _ddcrc = validate_ddca_display_handle(ddca_dh, &dh ); \ if (_ddcrc == 0) { \ (action); \ } \ } while(0); void init_api_displays(); #endif /* API_DISPLAYS_INTERNAL_H_ */ ddcutil-2.2.0/src/sysfs/0000775000175000001440000000000014754576332010660 5ddcutil-2.2.0/src/sysfs/Makefile.am0000644000175000001440000000113014754153540012615 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ $(LIBDRM_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = -Wall if WARNINGS_ARE_ERRORS_COND AM_CFLAGS += -Werror endif # AM_CFLAGS += -Wpedantic if ENABLE_CALLGRAPH_COND AM_CFLAGS += -fdump-rtl-expand endif CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libsysfs.la libsysfs_la_SOURCES = \ sysfs_dpms.c \ sysfs_sys_drm_connector.c \ sysfs_base.c \ sysfs_conflicting_drivers.c \ sysfs_i2c_info.c \ sysfs_i2c_sys_info.c \ sysfs_top.c \ sysfs_services.c ddcutil-2.2.0/src/sysfs/Makefile.in0000664000175000001440000005332514754576155012660 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @WARNINGS_ARE_ERRORS_COND_TRUE@am__append_1 = -Werror # AM_CFLAGS += -Wpedantic @ENABLE_CALLGRAPH_COND_TRUE@am__append_2 = -fdump-rtl-expand subdir = src/sysfs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsysfs_la_LIBADD = am_libsysfs_la_OBJECTS = sysfs_dpms.lo sysfs_sys_drm_connector.lo \ sysfs_base.lo sysfs_conflicting_drivers.lo sysfs_i2c_info.lo \ sysfs_i2c_sys_info.lo sysfs_top.lo sysfs_services.lo libsysfs_la_OBJECTS = $(am_libsysfs_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/sysfs_base.Plo \ ./$(DEPDIR)/sysfs_conflicting_drivers.Plo \ ./$(DEPDIR)/sysfs_dpms.Plo ./$(DEPDIR)/sysfs_i2c_info.Plo \ ./$(DEPDIR)/sysfs_i2c_sys_info.Plo \ ./$(DEPDIR)/sysfs_services.Plo \ ./$(DEPDIR)/sysfs_sys_drm_connector.Plo \ ./$(DEPDIR)/sysfs_top.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libsysfs_la_SOURCES) DIST_SOURCES = $(libsysfs_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ $(LIBDRM_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = -Wall $(am__append_1) $(am__append_2) CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libsysfs.la libsysfs_la_SOURCES = \ sysfs_dpms.c \ sysfs_sys_drm_connector.c \ sysfs_base.c \ sysfs_conflicting_drivers.c \ sysfs_i2c_info.c \ sysfs_i2c_sys_info.c \ sysfs_top.c \ sysfs_services.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/sysfs/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/sysfs/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsysfs.la: $(libsysfs_la_OBJECTS) $(libsysfs_la_DEPENDENCIES) $(EXTRA_libsysfs_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libsysfs_la_OBJECTS) $(libsysfs_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_base.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_conflicting_drivers.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_dpms.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_i2c_info.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_i2c_sys_info.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_sys_drm_connector.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_top.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/sysfs_base.Plo -rm -f ./$(DEPDIR)/sysfs_conflicting_drivers.Plo -rm -f ./$(DEPDIR)/sysfs_dpms.Plo -rm -f ./$(DEPDIR)/sysfs_i2c_info.Plo -rm -f ./$(DEPDIR)/sysfs_i2c_sys_info.Plo -rm -f ./$(DEPDIR)/sysfs_services.Plo -rm -f ./$(DEPDIR)/sysfs_sys_drm_connector.Plo -rm -f ./$(DEPDIR)/sysfs_top.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/sysfs_base.Plo -rm -f ./$(DEPDIR)/sysfs_conflicting_drivers.Plo -rm -f ./$(DEPDIR)/sysfs_dpms.Plo -rm -f ./$(DEPDIR)/sysfs_i2c_info.Plo -rm -f ./$(DEPDIR)/sysfs_i2c_sys_info.Plo -rm -f ./$(DEPDIR)/sysfs_services.Plo -rm -f ./$(DEPDIR)/sysfs_sys_drm_connector.Plo -rm -f ./$(DEPDIR)/sysfs_top.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/sysfs/sysfs_dpms.c0000644000175000001440000002235114754153540013127 /** @file sysfs_dpms.c * DPMS related functions */ // Copyright (C) 2023-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #ifdef USE_X11 #include #endif #include "util/data_structures.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/sysfs_util.h" #ifdef USE_X11 #include "util/x11_util.h" #endif #include "public/ddcutil_types.h" #include "config.h" #include "base/core.h" #include "base/displays.h" #include "base/rtti.h" #include "sysfs/sysfs_base.h" // for is_sysfs_reliable() #include "sysfs/sysfs_dpms.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SYSFS; // // DPMS Detection // Dpms_State dpms_state; // global Value_Name_Table dpms_state_flags_table = { #ifdef USE_X11 VN(DPMS_STATE_X11_CHECKED), VN(DPMS_STATE_X11_ASLEEP), #endif VN(DPMS_SOME_DRM_ASLEEP), VN(DPMS_ALL_DRM_ASLEEP), VN_END }; char * interpret_dpms_state_t(Dpms_State state) { return VN_INTERPRET_FLAGS_T(state, dpms_state_flags_table, "|"); } /** Does X Display Power Management Signaling (DPMS) report the X11 power level * as a sleep mode, i.e. other then DPMSModeOn? * * @retval true XDG session type is X11 and X11 power level != DPMSModeOn * @retval false XDG session type is X11 and X11 power Level = DPMS_ModeOn * @retval false XDG session type != X11 */ bool dpms_is_x11_asleep() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); bool result = false; #ifdef USE_X11 char * xdg_session_type = getenv("XDG_SESSION_TYPE"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "XDG_SESSION_TYPE = |%s|", xdg_session_type); // This is truly pathological. Symbol DPMSModeOn is defined in dpmsconst.h, which // is included if USE_X11 is set. However we get an undefined symbol error. // So we defined DPMSModeOn locally. Yet eclipse greys out the conditional local // definition, indicating that DPMSModeOn is defined. Moreover, if the // include of dpmsconst.h is not wrapped in a #ifdef USE_X11 blocked, the the // symbol is defined. #ifndef DPMSModeOn #define DPMSModeOn 0 #endif if (streq(xdg_session_type, "x11")) { // state indicates whether or not DPMS is enabled (TRUE) or disabled (FALSE). // power_level indicates the current power level (one of DPMSModeOn, // DPMSModeStandby, DPMSModeSuspend, or DPMSModeOff.) unsigned short power_level; unsigned char state; bool ok =get_x11_dpms_info(&power_level, &state); if (ok) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "power_level=%d = %s, state=%s", power_level, dpms_power_level_name(power_level), sbool(state)); result = (state && (power_level != DPMSModeOn) ); } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "get_x11_dpms_info() failed."); SYSLOG2(DDCA_SYSLOG_ERROR, "get_x11_dpms_info() failed"); } } #endif DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, ""); return result; } #ifdef UNUSED void dpms_check_x11_asleep() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); char * xdg_session_type = getenv("XDG_SESSION_TYPE"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "XDG_SESSION_TYPE = |%s|", xdg_session_type); #ifdef USE_X11 // This is truly pathological. Symbol DPMSModeOn is defined in dpmsconst.h, which // is included if USE_X11 is set. However we get an undefined symbol error. // So we defined DPMSModeOn locally. Yet eclipse greys out the conditional local // definition, indicating that DPMSModeOn is defined. Moreover, if the // include of dpmsconst.h is not wrapped in a #ifdef USE_X11 blocked, the the // symbol is defined. #ifndef DPMSModeOn #define DPMSModeOn 0 #endif if (streq(xdg_session_type, "x11")) { // state indicates whether or not DPMS is enabled (TRUE) or disabled (FALSE). // power_level indicates the current power level (one of DPMSModeOn, // DPMSModeStandby, DPMSModeSuspend, or DPMSModeOff.) unsigned short power_level; unsigned char state; bool ok =get_x11_dpms_info(&power_level, &state); if (ok) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "power_level=%d = %s, state=%s", power_level, dpms_power_level_name(power_level), sbool(state)); if (state && (power_level != DPMSModeOn) ) dpms_state |= DPMS_STATE_X11_ASLEEP; dpms_state |= DPMS_STATE_X11_CHECKED; } else { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "get_x11_dpms_info() failed."); SYSLOG2(DDCA_SYSLOG_ERROR, "get_x11_dpms_info() failed"); } } // dpms_state |= DPMS_STATE_X11_ASLEEP; // testing // dpms_state = 0; // testing #endif DBGTRC_DONE(debug, TRACE_GROUP, "dpms_state = 0x%02x = %s", dpms_state, interpret_dpms_state_t(dpms_state)); } #endif /** Checks if a display, specified by its DRM connector name, is in a DPMS * sleep mode. The check is performed using the connector's dpms attribute. * * @param drm_connector_name * @retval true if the dpms attribute value is other than "On" * @retval false if the dpms attribute value is "On" */ bool dpms_check_drm_asleep_by_connector(const char * drm_connector_name) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "drm_connector_name=%s", drm_connector_name); assert(drm_connector_name); char * dpms = NULL; char * enabled = NULL; char * status = NULL; int d = (IS_DBGTRC(debug, DDCA_TRC_NONE)) ? 1 : -1; possibly_write_detect_to_status_by_connector_name(drm_connector_name); RPT_ATTR_TEXT(d, &dpms, "/sys/class/drm", drm_connector_name, "dpms"); RPT_ATTR_TEXT(d, &enabled, "/sys/class/drm", drm_connector_name, "enabled"); RPT_ATTR_TEXT(d, &status, "/sys/class/drm", drm_connector_name, "status"); // Nvidia driver reports enabled value as "disabled" // asleep = !( streq(dpms, "On") && streq(enabled, "enabled") ); bool asleep = !streq(dpms, "On"); free(dpms); free(enabled); free(status); DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, asleep, ""); return asleep; } /** Checks if a display, specified by its I2C bus number, is in a DPMS * sleep mode. * * @param drm_connector_name * @return true if the display is in a sleep mode, false if not */ bool dpms_check_drm_asleep_by_businfo(I2C_Bus_Info * businfo) { bool debug = false; assert(businfo); DBGTRC_STARTING(debug, TRACE_GROUP, "bus = /dev/i2c-%d, flags: %s", businfo->busno, i2c_interpret_bus_flags_t(businfo->flags)); bool asleep = false; // ASSERT_IFF( !(businfo->flags&I2C_BUS_DRM_CONNECTOR_CHECKED), !businfo->drm_connector_found_by); char * xdg_session_type = getenv("XDG_SESSION_TYPE"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "XDG_SESSION_TYPE = |%s|", xdg_session_type); bool sysfs_reliable = is_sysfs_reliable_for_busno(businfo->busno); if (streq(xdg_session_type, "x11") && !sysfs_reliable) { char * s = g_strdup_printf( "is_sysfs_reliable_for_busno(%d) returned false and session_type = X11. " "Using X11 to determine if display is asleep", businfo->busno); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s", s); SYSLOG2(DDCA_SYSLOG_WARNING, "%s", s); free(s); asleep = dpms_is_x11_asleep(); } else { // can this ever be false? assert(businfo->drm_connector_found_by != DRM_CONNECTOR_NOT_CHECKED); #ifdef OUT assert(businfo->flags&I2C_BUS_DRM_CONNECTOR_CHECKED); if (!(businfo->flags&I2C_BUS_DRM_CONNECTOR_CHECKED)) { Sys_Drm_Connector * conn = i2c_check_businfo_connector(businfo); if (!conn) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "i2c_check_businfo_connector() failed for bus %d", businfo->busno); SYSLOG2(DDCA_SYSLOG_ERROR, "i2c_check_businfo_connector() failed for bus %d", businfo->busno); } else { assert(businfo->drm_connector_name); } } #endif if (!sysfs_reliable) { char * s = g_strdup_printf( "is_sysfs_reliable_for_busno(%d) returned false and session type != X11. Assuming not asleep", businfo->busno); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "%s", s); SYSLOG2(DDCA_SYSLOG_WARNING, "%s", s); free(s); } else { if (businfo->drm_connector_name) { asleep = dpms_check_drm_asleep_by_connector(businfo->drm_connector_name); } } } DBGTRC_RET_BOOL(debug, TRACE_GROUP, asleep, ""); return asleep; } /** Checks if a display, specified by its Display Reference, is in a DPMS * sleep mode. * * @param drm_connector_name * @return true if the display is in a sleep mode, false if not */ bool dpms_check_drm_asleep_by_dref(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref = %s", dref_repr_t(dref)); bool result = false; if (dref->detail) result = dpms_check_drm_asleep_by_businfo((I2C_Bus_Info*) dref->detail); DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, ""); return result; } void init_i2c_dpms() { RTTI_ADD_FUNC(dpms_is_x11_asleep); RTTI_ADD_FUNC(dpms_check_drm_asleep_by_businfo); RTTI_ADD_FUNC(dpms_check_drm_asleep_by_dref); RTTI_ADD_FUNC(dpms_check_drm_asleep_by_connector); // RTTI_ADD_FUNC(dpms_check_x11_asleep); } ddcutil-2.2.0/src/sysfs/sysfs_sys_drm_connector.c0000644000175000001440000005670414754153540015727 /** @file sysfs_sys_drm_connector.c * * Query /sys file system for information on I2C devices */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/debug_util.h" #ifdef USE_LIBDRM #include "util/drm_common.h" #endif #include "util/edid.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/utilrpt.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/i2c_bus_base.h" #include "base/rtti.h" #include "sysfs_base.h" #include "sysfs_sys_drm_connector.h" static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SYSFS; // // *** Scan /sys by drm connector - uses struct Sys_Drm_Connector *** // // from query_sysenv_sysfs // 9/28/2021 Requires hardening, testing on other than amdgpu, MST etc GPtrArray * sys_drm_connectors = NULL; // Sys_Drm_Connector bool all_drm_connectors_have_connector_id = false; /** Frees a Sys_Drm_Connector instance * * @param pointer to instance to free */ void free_sys_drm_connector(void * display) { bool debug = false; DBGMSF(debug, "Starting. display=%p", display); if (display) { Sys_Drm_Connector * disp = display; free(disp->connector_name); free(disp->connector_path); free(disp->name); // free(disp->dev); free(disp->ddc_dir_path); free(disp->base_name); free(disp->base_dev); free(disp->edid_bytes); free(disp->enabled); free(disp->status); free(disp); } DBGMSF(debug, "Done."); } /** Frees the persistent GPtrArray of #Sys_Drm_Connector instances pointed * to by global sys_drm_connectors. */ void free_sys_drm_connectors() { if (sys_drm_connectors) g_ptr_array_free(sys_drm_connectors, true); sys_drm_connectors = NULL; } /** Reports the contents of one #Sys_Drm_Connector instance * * @param cur pointer to instance * @param detailed_edid if false, show only edid summary * @param depth logical indentation depth */ void report_one_sys_drm_connector(Sys_Drm_Connector * cur, bool detailed_edid, int depth) { int d0 = depth; int d1 = depth+1; rpt_vstring(d0, "Connector: %s", cur->connector_name); rpt_vstring(d1, "i2c_busno: %d", cur->i2c_busno); rpt_vstring(d1, "connector_id: %d", cur->connector_id); rpt_vstring(d1, "name: %s", cur->name); // rpt_vstring(d1, "dev: %s", cur->dev); rpt_vstring(d1, "enabled: %s", cur->enabled); rpt_vstring(d1, "status: %s", cur->status); if (cur->is_aux_channel) { rpt_vstring(d1, "base_busno: %d", cur->base_busno); rpt_vstring(d1, "base_name: %s", cur->base_name); rpt_vstring(d1, "base dev: %s", cur->base_dev); } if (cur->edid_size > 0) { if (detailed_edid) { rpt_label(d1, "edid:"); rpt_hex_dump(cur->edid_bytes, cur->edid_size, d1); } else { Parsed_Edid * edid = create_parsed_edid(cur->edid_bytes); if (edid) { rpt_vstring(d1, "edid: %s, %s, %s", edid->mfg_id, edid->model_name, edid->serial_ascii); free_parsed_edid(edid); } else rpt_label(d1, "edid: invalid"); } } else rpt_label(d1, "edid: None"); } /** Returns a #Sys_Drm_Connector object for a single connector directory of * /sys/class/drm. It reads the directory itself instead of using the * #sys_drm_connectors array. * * @oaram connector_name e.g. card2-DP-3 * @param depth logical indentation depth, output connector report if >= 0 * @return Sys_Drm_Connector object for the connector */ Sys_Drm_Connector * get_drm_connector(const char * fn, int depth) { return one_drm_connector0("/sys/class/drm", fn, depth); } /** Scans a single connector directory of /sys/class/drm. * * Has typedef Dir_Foreach_Func */ void one_drm_connector( const char * dirname, // /sys/class/drm const char * fn, // e.g. card0-DP-1 void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, fn=%s, depth=%d", dirname, fn, depth); Sys_Drm_Connector * cur = one_drm_connector0(dirname, fn, depth); GPtrArray * drm_displays = accumulator; if (cur) g_ptr_array_add(drm_displays, cur); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // simplified variant Sys_Drm_Connector * one_drm_connector0( const char * dirname, // /sys/class/drm const char * fn, // e.g. card0-DP-1 int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, fn=%s, depth=%d", dirname, fn, depth); int d0 = depth; if (depth < 0 && (IS_DBGTRC(debug, TRACE_GROUP))) d0 = 2; Sys_Drm_Connector * cur = calloc(1, sizeof(Sys_Drm_Connector)); cur->i2c_busno = -1; // 0 is valid bus number cur->base_busno = -1; cur->connector_id = -1; cur->connector_name = g_strdup(fn); // e.g. card0-DP-1 RPT_ATTR_INT( d0, &cur->connector_id, dirname, fn, "connector_id"); RPT_ATTR_REALPATH(d0, &cur->connector_path, dirname, fn); GByteArray * edid_byte_array = NULL; possibly_write_detect_to_status_by_connector_path(cur->connector_path); RPT_ATTR_EDID(d0, &edid_byte_array, dirname, fn, "edid"); // e.g. /sys/class/drm/card0-DP-1/edid // DBGMSG("edid_byte_array=%p", (void*)edid_byte_array); if (edid_byte_array) { cur->edid_size = edid_byte_array->len; cur->edid_bytes = g_byte_array_free(edid_byte_array, false); // DBGMSG("Setting cur->edid_bytes = %p", (void*)cur->edid_bytes); } Connector_Bus_Numbers * cbn = calloc(1, sizeof(Connector_Bus_Numbers)); get_connector_bus_numbers(dirname, fn, cbn); cur->base_busno = cbn->base_busno; cur->i2c_busno = cbn->i2c_busno; cur->connector_id = cbn->connector_id; free_connector_bus_numbers(cbn); possibly_write_detect_to_status_by_connector_name(fn); RPT_ATTR_TEXT(d0, &cur->enabled, dirname, fn, "enabled"); // e.g. /sys/class/drm/card0-DP-1/enabled RPT_ATTR_TEXT(d0, &cur->status, dirname, fn, "status"); // e.g. /sys/class/drm/card0-DP-1/status if (depth >= 0) rpt_nl(); DBGTRC_DONE(debug, TRACE_GROUP, ""); return cur; } /** Collects information from all connector subdirectories of /sys/class/drm, * optionally emitting a report. * * @param depth logical indentation depth, if < 0 do not emit report * @return array of #Sys_Drm_Connector structs, one for each connector found * * Returns GPtrArray with 0 entries if no DRM displays found * * Also sets global #sys_drm_connectors */ GPtrArray * scan_sys_drm_connectors(int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "depth=%d", depth); if (depth < 0 && (IS_DBGTRC(debug, TRACE_GROUP))) depth = 1; GPtrArray * sys_drm_connectors = g_ptr_array_new_with_free_func(free_sys_drm_connector); dir_filtered_ordered_foreach( "/sys/class/drm", is_drm_connector, // filter function NULL, // ordering function one_drm_connector, sys_drm_connectors, // accumulator, GPtrArray * depth); DBGTRC_DONE(debug, DDCA_TRC_I2C, "size of sys_drm_connectors: %d", sys_drm_connectors->len); return sys_drm_connectors; } /** Gets the value of global #sys_drm_connectors. * * @param rescan free the existing data structure * * If sys_drm_connectors == NULL or rescan was set, * scan the /sys/class/drm/ directories */ GPtrArray* get_sys_drm_connectors(bool rescan) { if (sys_drm_connectors && rescan) { g_ptr_array_free(sys_drm_connectors, true); sys_drm_connectors = NULL; } if (!sys_drm_connectors) sys_drm_connectors = scan_sys_drm_connectors(-1); return sys_drm_connectors; } static gint sort_sys_drm_connectors (gconstpointer a, gconstpointer b) { const Sys_Drm_Connector *entry1 = *((Sys_Drm_Connector **) a); const Sys_Drm_Connector *entry2 = *((Sys_Drm_Connector **) b); return sys_drm_connector_name_cmp0(entry1->connector_name, entry2->connector_name); } /** Reports the contents of the array of #Sys_Drm_Connector instances * pointed to by global #sys_drm_connectors. If global #sys_drm_connectors * is NULL, scan the /sys/class/drm/ tree. * * @param verbose if true, show full edid information * @param depth logical indentation depth */ void report_sys_drm_connectors(bool verbose, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "depth=%d", depth); int d0 = depth; int d1 = (debug) ? 2 : -1; rpt_nl(); rpt_label(d0, "Display connectors reported by /sys:"); if (!sys_drm_connectors) sys_drm_connectors = scan_sys_drm_connectors(d1); GPtrArray * displays = sys_drm_connectors; if (!displays || displays->len == 0) { rpt_label(d1, "None"); } else { g_ptr_array_sort(displays, sort_sys_drm_connectors); for (int ndx = 0; ndx < displays->len; ndx++) { Sys_Drm_Connector * cur = g_ptr_array_index(displays, ndx); report_one_sys_drm_connector(cur, verbose, depth); rpt_nl(); } } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // TODO: Create version that directly examines each connector directory bool all_sys_drm_connectors_have_connector_id(bool rescan) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "rescan=%s", SBOOL(rescan)); GPtrArray * connectors = get_sys_drm_connectors(rescan); bool result = true; for (int ndx = 0; ndx < connectors->len; ndx++) { Sys_Drm_Connector * conn = g_ptr_array_index(connectors, ndx); if (conn->connector_id < 0) result = false; } DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, ""); return result; } Bit_Set_256 buses_having_edid_from_sys_drm_connectors(bool rescan) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "rescan=%s", SBOOL(rescan)); GPtrArray * connectors = get_sys_drm_connectors(rescan); Bit_Set_256 result = EMPTY_BIT_SET_256; for (int ndx = 0; ndx < connectors->len; ndx++) { Sys_Drm_Connector * conn = g_ptr_array_index(connectors, ndx); if (conn->edid_bytes) result = bs256_insert(result, conn->i2c_busno); } DBGTRC_DONE(debug, DDCA_TRC_NONE, "Returning; %s", bs256_to_string_decimal_t(result, "", ",")); return result; } /** Find a #Sys_Drm_Connector instance using one of the I2C bus number, * EDID value, or DRM connector name. * * @param busno I2C bus number * @param edid pointer to 128 byte EDID * @param connector_name e.g. card0-HDMI-A-1 * * Scans /sys/class/drm if global #sys_class_drm not already set */ Sys_Drm_Connector * find_sys_drm_connector(int busno, Byte * edid, const char * connector_name) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "busno=%d, edid=%p, connector_name=%s", busno, (void*)edid, connector_name); if (!sys_drm_connectors) sys_drm_connectors = scan_sys_drm_connectors(-1); assert(sys_drm_connectors); Sys_Drm_Connector * result = NULL; for (int ndx = 0; ndx < sys_drm_connectors->len; ndx++) { Sys_Drm_Connector * cur = g_ptr_array_index(sys_drm_connectors, ndx); // DBGMSG("cur->busno = %d", cur->i2c_busno); if (busno >= 0 && cur->i2c_busno == busno) { DBGTRC(debug, DDCA_TRC_NONE, "Matched by bus number"); result = cur; break; } if (edid && cur->edid_size >= 128 && (memcmp(edid, cur->edid_bytes,128) == 0)) { DBGTRC(debug, DDCA_TRC_NONE, "Matched by edid"); result = cur; break; } if (connector_name && streq(connector_name, cur->connector_name)) { DBGTRC(debug, DDCA_TRC_NONE, "Matched by connector_name"); result = cur; break; } } DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %p", (void*) result); return result; } Sys_Drm_Connector * find_sys_drm_connector_by_connector_id(int connector_id) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "connector_id=%d", connector_id); if (!sys_drm_connectors) sys_drm_connectors = scan_sys_drm_connectors(-1); assert(sys_drm_connectors); Sys_Drm_Connector * result = NULL; for (int ndx = 0; ndx < sys_drm_connectors->len; ndx++) { Sys_Drm_Connector * cur = g_ptr_array_index(sys_drm_connectors, ndx); if (cur->connector_id < 0) // driver does not set connector number, need only check once break; if (cur->connector_id == connector_id) { DBGTRC(debug, DDCA_TRC_NONE, "Matched"); result = cur; break; } } DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %p", (void*) result); return result; } Sys_Drm_Connector * find_sys_drm_connector_by_connector_identifier(Drm_Connector_Identifier dci) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "dci = %s", dci_repr_t(dci)); if (!sys_drm_connectors) sys_drm_connectors = scan_sys_drm_connectors(-1); assert(sys_drm_connectors); Sys_Drm_Connector * result = NULL; for (int ndx = 0; ndx < sys_drm_connectors->len; ndx++) { Sys_Drm_Connector * cur = g_ptr_array_index(sys_drm_connectors, ndx); Drm_Connector_Identifier cur_dci = parse_sys_drm_connector_name(cur->connector_name); if (dci_eq(dci, cur_dci)) { result = cur; break; } } DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %p", (void*) result); return result; } int sys_drm_get_busno_by_connector_name(const char * connector_name) { int result = -1; Sys_Drm_Connector * sdc = find_sys_drm_connector(-1, NULL, connector_name); if (sdc) result = sdc->i2c_busno; return result; } /** Searches for a Sys_Drm_Connector instance by I2C bus number. * * @param I2C bus number * @return pointer to instance, NULL if not found */ Sys_Drm_Connector * find_sys_drm_connector_by_busno(int busno) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "busno=%d", busno); Sys_Drm_Connector * result = find_sys_drm_connector(busno, NULL, NULL); DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %p: %s", result, (result) ? result->connector_name : "NOT FOUND"); return result; } /** If the display has an open-source conformant driver, * returns the connector name. * * If the display has a DRM driver that doesn't conform * to the standard (I'm looking at you, Nvidia), or it * is not a DRM driver, returns NULL. * * @param busno * @return connector name, caller must free */ char * find_drm_connector_name_by_busno(int busno) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Starting. busno = %d", busno); char * result = NULL; Sys_Drm_Connector * drm_connector = find_sys_drm_connector_by_busno(busno); if (drm_connector) { result = g_strdup(drm_connector->connector_name); } DBGTRC_RET_STRING(debug, TRACE_GROUP, result, ""); return result; } /** Searches for a Sys_Drm_Connector instance by EDID. * * @param pointer to 128 byte EDID value * @return pointer to instance, NULL if not found */ Sys_Drm_Connector * find_sys_drm_connector_by_edid(Byte * raw_edid) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "edid=%p", (void*) raw_edid); Sys_Drm_Connector * result = find_sys_drm_connector(-1, raw_edid, NULL); DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %p", (void*) result); return result; } /** Gets the DRM connector name, e.g. card0-DP-3, using the EDID. * * @param edid_bytes pointer to 128 byte EDID * @return connector name, NULL if not found */ char * get_drm_connector_name_by_edid(Byte * edid_bytes) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Finding connector by EDID..."); char * result = NULL; Sys_Drm_Connector * connector_rec = find_sys_drm_connector_by_edid(edid_bytes); if (connector_rec) { result = g_strdup(connector_rec->connector_name); } DBGTRC_RET_STRING(debug, TRACE_GROUP, result, ""); return result; } /** Searches for a Sys_Drm_Connector instance by the connector name * * @param connector name * @return pointer to instance, NULL if not found */ Sys_Drm_Connector * find_sys_drm_connector_by_connector_name(const char * name) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "name=|%s|", name); Sys_Drm_Connector * result = find_sys_drm_connector(-1, NULL, name); DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %p", (void*) result); return result; } // // End of Sys_Drm_Connector section // // // *** DRM Checks *** // #ifdef INVALID // adapter_path and adapter_class not set for nvidia driver /** Uses the Sys_I2C_Info array to get a list of all video adapters * and checks if each supports DRM. * * @param rescan always recreate the Sys_I2C_Info array * @return true if all display adapters support DRM, false if not */ bool all_sysfs_i2c_info_drm(bool rescan) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "rescan=%s", SBOOL(rescan)); bool result = false; #ifdef USE_LIBDRM GPtrArray* all_info = get_all_sysfs_i2c_info(rescan, -1); GPtrArray* adapter_paths = g_ptr_array_sized_new(4); g_ptr_array_set_free_func(adapter_paths, g_free); if (all_info->len > 0) { for (int ndx = 0; ndx < all_info->len; ndx++) { Sysfs_I2C_Info * info = g_ptr_array_index(all_info, ndx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "busno=%d, adapter_class=%s, adapter_path=%s", info->busno, info->adapter_class, info->adapter_path); if (str_starts_with(info->adapter_class, "0x03")) { g_ptr_array_add(adapter_paths, info->adapter_path); } } result = all_video_adapters_support_drm_using_drm_api(adapter_paths); } g_ptr_array_free(adapter_paths, false); #endif DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, ""); return result; } #endif #ifdef WRONG // directory drm always exists, need to check if it has connector nodes /** Checks that all video devices have DRM drivers. * * @return true/false */ bool i2c_all_video_devices_drm() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); GPtrArray * video_devices = get_sys_video_devices(); bool all_devices_drm = true; for (int ndx = 0; ndx < video_devices->len; ndx++) { char * device_path = g_ptr_array_index(video_devices, ndx); int d = IS_DBGTRC(debug,DDCA_TRC_NONE) ? 1 : -1; bool found_drm = RPT_ATTR_SINGLE_SUBDIR(d, NULL, fn_equal, "drm", device_path); if (!found_drm) { all_devices_drm = false; break; } } g_ptr_array_free(video_devices, true); DBGTRC_RET_BOOL(debug, TRACE_GROUP, all_devices_drm, ""); return all_devices_drm; } #endif #ifdef UNUSED /** If possible, determines the drm connector for an I2C bus number. * If insufficient fields exist in sysfs to do this with absolute * assurance, EDID comparison is used. * * Fields drm_connector_name and drm_connector_found_by are set. * If the drm connector cannot be determined, drm_connector_found_by * is set to DRM_CONNECTOR_NOT_FOUND. * * @param businfo I2C_Bus_Info record * @return pointer to Sys_Drm_Connector instance */ Sys_Drm_Connector * i2c_check_businfo_connector(I2C_Bus_Info * businfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "Checking I2C_Bus_Info for /dev/i2c-%d", businfo->busno); businfo->drm_connector_found_by = DRM_CONNECTOR_NOT_FOUND; Sys_Drm_Connector * drm_connector = find_sys_drm_connector_by_busno(businfo->busno); if (drm_connector) { businfo->drm_connector_found_by = DRM_CONNECTOR_FOUND_BY_BUSNO; businfo->drm_connector_name = g_strdup(drm_connector->connector_name); businfo->drm_connector_id = drm_connector->connector_id; } else if (businfo->edid) { drm_connector = find_sys_drm_connector_by_edid(businfo->edid->bytes); if (drm_connector) { businfo->drm_connector_name = g_strdup(drm_connector->connector_name); businfo->drm_connector_found_by = DRM_CONNECTOR_FOUND_BY_EDID; businfo->drm_connector_id = drm_connector->connector_id; } } businfo->flags |= I2C_BUS_DRM_CONNECTOR_CHECKED; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Final businfo flags: %s", i2c_interpret_bus_flags_t(businfo->flags)); if (businfo->drm_connector_name) DBGTRC_DONE(debug, TRACE_GROUP, "Returning: SYS_Drm_Connector for %s", businfo->drm_connector_name); else DBGTRC_RETURNING_STRING(debug, TRACE_GROUP, NULL, ""); return drm_connector; } #endif /** Module initialization */ void init_i2c_sysfs() { // Sys_Drm_Connector RTTI_ADD_FUNC(one_drm_connector); RTTI_ADD_FUNC(scan_sys_drm_connectors); RTTI_ADD_FUNC(report_sys_drm_connectors); RTTI_ADD_FUNC(find_sys_drm_connector_by_busno); RTTI_ADD_FUNC(find_sys_drm_connector_by_connector_identifier); RTTI_ADD_FUNC(find_sys_drm_connector_by_connector_id); RTTI_ADD_FUNC(find_sys_drm_connector_by_edid); RTTI_ADD_FUNC(find_sys_drm_connector); RTTI_ADD_FUNC(find_drm_connector_name_by_busno); } #ifdef FOR_FUTURE_USE Connector_Busno_Dref_Table * cbd_table = NULL; void gdestroy_cbd(void * data) { Connector_Busno_Dref * cbd = data; free(cbd->connector); } Connector_Busno_Dref_Table * create_connector_busnfo_dref_table() { Connector_Busno_Dref_Table * cbdt = g_ptr_array_new_with_free_func(gdestroy_cbd); return cbdt; } Connector_Busno_Dref * new_cbd(const char * connector, int busno) { Connector_Busno_Dref * cbd = calloc(1, sizeof(Connector_Busno_Dref)); cbd->connector = g_strdup(connector); cbd->busno = busno; return cbd; } Connector_Busno_Dref * new_cbd0(int busno) { Connector_Busno_Dref * cbd = calloc(1, sizeof(Connector_Busno_Dref)); cbd->busno = busno; return cbd; } Connector_Busno_Dref * get_cbd_by_connector(const char * connector) { Connector_Busno_Dref * result = NULL; assert(cbd_table); for (int ndx = 0; ndx < cbd_table->len; ndx++) { Connector_Busno_Dref * cur = g_ptr_array_index(cbd_table, ndx); if (streq(connector, cur->connector)) { result = cur; break; } } return result; } // how to handle secondary busno's Connector_Busno_Dref * get_cbd_by_busno(int busno) { Connector_Busno_Dref * result = NULL; assert(cbd_table); for (int ndx = 0; ndx < cbd_table->len; ndx++) { Connector_Busno_Dref * cur = g_ptr_array_index(cbd_table, ndx); if ( cur->busno == busno) { result = cur; break; } } return result; } // if dref != NULL, replaces, if NULL, just erases void set_cbd_connector(Connector_Busno_Dref * cbd, Display_Ref * dref) { cbd->dref = dref; } void dbgrpt_cbd_table(Connector_Busno_Dref_Table * cbd_table, int depth) { rpt_structure_loc("cbd_table", cbd_table, depth); int d0 = depth; int d1 = depth+1; for (int ndx = 0; ndx < cbd_table->len; ndx++) { Connector_Busno_Dref* cur = g_ptr_array_index(cbd_table, ndx); rpt_structure_loc("Connector_Busno_Dref", cur, d0); rpt_vstring(d1, "connector: %s", cur->connector); rpt_vstring(d1, "busno: %s", cur->busno); rpt_vstring(d1, "dref: %s", (cur->dref) ? dref_repr_t(cur->dref) : "NULL"); } } #endif ddcutil-2.2.0/src/sysfs/sysfs_base.c0000644000175000001440000013737314754153540013111 /** @file sysfs_base.c */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "util/coredefs.h" #include "util/data_structures.h" #include "util/debug_util.h" #ifdef USE_LIBDRM #include "util/drm_common.h" #endif #include "util/edid.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/utilrpt.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/i2c_bus_base.h" #include "base/rtti.h" #include "sysfs_base.h" static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SYSFS; // // Predicate Functions // bool is_n_nnnn(const char * dirname, const char * simple_fn) { bool result = predicate_any_D_00hh(simple_fn); DBGMSF(false,"dirname=%s. simple_fn=%s, returning %s", dirname, simple_fn, SBOOL(result)); return result; } #ifdef NOT_NEEDED // just set func arg to NULL bool fn_any(const char * filename, const char * ignore) { DBGMSF(true, "filename=%s, ignore=%s: Returning true", filename, ignore); return true; } #endif // // *** Common Functions // #ifdef UNUSED static void add_video_device_to_array( const char * dirname, // const char * fn, void * data, int depth) { bool debug = false; DBGMSF(debug, "dirname=%s, fn=%s", dirname, fn); GPtrArray* accumulator = (GPtrArray*) data; char * s = g_strdup_printf("%s/%s", dirname, fn); g_ptr_array_add(accumulator, s); // RPT_ATTR_TEXT( 1, NULL, dirname, fn, "class"); // RPT_ATTR_REALPATH(1, NULL, dirname, fn, "driver"); } /** Gets all sysfs devices with class video device, i.e. x03 * * @return array of fully qualified device paths */ GPtrArray * get_sys_video_devices() { bool debug = false; GPtrArray * video_devices = g_ptr_array_new_with_free_func(g_free); DBGTRC_STARTING(debug, TRACE_GROUP, "video_devices=%p", video_devices); dir_filtered_ordered_foreach("/sys/bus/pci/devices", has_class_display, // filter function NULL, // ordering function add_video_device_to_array, video_devices, // accumulator -1); DBGTRC_DONE(debug, TRACE_GROUP,"Returning array with %d video devices", video_devices->len); return video_devices; } #endif // // Extract bus numbers connetor_id, and name from card-connector directories // void dbgrpt_connector_bus_numbers(Connector_Bus_Numbers * cbn, int depth) { rpt_structure_loc("Connector_Bus_Numbers", cbn, depth); int d1 = depth+1; rpt_vstring(d1, "i2c_busno: %d", cbn->i2c_busno); rpt_vstring(d1, "base_busno: %d", cbn->base_busno); rpt_vstring(d1, "connector_id: %d", cbn->connector_id); rpt_vstring(d1, "name: %s", cbn->name); } void free_connector_bus_numbers(Connector_Bus_Numbers * cbn) { free(cbn->name); free(cbn); } /** Attempts to extract an I2C bus number and additional information from a * card-connector directory. This may not always be successful: * - connector is on MST hub * - Nvidia proprietary driver * * @param dirname drm/cardN * @param fn connector name, e.g. card0-HDMI-1 * @param cbn struct in which to collect results * * @remark * DP connectors: * - normally have a i2c-N subdirectory * - not present for MST * - have drm_dp_aux subdirectory (amdgpu, i915) * - not present for Nvidia * - name attribute in drm_dp_aux subdir may be "DPMST" * - ddc/i2c-dev directory contains dir with name of "base" i2c-dev device * - not present for MST * HDMI, DVI connectors: * - have ddc directory * - ddc/i2c-dev contains subdirectory with i2c bus name * - ddc/name exists */ void get_connector_bus_numbers( const char * dirname, // /drm/cardN const char * fn, // card0-HDMI-1 etc Connector_Bus_Numbers * cbn) { bool debug = false; int d = (IS_DBGTRC(debug, DDCA_TRC_NONE)) ? 1 : -1; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, fn=|%s|", dirname, fn); int d0 = (debug) ? 1 : -1; bool validate_name = debug; bool is_dp_connector = (str_contains(fn, "-DP-") > 0) ; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "is_dp_connector=%s", sbool(is_dp_connector)); cbn->i2c_busno = -1; // 0 is valid bus number cbn->base_busno = -1; cbn->connector_id = -1; int connector_id; bool found = RPT_ATTR_INT(d, &connector_id, dirname, fn, "connector_id"); if (found) cbn->connector_id = connector_id; if (is_dp_connector) { // DP // was has_i2c_subdir // name attribute exists in multiple location char * aux_dir_name = NULL; char * i2cN_dir_name = NULL; char * ddc_dir_name = NULL; // Examine drm_dp_auxN subdirectory // Present: i915, amdgpu // Absent: Nvidia char * drm_dp_aux_dir = NULL; bool has_drm_dp_aux_dir = // does it exist? e.g. /sys/class/drm/card0-DP-1/drm_dp_aux0 RPT_ATTR_SINGLE_SUBDIR(d0, &drm_dp_aux_dir, fn_starts_with, "drm_dp_aux", dirname, fn); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "has_drm_dp_aux_dir=%s, drm_dp_aux_dir = %s", SBOOL(has_drm_dp_aux_dir), drm_dp_aux_dir); if (has_drm_dp_aux_dir) { RPT_ATTR_TEXT(d0, &aux_dir_name, dirname, fn, drm_dp_aux_dir, "name"); free(drm_dp_aux_dir); } // Examine i2c-N subdirectory // Present: i915, amdgpu (normal) // Absent: amdgpu(MST), Nvidia char * i2cN_buf = NULL; // i2c-N char * i2cN_buf2 = NULL; bool has_i2c_subdir = RPT_ATTR_SINGLE_SUBDIR(d0, &i2cN_buf, fn_starts_with,"i2c-", dirname, fn); if (has_i2c_subdir) { // i2c-N directory not present for MST hub cbn->i2c_busno = i2c_name_to_busno(i2cN_buf); // e.g. /sys/class/drm/card0-DP-1/i2c-6/name: RPT_ATTR_TEXT(d0, &i2cN_dir_name, dirname, fn, i2cN_buf, "name"); } // Examine ddc subdirectory. // Present: i915, amdgpu (normal) // Absent: Nvidia, amdgpu(MST) bool has_ddc_subdir = RPT_ATTR_NOTE_SUBDIR(-1, NULL, dirname, fn, "ddc"); // char * ddc_dir_path; if (has_ddc_subdir) { // RPT_ATTR_REALPATH(-1, &ddc_dir_path, dirname, fn, "ddc"); // RPT_ATTR_TEXT(-1, &ddc_dir_name, ddc_dir_path, "name"); RPT_ATTR_TEXT(-1, &ddc_dir_name, dirname, fn, "ddc", "name"); bool has_i2c_dev_subdir = RPT_ATTR_NOTE_SUBDIR(-1, NULL, dirname, fn, "ddc", "i2c-dev"); if (has_i2c_dev_subdir) { // looking for e.g. /sys/bus/drm/card0-DP-1/ddc/i2c-dev/i2c-1 has_i2c_subdir = RPT_ATTR_SINGLE_SUBDIR(d0, &i2cN_buf2, fn_starts_with, "i2c-", dirname, fn, "ddc", "i2c-dev"); if (has_i2c_subdir) { cbn->base_busno = i2c_name_to_busno(i2cN_buf2); // RPT_ATTR_TEXT(d0, &cbn->base_dev, dirname, fn, "ddc", "i2c-dev", i2cN_buf2, "dev"); } } } //ddc subdirectory free(i2cN_buf); free(i2cN_buf2); // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, // "connector: %s, aux_dir_name: |%s|, i2cN_dir_name: |%s|, ddc_dir_name: |%s|", // fn, aux_dir_name, i2cN_dir_name, ddc_dir_name); if (aux_dir_name) cbn->name = strdup(aux_dir_name); else if (i2cN_dir_name) cbn->name = strdup(i2cN_dir_name); else if (ddc_dir_name) cbn->name = strdup(ddc_dir_name); else cbn->name = NULL; free(aux_dir_name); free(i2cN_dir_name); free(ddc_dir_name); } // DP else { // not DP // Examine ddc subdirectory // Not present: Nvidia char * ddc_dir_path = NULL; bool found_ddc = RPT_ATTR_REALPATH(d0, &ddc_dir_path, dirname, fn, "ddc"); ASSERT_IFF(found_ddc, ddc_dir_path); // guaranteed by RPT_ATTR_REALPATH() if (ddc_dir_path) { RPT_ATTR_TEXT(d0, &cbn->name, dirname, fn, "ddc", "name"); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "name=%s", cbn->name); // No ddc directory on Nvidia? // Examine ddc subdirectory char * i2cN_buf = NULL; // looking for e.g. /sys/bus/drm/card0-DVI-D-1/ddc/i2c-dev/i2c-1 bool has_i2c_subdir = RPT_ATTR_SINGLE_SUBDIR(d0, &i2cN_buf, fn_starts_with, "i2c-", dirname, fn, "ddc", "i2c-dev"); if (has_i2c_subdir) { cbn->i2c_busno = i2c_name_to_busno(i2cN_buf); // RPT_ATTR_TEXT(d0, &cur->base_dev, dirname, fn, "ddc", "i2c-dev", i2cN_buf, "dev"); if (validate_name) { // Check that /ddc/i2c-dev/i2c-N/name and /ddc/name match char * ddc_i2c_dev_name = NULL; RPT_ATTR_TEXT(d0, &ddc_i2c_dev_name, dirname, fn, "ddc", "i2c-dev", i2cN_buf, "name"); if (!streq(ddc_i2c_dev_name, cbn->name) && debug) rpt_vstring(d0, "Unexpected: %s/ddc/i2c-dev/%s/name and %s/ddc/name do not match", fn, i2cN_buf, fn); free(ddc_i2c_dev_name); } } free(i2cN_buf); free(ddc_dir_path); } // has ddc subdirectory } // not DP if (IS_DBGTRC(debug, TRACE_GROUP)) dbgrpt_connector_bus_numbers(cbn, 1); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Debug Reports // static void simple_report_one_connector0( const char * dirname, // /drm/cardN const char * simple_fn, // card0-HDMI-1 etc bool verbose, int depth) { bool debug = false; // verbose = true; int d1 = depth+1; DBGMSF(debug, "Starting. dirname=%s, simple_fn=%s", dirname, simple_fn); assert(dirname); assert(simple_fn); GByteArray * edid_byte_array = NULL; char * status = NULL; char * connector_id = NULL; char * enabled = NULL; possibly_write_detect_to_status_by_connector_name(simple_fn); GET_ATTR_TEXT(&connector_id, dirname, simple_fn, "connector_id"); GET_ATTR_TEXT(&status, dirname, simple_fn, "status"); GET_ATTR_TEXT(&enabled, dirname, simple_fn, "enabled"); GET_ATTR_EDID(&edid_byte_array, dirname, simple_fn, "edid"); Connector_Bus_Numbers * cbn = calloc(1, sizeof(Connector_Bus_Numbers)); get_connector_bus_numbers(dirname, simple_fn, cbn); if (verbose || edid_byte_array || streq(status, "connected")) { rpt_nl(); rpt_vstring(depth, "Connector: %s", simple_fn); rpt_vstring(d1, "connector id: %s", connector_id); rpt_vstring(d1, "status: %s", status); rpt_vstring(d1, "enabled: %s", enabled); if (edid_byte_array) { Parsed_Edid * parsed = create_parsed_edid(edid_byte_array->data); if (parsed) { rpt_vstring(d1, "edid: %s/%s/%s", parsed->mfg_id, parsed->model_name, parsed->serial_ascii); free_parsed_edid(parsed); } else rpt_label( d1, "edid: parse failed"); } rpt_vstring(d1, "i2c busno: %d", cbn->i2c_busno); rpt_vstring(d1, "name: %s", cbn->name); } free_connector_bus_numbers(cbn); free(status); free(connector_id); free(enabled); if (edid_byte_array) g_byte_array_free(edid_byte_array, true); DBGMSF(debug, "Done"); } static void simple_report_one_connector( const char * dirname, // /drm/cardN const char * simple_fn, // card0-HDMI-1 etc void * data, int depth) { simple_report_one_connector0(dirname, simple_fn, false, depth); } /** Reports sysfs attributes connector_id, enabled, status, dpms, and edid * for each DRM connector. * * @param depth logical indentation depth */ void dbgrpt_sysfs_basic_connector_attributes(int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); int d0 = depth; rpt_nl(); char * dname = "/sys/class/drm"; rpt_vstring(d0, "*** Examining %s for card-connector dirs that appear to be connected ***", dname); dir_filtered_ordered_foreach( dname, is_card_connector_dir, // filter function sys_drm_connector_name_cmp, // ordering function simple_report_one_connector, NULL, // accumulator depth); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Get DRM connector name given an I2C bus number or connector id. typedef struct { int connector_id; // char * connector_id_s; char * connector_name; } Check_Connector_Id_Accumulator; typedef struct { int busno; char * connector_name; } Check_Busno_Accumulator; static bool check_connector_id( const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dirname=|%s|, fn=|%s|", dirname, fn); int debug_depth = (debug) ? 1 : -1; bool terminate = false; int this_connector_id = -1; Check_Connector_Id_Accumulator * accum = accumulator; // DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "accum->connector_id=%d, accum->connector_id_s=|%s|", // accum->connector_id, accum->connector_id_s); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "accum->connector_id=%d", accum->connector_id); bool connector_id_found = RPT_ATTR_INT(debug_depth, &this_connector_id, dirname, fn, "connector_id"); if (connector_id_found && this_connector_id == accum->connector_id) { accum->connector_name = strdup(fn); terminate = true; } DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, terminate, "accum->connector_name = |%s|", accum->connector_name); return terminate; } static bool check_busno( const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dirname=|%s|, fn=|%s|", dirname, fn); bool terminate = false; Check_Busno_Accumulator * accum = accumulator; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "accum->busno=%d", accum->busno); Connector_Bus_Numbers * cbn = calloc(1, sizeof(Connector_Bus_Numbers)); get_connector_bus_numbers(dirname, fn, cbn); if (cbn->i2c_busno == accum->busno) { terminate = true; accum->connector_name = g_strdup(fn); } free_connector_bus_numbers(cbn); DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, terminate, "accum->connector_name = |%s|", accum->connector_name); return terminate; } /** Given a DRM connector id, return the sysfs connector name * * @param connector_id * @return connector name, e.g. card1-DP-1, caller must free */ char * get_sys_drm_connector_name_by_connector_id(int connector_id) { bool debug = false; int depth = 0; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "connector_id=%d", connector_id); char connector_id_s[20]; snprintf(connector_id_s, 20, "%d", connector_id); Check_Connector_Id_Accumulator accum; accum.connector_id = connector_id; // accum.connector_id_s = connector_id_s; accum.connector_name = NULL; dir_foreach_terminatable( "/sys/class/drm", predicate_cardN_connector, // filter function check_connector_id, &accum, depth); DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %s", accum.connector_name); return accum.connector_name; } /** Given a I2C bus number, return the name of the * connector for that bus number. * * @param busno i2c bus number * @return connector name */ char * get_sys_drm_connector_name_by_busno(int busno) { bool debug = false; int depth = 0; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "busno=%d", busno); Check_Busno_Accumulator accum; accum.busno = busno; accum.connector_name = NULL; dir_foreach_terminatable( "/sys/class/drm", predicate_cardN_connector, // filter function check_busno, &accum, depth); DBGTRC_DONE(debug, DDCA_TRC_I2C, "Returning: %s", accum.connector_name); return accum.connector_name; } // // Checks whether connector_id exists // typedef struct { bool all_connectors_have_connector_id; } Check_Connector_Id_Present_Accumulator; static bool check_connector_id_present( const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dirname=|%s|, fn=|%s|", dirname, fn); int debug_depth = (debug) ? 1 : -1; bool terminate = false; int this_connector_id = -1; Check_Connector_Id_Present_Accumulator * accum = accumulator; DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "accum->all_connectors_have_connector_id=%s", SBOOL(accum->all_connectors_have_connector_id)); bool found = RPT_ATTR_INT(debug_depth, &this_connector_id, dirname, fn, "connector_id"); if (!found) { accum->all_connectors_have_connector_id = false; terminate = true; } DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, terminate, "accum->all_connectors_have_connector_id = %s", SBOOL(accum->all_connectors_have_connector_id)); return terminate; } /** Checks if attribute connector_id exists for all sysfs drm connectors * * @return true if all drm connectors have connector_id, false if not * * /remark * returns true if there are no drm_connectors */ bool all_sys_drm_connectors_have_connector_id_direct() { bool debug = false; int depth = 0; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "depth=%d", depth); Check_Connector_Id_Present_Accumulator accum; accum.all_connectors_have_connector_id = true; dir_foreach_terminatable( "/sys/class/drm", predicate_cardN_connector, // filter function check_connector_id_present, &accum, depth); DBGTRC_RET_BOOL(debug, DDCA_TRC_I2C, accum.all_connectors_have_connector_id, ""); return accum.all_connectors_have_connector_id; } // // Driver inquiry functions // /** Given the sysfs path to an adapter of some sort, returns * the name of its driver. * * @param adapter_path * @param depth logical indentation depth * @return name of driver module, NULL if not found * * Parameter **depth** behaves as usual for sysfs RPT_... functions. * If depth >= 0, sysfs attributes are reported. * If depth < 0, there is no output * * Caller is responsible for freeing the returned value */ char * get_driver_for_adapter(char * adapter_path, int depth) { char * basename = NULL; RPT_ATTR_REALPATH_BASENAME(depth, &basename, adapter_path, "driver", "module"); return basename; } /** Given a sysfs node, walk up the chain of device directory links * until an adapter node is found, and return the name of its driver. * * @param path e.g. /sys/bus/i2c/drivers/i2c-5 * @param depth logical indentation depth * @return sysfs path to adapter * * Parameter **depth** behaves as usual for sysfs RPT_... functions. * If depth >= 0, sysfs attributes are reported. * If depth < 0, there is no output * * Caller is responsible for freeing the returned value */ char * find_adapter_and_get_driver(char * path, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "path=%s, depth=%d", path, depth); assert(path); assert(strlen(path)>0); char * result = NULL; char * adapter_path = sysfs_find_adapter(path); if (adapter_path) { result = get_driver_for_adapter(adapter_path, depth); free(adapter_path); } DBGTRC_DONE(debug, DDCA_TRC_NONE,"Returning: %s", result); return result; } /** Returns the name of the video driver for an I2C bus. * * @param busno I2 bus number * @return driver name, NULL if can't determine * * Caller is responsible for freeing the returned string. */ char * get_driver_for_busno(int busno) { char path[PATH_MAX]; g_snprintf(path, PATH_MAX, "/sys/bus/i2c/devices/i2c-%d", busno); char * result = find_adapter_and_get_driver(path, -1); return result; } // // Possibly write "detect" to attribute status before reading connector attributes // with nvidia driver // void possibly_write_detect_to_status(const char * driver, const char * connector) { bool debug = false; assert(driver); assert(connector); DBGTRC_STARTING(debug, DDCA_TRC_NONE, "driver=%s, connector=%s", driver, connector); bool wrote_detect_to_status = false; bool do_driver = streq(driver, "nvidia"); if (enable_write_detect_to_status && do_driver && connector) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Writing detect to status"); char path[50]; g_snprintf(path, 50, "/sys/class/drm/%s/status", connector); FILE * f = fopen(path, "w"); if (f) { fputs("detect", f); fclose(f); wrote_detect_to_status = true; } else { DBGTRC(debug, DDCA_TRC_NONE, "fopen() failed. connector=%s, errno=%d", connector, errno); } } DBGTRC_DONE(debug, DDCA_TRC_NONE, "wrote detect to status: %s", SBOOL(wrote_detect_to_status)); } void possibly_write_detect_to_status_by_connector_path(const char * connector_path) { bool debug = false; int d = (debug) ? 1 : -1; if (enable_write_detect_to_status) { char * driver = find_adapter_and_get_driver((char*) connector_path, d); if (driver) { possibly_write_detect_to_status(driver, connector_path); free(driver); } } } void possibly_write_detect_to_status_by_connector_name(const char * connector) { bool debug = false; int d = (debug) ? 1 : -1; if (enable_write_detect_to_status) { char path[50]; g_snprintf(path, 50, "/sys/class/drm/%s", connector); char * driver = find_adapter_and_get_driver(path, d); if (driver) { possibly_write_detect_to_status(driver, connector); free(driver); } } } void possibly_write_detect_to_status_by_businfo(I2C_Bus_Info * businfo) { if (enable_write_detect_to_status) { if (businfo->driver) possibly_write_detect_to_status(businfo->driver, businfo->drm_connector_name); else { char * driver = get_driver_for_busno(businfo->busno); possibly_write_detect_to_status(businfo->driver, businfo->drm_connector_name); free(driver); } } } void possibly_write_detect_to_status_by_dref(Display_Ref * dref) { if (enable_write_detect_to_status) { if (dref->io_path.io_mode == DDCA_IO_I2C) { I2C_Bus_Info * businfo = dref->detail; possibly_write_detect_to_status_by_businfo(businfo); } else { if (dref->drm_connector) { possibly_write_detect_to_status_by_connector_name(dref->drm_connector); } } } } // // Sysfs_Connector_Names functions // /** Adds a single connector name, e.g. card0-HDMI-1, to the accumulated * list of all connections, and if the connector has a valid EDID, to * the accumulated list of connectors having a valid EDID. * * @param dirname directory to examine, /drm/cardN * @param simple_fn filename to examine * @param data pointer to Sysfs_Connector_Names instance * @param depth if >= 0, emits a report with this logical indentation depth */ STATIC void get_sysfs_drm_add_one_connector_name( const char * dirname, // /drm/cardN const char * simple_fn, // card0-HDMI-1 etc void * data, // pointer to Sysfs_Connector_Names collecting connector names int depth) { bool debug = false; Sysfs_Connector_Names * accum = (Sysfs_Connector_Names*) data; DBGMSF(debug, "Starting. dirname=%s, simple_fn=%s", dirname, simple_fn); g_ptr_array_add(accum->all_connectors, strdup(simple_fn)); possibly_write_detect_to_status_by_connector_name(simple_fn); bool collect = GET_ATTR_EDID(NULL, dirname, simple_fn, "edid"); if (collect) { g_ptr_array_add(accum->connectors_having_edid, g_strdup(simple_fn)); DBGMSF(debug, "Added connector %s", simple_fn); } DBGMSF(debug, "Connector %s has edid = %s", simple_fn, SBOOL(collect)); } /**Checks /sys/class/drm for connectors. * * @return struct Sysfs_Connector_Names * * @remark * Note the result is returned on the stack, not the heap */ Sysfs_Connector_Names get_sysfs_drm_connector_names() { bool debug = false; char * dname = #ifdef TARGET_BSD "/compat/linux/sys/class/drm"; #else "/sys/class/drm"; #endif DBGTRC_STARTING(debug, TRACE_GROUP, "Examining %s", dname); Sysfs_Connector_Names connector_names = {NULL, NULL}; connector_names.all_connectors = g_ptr_array_new_with_free_func(g_free); connector_names.connectors_having_edid = g_ptr_array_new_with_free_func(g_free); dir_filtered_ordered_foreach( dname, is_card_connector_dir, // filter function NULL, // ordering function get_sysfs_drm_add_one_connector_name, &connector_names, // accumulator 0); g_ptr_array_sort(connector_names.all_connectors, gaux_ptr_scomp); g_ptr_array_sort(connector_names.connectors_having_edid, gaux_ptr_scomp); DBGTRC_RET_STRUCT_VALUE(debug, DDCA_TRC_NONE, Sysfs_Connector_Names, dbgrpt_sysfs_connector_names, connector_names); return connector_names; } /** Tests if two Sysfs_Connector_Names instances have the same lists * for all connectors and for connectors having a valid EDID * * @param cn1 first instance * @param cn2 second instance * @return true if the arrays in each instance contain the same connector names */ bool sysfs_connector_names_equal(Sysfs_Connector_Names cn1, Sysfs_Connector_Names cn2) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, ""); if (IS_DBGTRC(debug, DDCA_TRC_NONE)) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "cn1 = %p:", cn1); dbgrpt_sysfs_connector_names(cn1, 1); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "cn2 = %p:", cn2); dbgrpt_sysfs_connector_names(cn2, 1); } bool result = gaux_unique_string_ptr_arrays_equal(cn1.all_connectors, cn2.all_connectors); result &= gaux_unique_string_ptr_arrays_equal(cn1.connectors_having_edid, cn2.connectors_having_edid); DBGTRC_RET_BOOL(debug, DDCA_TRC_NONE, result, ""); return result; } /** Emit a debugging report of a #Sysfs_Connector_Names instance. * * @param connector_names Sysfs_Connector_Names instance, not a pointer * @param depth logical indentation depth */ void dbgrpt_sysfs_connector_names(Sysfs_Connector_Names connector_names, int depth) { rpt_vstring(depth, "all_connectors @%p: %s", connector_names.all_connectors, join_string_g_ptr_array_t(connector_names.all_connectors, ", ") ); rpt_vstring(depth, "connectors_having_edid @%p: %s", connector_names.connectors_having_edid, join_string_g_ptr_array_t(connector_names.connectors_having_edid, ", ") ); #ifdef FOR_DEBUGGING rpt_vstring(depth, "all_connectors @%p:", connector_names.all_connectors); rpt_vstring(depth+3, "%s", join_string_g_ptr_array_t(connector_names.all_connectors, ", ") ); rpt_vstring(depth, "connectors_having_edid @%p:", connector_names.connectors_having_edid); rpt_vstring(depth+3, "%s", join_string_g_ptr_array_t(connector_names.connectors_having_edid, ", ") ); #endif } void free_sysfs_connector_names_contents(Sysfs_Connector_Names names_struct) { if (names_struct.all_connectors) { g_ptr_array_free(names_struct.all_connectors, true); names_struct.all_connectors = NULL; } if (names_struct.connectors_having_edid) { g_ptr_array_free(names_struct.connectors_having_edid, true); names_struct.connectors_having_edid = NULL; } } Sysfs_Connector_Names copy_sysfs_connector_names_struct(Sysfs_Connector_Names original) { Sysfs_Connector_Names result = {NULL, NULL}; result.all_connectors = gaux_deep_copy_string_array(original.all_connectors); result.connectors_having_edid = gaux_deep_copy_string_array(original.connectors_having_edid); return result; } // Note: On amdgpu, for DP device realpath is connector with EDID, for HDMI and DVI device is adapter /** Searches connectors for one with matching EDID * * @param connector_names array of connector names * @param edid pointer to 128 byte EDID * @return name of connector with matching EDID (caller must free) */ char * find_sysfs_drm_connector_name_by_edid(GPtrArray* connector_names, Byte * edid) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_I2C, "edid=%p", edid); char * result = NULL; for (int ndx = 0; ndx < connector_names->len; ndx++) { char * connector_name = g_ptr_array_index(connector_names, ndx); GByteArray * sysfs_edid; int depth = (debug) ? 1 : -1; possibly_write_detect_to_status_by_connector_name(connector_name); RPT_ATTR_EDID(depth, &sysfs_edid, "/sys/class/drm", connector_name, "edid"); if (sysfs_edid) { if (sysfs_edid->len >= 128 && memcmp(sysfs_edid->data, edid, 128) == 0) result = g_strdup(connector_name); g_byte_array_free(sysfs_edid, true); if (result) break; } } DBGTRC_RET_STRING(debug, DDCA_TRC_I2C, result, ""); return result; } /* i915, amdgpu, radeon, nouveau and (likely) other video drivers that share * the kernel's DRM code can be relied on to maintain the edid, * status, and enabled attributes as displays are connected and * disconnected. * * Unfortunately depending version, the nvidia driver does not. * Attribute enabled is always "disabled". It may be the case * that the edid value is that of the monitor initially connected. * What has been observed is that if the driver does change the * edid attribute, it also properly sets status to "connected" or * disconnected. If it does not, status is always "disconnected", * whether or not a monitor is connected. */ typedef struct { bool known_good_driver_seen; bool other_driver_seen; uint8_t nvidia_connector_ct; uint8_t nvidia_connector_w_edid_ct; uint8_t nvidia_connector_w_edid_and_connected_ct; } Sysfs_Reliability_Accumulator; static bool known_reliable_driver(const char * driver) { return streq(driver, "i915") || streq(driver, "xe") || streq(driver, "amdgpu") || streq(driver, "radeon") || streq(driver, "nouveau"); } static void check_connector_reliability( const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "dirname=|%s|, fn=|%s|", dirname, fn); int debug_depth = (debug) ? 1 : -1; Sysfs_Reliability_Accumulator * accum = accumulator; char buf[PATH_MAX]; g_snprintf(buf, PATH_MAX, "%s/%s", dirname, fn); char * driver = find_adapter_and_get_driver(buf, debug_depth); if (known_reliable_driver(driver)) { accum->known_good_driver_seen = true; } else if (streq(driver, "nvidia")) { // Per Michael Hamilton, testing that status == "connected" for any connector with EDID // does not guarantee that DRM connector is updated when a display is connected/disconnected accum->nvidia_connector_ct++; GByteArray * edid_byte_array = NULL; possibly_write_detect_to_status_by_connector_name(fn); RPT_ATTR_EDID(debug_depth, &edid_byte_array, dirname, fn, "edid"); // e.g. /sys/class/drm/card0-DP-1/edid // DBGMSG("edid_byte_array=%p", (void*)edid_byte_array); if (edid_byte_array) { accum->nvidia_connector_w_edid_ct++; g_byte_array_free(edid_byte_array,true); char * status = NULL; RPT_ATTR_TEXT(debug_depth, &status, dirname, fn, "status"); // e.g. /sys/class/drm/card0-DP-1/status if (status) { if (streq(status, "connected")) accum->nvidia_connector_w_edid_and_connected_ct++; free(status); } } } else { accum->other_driver_seen = true; } free(driver); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } static bool drm_reliability_checked = false; static bool other_drivers_seen = false; static bool nvidia_connectors_reliable = false; static bool nvidia_connectors_exist = false; static void check_sysfs_reliability() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, ""); Sysfs_Reliability_Accumulator * accum = calloc(1, sizeof(Sysfs_Reliability_Accumulator)); int depth=0; dir_foreach( "/sys/class/drm", predicate_cardN_connector, // filter function check_connector_reliability, accum, depth); drm_reliability_checked = true; nvidia_connectors_exist = (accum->nvidia_connector_ct > 0); // known_good_driver_seen = > 0; // This appears to be a necessary, but not sufficient, condition nvidia_connectors_reliable = accum->nvidia_connector_w_edid_ct > 0 && accum->nvidia_connector_w_edid_ct == accum->nvidia_connector_w_edid_and_connected_ct; other_drivers_seen = accum->other_driver_seen; free(accum); DBGTRC_DONE(debug, DDCA_TRC_NONE, "nvidia_connectors_exist=%s, nvidia_connectors_reliable=%s", sbool(nvidia_connectors_exist), sbool(nvidia_connectors_reliable)); } bool force_sysfs_unreliable = false; bool force_sysfs_reliable = false; bool enable_write_detect_to_status = false; /** Reports whether sysfs attributes for DRM connectors using the given video * driver reliably reflect display connection and disconnection. * * @param driver name of driver * @return true if reliable, false if not */ bool is_sysfs_reliable_for_driver(const char * driver) { bool debug = false; bool result = false; if (!drm_reliability_checked) check_sysfs_reliability(); if (force_sysfs_unreliable) result = false; else if (force_sysfs_reliable) result = true; else { if (streq(driver, "nvidia")) result = nvidia_connectors_reliable; else result = known_reliable_driver(driver); } DBGF(debug, "Executed. Returning %s, driver=%s", SBOOL(result), driver); return result; } /** Reports whether sysfs attributes for the DRM connector associated with an * I2C bus number reliably reflect display connection and disconnection. * * @param busno I2C bus number * @return true if reliable, false if not */ bool is_sysfs_reliable_for_busno(int busno) { char * driver = get_driver_for_busno(busno); bool result = is_sysfs_reliable_for_driver(driver); free(driver); return result; } /** Reports whether sysfs attributes for all DRM connectors reliably reflect * display connection and disconnection. * * @return true if reliable, false if not */ bool is_sysfs_reliable() { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "force_sysfs_unreliable=%s, force_sysfs_reliable=%s", sbool(force_sysfs_unreliable), sbool(force_sysfs_reliable)); if (!drm_reliability_checked) check_sysfs_reliability(); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "other_drivers_seen=%s, nvidia_connectors_exist=%s", sbool(other_drivers_seen), sbool(nvidia_connectors_exist)); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "nvdia_connectors_reliable=%s", SBOOL(nvidia_connectors_reliable)); bool result = true; if (force_sysfs_unreliable) result = false; else if (force_sysfs_reliable) result = true; else if (other_drivers_seen) result = false; else if (nvidia_connectors_exist) result = nvidia_connectors_reliable; DBGTRC_EXECUTED(debug, DDCA_TRC_NONE, "Returning %s", SBOOL(result)); return result; } // moved from sysfs_i2c_util.c: // The following functions are not really generic sysfs utilities, and more // properly belong in a file in subdirectory base, but to avoid yet more file // proliferation are included here. /** Gets the sysfs name of an I2C device, * i.e. the value of /sys/bus/i2c/devices/i2c-n/name * * \param busno I2C bus number * \return newly allocated string containing attribute value, * NULL if not found * * \remark * Caller is responsible for freeing returned value */ char * get_i2c_device_sysfs_name(int busno) { char workbuf[50]; snprintf(workbuf, 50, "/sys/bus/i2c/devices/i2c-%d/name", busno); char * name = file_get_first_line(workbuf, /*verbose */ false); // DBGMSG("busno=%d, returning: %s", busno, bool_repr(result)); return name; } /** Given a sysfs node, walk up the chain of device directory links * until an adapter node is found. * * @param path e.g. /sys/bus/i2c/devices/i2c-5 * @param depth logical indentation depth * @return sysfs path to adapter * * Parameter **depth** behaves as usual for sysfs RPT_... functions. * If depth >= 0, sysfs attributes are reported. * If depth < 0, there is no output * * Caller is responsible for freeing the returned value */ #ifdef OLD char * sysfs_find_adapter_old(char * path) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "path=%s", path); assert(path); int depth = (debug) ? 2 : -1; char * devpath = NULL; // #ifdef OUT if ( RPT_ATTR_NOTE_SUBDIR(depth, NULL, path, "device") ) { if ( RPT_ATTR_TEXT(depth, NULL, path, "device", "class") ) { RPT_ATTR_REALPATH(depth, &devpath, path, "device"); } else { char p2[PATH_MAX]; g_snprintf(p2, PATH_MAX, "%s/device", path); devpath = sysfs_find_adapter(p2); } } else // #endif { char * rp1 = NULL; char * rp2 = NULL; RPT_ATTR_REALPATH(depth, &rp1, path); if ( RPT_ATTR_TEXT(depth, NULL, rp1, "class")) { devpath = rp1; } else { RPT_ATTR_REALPATH(depth, &rp2, rp1, ".."); free(rp1); DBGF(debug, " rp2 = %s", rp2); if ( RPT_ATTR_TEXT(depth, NULL, rp2, "../class")) devpath = rp2; else free(rp2); } } DBGTRC_DONE(debug,TRACE_GROUP, "Returning: %s", devpath); return devpath; } #endif char * sysfs_find_adapter(char * path) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "path=%s", path); assert(path); int depth = (IS_DBGTRC(debug, DDCA_TRC_NONE)) ? 2 : -1; char * devpath = NULL; char * rp1 = strdup(path); char * rp2 = NULL; // strlen(rp1) > 1 shuld be unnecessary, but just in case: while(!devpath && strlen(rp1) > 0 && !streq(rp1, "/")) { if ( RPT_ATTR_TEXT(depth, NULL, rp1, "class")) { devpath = rp1; } else { RPT_ATTR_REALPATH(depth, &rp2, rp1, ".."); free(rp1); rp1 = rp2; rp2 = NULL; } } if (!devpath) free(rp1); DBGTRC_DONE(debug,TRACE_GROUP, "Returning: %s", devpath); return devpath; } /** Gets the driver name of an I2C device, * i.e. the basename of /sys/bus/i2c/devices/i2c-n/device/driver/module * * \param busno I2C bus number * \return newly allocated string containing driver name * NULL if not found * * \remark * Caller is responsible for freeing returned value */ char * get_i2c_sysfs_driver_by_busno(int busno) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d", busno); int depth = (debug) ? 2 : -1; char * driver_name = NULL; char workbuf[100]; #ifdef FAILS_FOR_NVIDIA snprintf(workbuf, 100, "/sys/bus/i2c/devices/i2c-%d/device/driver/module", busno); DBGF(debug, "workbuf(1) = %s", workbuf); driver_name = get_rpath_basename(workbuf); if (!driver_name) { snprintf(workbuf, 100, "/sys/bus/i2c/devices/i2c-%d/device/device/device/driver/module", busno); DBGF(debug, "workbuf(2) = %s", workbuf); driver_name = get_rpath_basename(workbuf); } #endif snprintf(workbuf, 100, "/sys/bus/i2c/devices/i2c-%d", busno); DBGF(debug, "workbuf(3) = %s", workbuf); char * adapter_path = sysfs_find_adapter(workbuf); if (adapter_path) { // RPT_ATTR_TEXT( depth, &result->adapter_class, adapter_path, "class"); RPT_ATTR_REALPATH_BASENAME(depth, &driver_name, adapter_path, "driver"); // RPT_ATTR_TEXT( depth, &result->driver_version, adapter_path, "driver/module/version"); free(adapter_path); } DBGTRC_DONE(debug, TRACE_GROUP, "busno=%d, Returning %s", busno, driver_name); return driver_name; } #ifdef UNUSED /** Gets the name of the driver for a /dev/i2c-N device, * i.e. the basename of /sys/bus/i2c/devices/i2c-n/device/driver/module * * \param device_name e.g. /dev/i2c-n * \return newly allocated string containing driver name * NULL if not found * * \remark * Caller is responsible for freeing returned value */ char * get_i2c_sysfs_driver_by_device_name(char * device_name) { bool debug = false; if (debug) printf("(%s) Starting. device_name = %s", __func__, device_name); char * driver_name = NULL; int busno = extract_number_after_hyphen(device_name); if (busno >= 0) { driver_name = get_i2c_sysfs_driver_by_busno(busno); } if (debug) printf("(%s) Done. Returning: %s", __func__, driver_name); return driver_name; } #endif #ifdef UNUSED /** Gets the name of the driver for a /dev/i2c-N device, specified by its file descriptor. * i.e. the basename of /sys/bus/i2c/devices/i2c-n/device/driver/module * * \param fd file descriptor * \return newly allocated string containing driver name * NULL if not found * * \remark * Caller is responsible for freeing returned value */ char * get_i2c_sysfs_driver_by_fd(int fd) { bool debug = false; char * driver_name = NULL; int busno = extract_number_after_hyphen(filename_for_fd_t(fd)); if (busno >= 0) { driver_name = get_i2c_sysfs_driver_by_busno(busno); } if (debug) printf("(%s) fd=%d, returning %s\n", __func__, fd, driver_name); return driver_name; } #endif /** Gets the class of an I2C device, * i.e. /sys/bus/i2c/devices/i2c-n/device/class * or /sys/bus/i2c/devices/i2c-n/device/device/device/class * * \param busno I2C bus number * \return device class * 0 if not found (should never occur) */ uint32_t get_i2c_device_sysfs_class(int busno) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d"); uint32_t result = 0; char workbuf[100]; snprintf(workbuf, 100, "/sys/bus/i2c/devices/i2c-%d/device", busno); char * s_class = read_sysfs_attr(workbuf, "class", /*verbose*/ false); if (!s_class) { snprintf(workbuf, 100, "/sys/bus/i2c/devices/i2c-%d/device/device/device", busno); s_class = read_sysfs_attr(workbuf, "class", /*verbose*/ false); } if (s_class) { // printf("(%s) Found %s/class\n", __func__, workbuf); /* bool ok =*/ str_to_int(s_class, (int*) &result, 16); // if fails, &result unchanged free(s_class); } else{ // printf("(%s) class for bus %d not found\n", __func__, busno); } DBGTRC_DONE(debug, TRACE_GROUP, "busno=%d, Returning 0x%08x", busno, result); return result; } static bool ignorable_i2c_device_sysfs_name(const char * name, const char * driver) { bool result = false; const char * ignorable_prefixes[] = { "SMBus", "Synopsys DesignWare", "soc:i2cdsi", // Raspberry Pi "smu", // Mac G5, probing causes system hang "mac-io", // Mac G5 "u4", // Mac G5 "AMDGPU SMU", // AMD Navi2 variants, e.g. RX 6000 series NULL }; if (name) { if (starts_with_any(name, ignorable_prefixes) >= 0) result = true; else if (streq(driver, "nouveau")) { if ( !str_starts_with(name, "nvkm-") ) { result = true; // printf("(%s) name=|%s|, driver=|%s| - Ignore\n", __func__, name, driver); } } } // printf("(%s) name=|%s|, driver=|%s|, returning: %s\n", __func__, name, driver, sbool(result)); return result; } /** Checks if an I2C bus cannot be a DDC/CI connected monitor * and therefore can be ignored, e.g. if it is an SMBus device. * * \param busno I2C bus number * \return true if ignorable, false if not */ bool sysfs_is_ignorable_i2c_device(int busno) { bool debug = false; bool ignorable = false; DBGF(debug, "Starting. busno=%d", busno); // It is possible for a display device to have an I2C bus // that should be ignored. Recent AMD Navi board (e.g. RX 6000) // have an I2C SMU bus that will hang the card if probed. // So first check for specific device names to ignore. // If not found, then base the result on the device's class. char * name = get_i2c_device_sysfs_name(busno); char * driver = get_i2c_sysfs_driver_by_busno(busno); if (name) { ignorable = ignorable_i2c_device_sysfs_name(name, driver); DBGF(debug, " busno=%d, name=|%s|, ignorable_i2c_sysfs_name() returned %s", busno, name, sbool(ignorable)); } free(name); // safe if NULL free(driver); // ditto if (!ignorable) { uint32_t class = get_i2c_device_sysfs_class(busno); if (class) { DBGF(debug, " class = 0x%08x", class); uint32_t cl2 = class & 0xffff0000; DBGF(debug, " cl2 = 0x%08x", cl2); ignorable = (cl2 != 0x030000 && cl2 != 0x0a0000); // docking station } } DBGF(debug, "busno=%d, returning: %s", busno, sbool(ignorable)); return ignorable; } int search_all_businfo_records_by_connector_name(char *connector_name) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "connector_name = |%s|", connector_name); // reads connector dir directly, i.e. does not retrieve persistent data structure // Sys_Drm_Connector * conn = get_drm_connector(connector_name, debug_depth); // int busno = conn->i2c_busno; // free(conn); Connector_Bus_Numbers *cbn = calloc(1, sizeof(Connector_Bus_Numbers)); get_connector_bus_numbers("/sys/class/drm", connector_name, cbn); int busno = cbn->i2c_busno; free_connector_bus_numbers(cbn); if (busno < 0) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Examining businfo records..."); // look through all businfo records for one with the connector name for (int ndx = 0; ndx < all_i2c_buses->len; ndx++) { I2C_Bus_Info *businfo = g_ptr_array_index(all_i2c_buses, ndx); DBGMSG("Examining businfo record for bus %d, I2C_BUS_PROBED=%s, connector_found_by=%s", businfo->busno, sbool(businfo->flags & I2C_BUS_PROBED), drm_connector_found_by_name(businfo->drm_connector_found_by)); // need to check if businfo record is valid? if (streq(businfo->drm_connector_name, connector_name)) { busno = businfo->busno; break; } } } DBGTRC_DONE(debug, TRACE_GROUP, "returning busno %d", busno); return busno; } void init_i2c_sysfs_base() { RTTI_ADD_FUNC(possibly_write_detect_to_status); RTTI_ADD_FUNC(sysfs_find_adapter); RTTI_ADD_FUNC(get_i2c_sysfs_driver_by_busno); RTTI_ADD_FUNC(get_i2c_device_sysfs_class); RTTI_ADD_FUNC(check_connector_reliability); RTTI_ADD_FUNC(check_sysfs_reliability); RTTI_ADD_FUNC(dbgrpt_sysfs_basic_connector_attributes); RTTI_ADD_FUNC(find_adapter_and_get_driver); RTTI_ADD_FUNC(find_sysfs_drm_connector_name_by_edid); RTTI_ADD_FUNC(get_connector_bus_numbers); RTTI_ADD_FUNC(get_sys_drm_connector_name_by_connector_id); RTTI_ADD_FUNC(is_sysfs_reliable); RTTI_ADD_FUNC(search_all_businfo_records_by_connector_name); #ifdef UNUSED RTTI_ADD_FUNC(get_sys_video_devices); #endif } ddcutil-2.2.0/src/sysfs/sysfs_conflicting_drivers.c0000644000175000001440000001766614754153540016236 /** @file sysfs_conflicting_drivers.c */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/debug_util.h" #ifdef USE_LIBDRM #include "util/drm_common.h" #endif #include "util/edid.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/utilrpt.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/i2c_bus_base.h" #include "base/rtti.h" #include "sysfs_sys_drm_connector.h" #include "sysfs_conflicting_drivers.h" static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SYSFS; // // Scan for conflicting modules/drivers: Struct Sys_Conflicting_Driver // void free_sys_conflicting_driver(Sys_Conflicting_Driver * rec) { bool debug = false; DBGMSF(debug, "rec=%p", (void*)rec); if (rec) { free(rec->n_nnnn); free(rec->name); free(rec->driver_module); free(rec->modalias); free(rec->eeprom_edid_bytes); free(rec); } } #ifdef UNUSED static void free_sys_conflicting_driver0(void * rec) { free_sys_conflicting_driver((Sys_Conflicting_Driver*) rec); } #endif char * best_conflicting_driver_name(Sys_Conflicting_Driver* rec) { char * result = NULL; if (rec->name) result = rec->name; else if (rec->driver_module) result = rec->driver_module; else result = rec->modalias; return result; } void dbgrpt_conflicting_driver(Sys_Conflicting_Driver * conflict, int depth) { int d1 = depth+1; rpt_structure_loc("Sys_Conflicting_Driver", conflict, depth); rpt_vstring(d1, "i2c_busno: %d", conflict->i2c_busno); rpt_vstring(d1, "n_nnnn: %s", conflict->n_nnnn); rpt_vstring(d1, "name: %s", conflict->name); rpt_vstring(d1, "driver/module: %s", conflict->driver_module); rpt_vstring(d1, "modalias: %s", conflict->modalias); rpt_vstring(d1, "best conflicting driver name: %s", best_conflicting_driver_name(conflict)); if (conflict->eeprom_edid_bytes) { rpt_vstring(d1, "eeprom_edid_bytes:"); rpt_hex_dump(conflict->eeprom_edid_bytes, conflict->eeprom_edid_size, d1); } } // typedef Dir_Foreach_Func void one_n_nnnn( const char * dir_name, // e.g. /sys/bus/i2c/devices/i2c-4 const char * fn, // e.g. 4-0037 void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, fn=%s, depth=%d", dir_name, fn, depth); GPtrArray* conflicting_drivers= accumulator; Sys_Conflicting_Driver * conflicting_driver = calloc(1, sizeof(Sys_Conflicting_Driver)); DBGMSF(debug, "Allocated Sys_Conflicting_Driver %p", (void*) conflicting_driver); conflicting_driver->n_nnnn = g_strdup(fn); RPT_ATTR_TEXT(depth, &conflicting_driver->name, dir_name, fn, "name"); if (str_ends_with(fn, "0050")) { GByteArray * edid_byte_array = NULL; RPT_ATTR_EDID(depth, &edid_byte_array, dir_name, fn, "eeprom"); if (edid_byte_array) { conflicting_driver->eeprom_edid_size = edid_byte_array->len; conflicting_driver->eeprom_edid_bytes = g_byte_array_free(edid_byte_array, false); } } // N. subdirectory driver does not always exist, e.g. for ddcci - N-0037 RPT_ATTR_REALPATH_BASENAME(depth, &conflicting_driver->driver_module, dir_name, fn, "driver/module"); RPT_ATTR_TEXT(depth, &conflicting_driver->modalias, dir_name, fn, "modalias"); g_ptr_array_add(conflicting_drivers, conflicting_driver); if (depth >= 0) rpt_nl(); DBGTRC_DONE(debug, TRACE_GROUP, ""); } static void collect_conflicting_drivers0(GPtrArray * conflicting_drivers, int busno, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, conflicting_drivers=%p", busno, (void*)conflicting_drivers); char i2c_bus_path[PATH_MAX]; g_snprintf(i2c_bus_path, sizeof(i2c_bus_path), "/sys/bus/i2c/devices/i2c-%d", busno); char sbusno[4]; g_snprintf(sbusno, 4, "%d", busno); int old_ct = conflicting_drivers->len; dir_ordered_foreach_with_arg( i2c_bus_path, // directory predicate_exact_D_00hh, // filter function sbusno, // filter function argument NULL, // ordering function one_n_nnnn, // process dir named like 4-0050 conflicting_drivers, // accumulator depth); for (int ndx=old_ct; ndx < conflicting_drivers->len; ndx++) { Sys_Conflicting_Driver * cur = g_ptr_array_index(conflicting_drivers, ndx); cur->i2c_busno = busno; } DBGTRC_DONE(debug, TRACE_GROUP, "" ); } GPtrArray * collect_conflicting_drivers(int busno, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, depth=%d", busno, depth); GPtrArray * conflicting_drivers = g_ptr_array_new_with_free_func((GDestroyNotify) free_sys_conflicting_driver); collect_conflicting_drivers0(conflicting_drivers, busno, depth); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", (void*)conflicting_drivers); return conflicting_drivers; } GPtrArray * collect_conflicting_drivers_for_any_bus(int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); GPtrArray* all_connectors = get_sys_drm_connectors(false); GPtrArray * conflicting_drivers = g_ptr_array_new_with_free_func((GDestroyNotify) free_sys_conflicting_driver); for (int ndx = 0; ndx < all_connectors->len; ndx++) { Sys_Drm_Connector * cur = g_ptr_array_index(all_connectors, ndx); DBGMSF(debug, "cur->i2c_busno=%d", cur->i2c_busno); if (cur->i2c_busno >= 0) // may not have been set collect_conflicting_drivers0(conflicting_drivers, cur->i2c_busno, depth); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", (void*) conflicting_drivers); return conflicting_drivers; } void report_conflicting_drivers(GPtrArray * conflicts, int depth) { if (conflicts && conflicts->len > 0) { for (int ndx=0; ndx < conflicts->len; ndx++) { Sys_Conflicting_Driver * cur = g_ptr_array_index(conflicts, ndx); dbgrpt_conflicting_driver(cur, depth); } } else rpt_label(depth, "No conflicting drivers found"); } GPtrArray * conflicting_driver_names(GPtrArray * conflicts) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "conflicts=%p", (void*)conflicts); GPtrArray * result = g_ptr_array_new_with_free_func(g_free); for (int ndx = 0; ndx < conflicts->len; ndx++) { Sys_Conflicting_Driver * cur = g_ptr_array_index(conflicts, ndx); gaux_unique_string_ptr_array_include(result, best_conflicting_driver_name(cur)); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", join_string_g_ptr_array_t(result, " + ") ); return result; } char * conflicting_driver_names_string_t(GPtrArray * conflicts) { GPtrArray * driver_names = conflicting_driver_names(conflicts); char * result = join_string_g_ptr_array_t(driver_names, ". "); g_ptr_array_free(driver_names, true); return result; } void free_conflicting_drivers(GPtrArray* conflicts) { if (conflicts) g_ptr_array_free(conflicts, true); } void init_i2c_sysfs_conflicting_drivers() { RTTI_ADD_FUNC(one_n_nnnn); RTTI_ADD_FUNC(collect_conflicting_drivers0); RTTI_ADD_FUNC(collect_conflicting_drivers); RTTI_ADD_FUNC(collect_conflicting_drivers_for_any_bus); RTTI_ADD_FUNC(conflicting_driver_names); } // // End of conflicting drivers section // ddcutil-2.2.0/src/sysfs/sysfs_i2c_info.c0000644000175000001440000002745214754153540013663 /** @file sysfs_i2c_info.c */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/debug_util.h" #ifdef USE_LIBDRM #include "util/drm_common.h" #endif #include "util/edid.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/utilrpt.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/i2c_bus_base.h" #include "base/rtti.h" #include "sysfs_base.h" #include "sysfs_i2c_info.h" static const DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SYSFS; // // Sysfs_I2C_Info // void dbgrpt_sysfs_i2c_info(Sysfs_I2C_Info * info, int depth) { int d1 = depth+1; rpt_structure_loc("Sysfs_I2C_Info", info, depth); rpt_vstring(d1, "busno: %d", info->busno); rpt_vstring(d1, "name: %s", info->name); rpt_vstring(d1, "adapter_path: %s", info->adapter_path); rpt_vstring(d1, "adapter_class: %s", info->adapter_class); rpt_vstring(d1, "driver: %s", info->driver); rpt_vstring(d1, "driver_version: %s", info->driver_version); rpt_vstring(d1, "conflicting_driver_names: %s", join_string_g_ptr_array_t(info->conflicting_driver_names, ", ") ); #ifdef USE_LIBDRM if (info->adapter_path) { rpt_vstring(d1, "adapter supports DRM: %s", sbool(adapter_supports_drm_using_drm_api(info->adapter_path))); } #endif } void dbgrpt_all_sysfs_i2c_info(GPtrArray * infos, int depth) { rpt_vstring(depth, "All Sysfs_I2C_Info records"); if (infos && infos->len > 0) { for (int ndx = 0; ndx < infos->len; ndx++) dbgrpt_sysfs_i2c_info(g_ptr_array_index(infos,ndx), depth+1); } else rpt_vstring(depth+1, "None"); } static GPtrArray * all_i2c_info = NULL; void free_sysfs_i2c_info(Sysfs_I2C_Info * info) { if (info) { free(info->name); free(info->adapter_path); free(info->adapter_class); free(info->driver); free(info->driver_version); if (info->conflicting_driver_names) g_ptr_array_free(info->conflicting_driver_names, true); free(info); } } char * best_driver_name_for_n_nnnn(const char * dirname, const char * fn, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, fn=%s", dirname, fn); char * best_name = NULL; char * attr = "name"; RPT_ATTR_TEXT(depth, &best_name, dirname, fn, attr); if (!best_name) { // N. subdirectory driver does not always exist, e.g. for ddcci N-0037 attr = "driver/module"; RPT_ATTR_REALPATH_BASENAME(depth, &best_name, dirname, fn, attr); if (!best_name) { attr = "modalias"; RPT_ATTR_TEXT(depth, &best_name, dirname, fn, attr); } } DBGTRC_DONE(debug, TRACE_GROUP, "using attr=%s, returning: %s", attr, best_name); return best_name; } // typedef Dir_Foreach_Func void simple_one_n_nnnn( const char * dir_name, // e.g. /sys/bus/i2c/devices/i2c-4 const char * fn, // e.g. 4-0037 void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, fn=%s, depth=%d", dir_name, fn, depth); char * best_name = best_driver_name_for_n_nnnn(dir_name, fn, depth); if (best_name) { gaux_unique_string_ptr_array_include(accumulator,best_name ); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "appending: |%s|", best_name); free(best_name); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } Sysfs_I2C_Info * get_i2c_driver_info(int busno, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, depth=%d", busno, depth); if (IS_DBGTRC(debug, DDCA_TRC_NONE) && depth < 0) depth = 2; char bus_path[40]; g_snprintf(bus_path, 40, "/sys/bus/i2c/devices/i2c-%d", busno); Sysfs_I2C_Info * result = calloc(1, sizeof(Sysfs_I2C_Info)); result->busno = busno; RPT_ATTR_TEXT(depth, &result->name, bus_path, "name"); char * adapter_path = sysfs_find_adapter(bus_path); if (adapter_path) { result->adapter_path = adapter_path; RPT_ATTR_TEXT( depth, &result->adapter_class, adapter_path, "class"); RPT_ATTR_REALPATH_BASENAME(depth, &result->driver, adapter_path, "driver"); RPT_ATTR_TEXT( depth, &result->driver_version, adapter_path, "driver/module/version"); } DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "Sysfs_I2C_Info", dbgrpt_sysfs_i2c_info, result); if (debug) rpt_nl(); return result; } Sysfs_I2C_Info * get_basic_i2c_driver_info(int busno) { return get_i2c_driver_info(busno, -1); } /** Returns a newly allocated #Sysfs_I2c_Info struct describing * a /sys/bus/i2c/devices/i2c-N instance, and optionally reports the * result of examining the instance * * @param busno i2c bus number * @param depth logical indentation depth, if < 0 do not emit report * @result newly allocated #Sys_I2c_Info struct */ Sysfs_I2C_Info * get_i2c_info(int busno, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, depth=%d", busno, depth); char bus_path[40]; g_snprintf(bus_path, 40, "/sys/bus/i2c/devices/i2c-%d", busno); #ifdef OLD Sysfs_I2C_Info * result = calloc(1, sizeof(Sysfs_I2C_Info)); result->busno = busno; RPT_ATTR_TEXT(depth, &result->name, bus_path, "name"); char * adapter_path = find_adapter(bus_path, depth); if (adapter_path) { result->adapter_path = adapter_path; RPT_ATTR_TEXT( depth, &result->adapter_class, adapter_path, "class"); RPT_ATTR_REALPATH_BASENAME(depth, &result->driver, adapter_path, "driver"); RPT_ATTR_TEXT( depth, &result->driver_version, adapter_path, "driver/module/version"); } #endif Sysfs_I2C_Info * result = get_i2c_driver_info(busno, depth); result->conflicting_driver_names = g_ptr_array_new_with_free_func(g_free); DBGMSF(debug, "Looking for D-00hh match"); char sbusno[4]; g_snprintf(sbusno, 4, "%d",busno); dir_ordered_foreach_with_arg( "/sys/bus/i2c/devices", predicate_exact_D_00hh, sbusno, NULL, // compare func simple_one_n_nnnn, result->conflicting_driver_names, depth); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "After collecting /sys/bus/i2c/devices subdirectories: %s", join_string_g_ptr_array_t(result->conflicting_driver_names, ", ")); dir_filtered_ordered_foreach( bus_path, // e.g. /sys/bus/i2c/devices/i2c-0 is_n_nnnn, NULL, simple_one_n_nnnn, result->conflicting_driver_names, depth); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "After collecting %s subdirectories: %s", bus_path, join_string_g_ptr_array_t(result->conflicting_driver_names, ", ")); DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", (void*) result); if (debug) rpt_nl(); return result; } /** Function of typedef Dir_Foreach_Func, called from #get_all_i2c_info() * for each i2c-N device in /sys/bus/i2c/devices * * @param dir_name always /sys/bus/i2c/devices * @param fn i2c-N * @param accumulator GPtrArray to which to add newly allocated Sysfs_I2c_Info * instance */ // typedef Dir_Foreach_Func void get_single_i2c_info( const char * dir_name, // e.g. /sys/bus/i2c/devices const char * fn, // e.g. i2c-3 void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dir_name=%s, fn=%s, depth=%d", dir_name, fn, depth); int busno = i2c_name_to_busno(fn); if (busno >= 0) { Sysfs_I2C_Info * info = get_i2c_info(busno, depth); g_ptr_array_add(accumulator, info); } DBGTRC_DONE(debug, TRACE_GROUP, "accumulator now has %d records", ((GPtrArray*)accumulator)->len); } /** Returns an array of #Sysfs_I2C_Info describing each i2c-N device in * directory /sys/bus/i2c/devices, and optionally reports the contents * * @param rescan if true, discard cached array and rescan * @param depth logical indentation depth, if < 0 do not emit report * @return pointer to array containing one #Sysfs_I2C_Info for each i2c-N device * * The returned array is cached. Caller should not free. */ GPtrArray * get_all_sysfs_i2c_info(bool rescan, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "depth=%d", depth); if (all_i2c_info && rescan) { g_ptr_array_free(all_i2c_info, true); all_i2c_info = NULL; } if (!all_i2c_info) { all_i2c_info = g_ptr_array_new_with_free_func((GDestroyNotify) free_sysfs_i2c_info); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "newly allocated all_i2c_info=%p", all_i2c_info); dir_ordered_foreach( "/sys/bus/i2c/devices", predicate_i2c_N, i2c_compare, get_single_i2c_info, all_i2c_info, depth); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning pointer to GPtrArray=%p, containing %d records", (void*)all_i2c_info, all_i2c_info->len); return all_i2c_info; } #ifdef UNUSED char * get_conflicting_drivers_for_bus(int busno) { Sysfs_I2C_Info * info = get_i2c_info(busno, -1); char * result = join_string_g_ptr_array(info->conflicting_driver_names, ", "); free_sysfs_i2c_info(info); return result; } #endif #ifdef UNUSED static bool is_potential_i2c_display(Sysfs_I2C_Info * info) { assert(info); bool debug = false; char * uname = strdup_uc(info->name); bool result = str_starts_with(info->adapter_class, "0x03") && str_contains(uname, "SMBUS")<0; free(uname); DBGMSF(debug, "busno=%d, adapter_class=%s, name=%s, returning %s", info->busno, info->adapter_class, info->name, SBOOL(result)); return result; } #endif /** Return the bus numbers for all video adapter i2c buses, filtering out * those, such as ones with SMBUS in their name, that are definitely not * used for DDC/CI communication with a monitor. * * The numbers are determined by examining /sys/bus/i2c. * * This function looks only in /sys. It does not verify that the * corresponding /dev/i2c-N devices exist. */ Bit_Set_256 get_possible_ddc_ci_bus_numbers_using_sysfs_i2c_info() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); Bit_Set_256 result = EMPTY_BIT_SET_256; GPtrArray * allinfo = get_all_sysfs_i2c_info(true, -1); for (int ndx = 0; ndx < allinfo->len; ndx++) { Sysfs_I2C_Info* cur = g_ptr_array_index(allinfo, ndx); if (!sysfs_is_ignorable_i2c_device(cur->busno)) // if (is_potential_i2c_display(cur)) result = bs256_insert(result, cur->busno); } // result = bs256_insert(result, 33); // for testing DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", bs256_to_string_t(result, "0x", ", ")); return result; } void init_i2c_sysfs_i2c_info() { // Sysfs_I2C_Info RTTI_ADD_FUNC(get_i2c_driver_info); RTTI_ADD_FUNC(best_driver_name_for_n_nnnn); RTTI_ADD_FUNC(simple_one_n_nnnn); RTTI_ADD_FUNC(get_i2c_info); RTTI_ADD_FUNC(get_single_i2c_info); RTTI_ADD_FUNC(get_all_sysfs_i2c_info); RTTI_ADD_FUNC(get_possible_ddc_ci_bus_numbers_using_sysfs_i2c_info); } /** Module termination. Release resources. */ void terminate_i2c_sysfs_i2c_info() { if (all_i2c_info) g_ptr_array_free(all_i2c_info, true); } ddcutil-2.2.0/src/sysfs/sysfs_i2c_sys_info.c0000644000175000001440000004121214754153540014547 /** @file sysfs_sys_info.c */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "util/data_structures.h" #include "util/debug_util.h" #ifdef USE_LIBDRM #include "util/drm_common.h" #endif #include "util/edid.h" #include "util/file_util.h" #include "util/glib_string_util.h" #include "util/i2c_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/subprocess_util.h" #include "util/sysfs_filter_functions.h" #include "util/sysfs_i2c_util.h" #include "util/sysfs_util.h" #include "util/utilrpt.h" #include "public/ddcutil_types.h" #include "base/core.h" #include "base/i2c_bus_base.h" #include "base/rtti.h" #include "sysfs_base.h" #include "sysfs_i2c_sys_info.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_SYSFS; // // *** I2C_Sys_Info *** // // Detailed exploratory scan of sysfs // Called from query_sysenv_sysfs.c // void free_i2c_sys_info(I2C_Sys_Info * info) { if (info) { free(info->pci_device_path); free(info->drm_connector_path); free(info->connector); free(info->linked_ddc_filename); free(info->device_name); free(info->drm_dp_aux_name); free(info->drm_dp_aux_dev); free(info->i2c_dev_name); free(info->i2c_dev_dev); free(info->driver); free(info->ddc_path); free(info->ddc_name); free(info->ddc_i2c_dev_name); free(info->ddc_i2c_dev_dev); free(info); } } // same whether displayport, non-displayport video, non-video // /sys/bus/i2c/devices/i2c-N // /sys/devices/pci0000:00/0000:00:02.0/0000:01:00.0/drm/card0/card0-DP-1/i2c-N // static void read_i2cN_device_node( const char * device_path, I2C_Sys_Info * info, int depth) { assert(device_path); assert(info); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "device_path=%s", device_path); int d0 = (depth < 0 && IS_DBGTRC(debug, TRACE_GROUP)) ? 2 : depth; assert(device_path); char * i2c_N = g_path_get_basename(device_path); RPT_ATTR_TEXT( d0, &info->device_name, device_path, "name"); RPT_ATTR_TEXT( d0, &info->i2c_dev_dev, device_path, "i2c-dev", i2c_N, "dev"); RPT_ATTR_TEXT( d0, &info->i2c_dev_name, device_path, "i2c-dev", i2c_N, "name"); free(i2c_N); DBGTRC_DONE(debug, TRACE_GROUP, ""); } #ifdef IN_PROGRESS static void read_drm_card_connector_node_common( const char * dirname, const char * connector; // e.g. card0-DP-1 void * accumulator, int depth) { bool debug = false; DBGMSF(debug, "connector_path=%s", connector_path); int d0 = depth; if (debug && d0 < 0) d0 = 2; I2C_Sys_Info * info = accumulator; char connector_path[PATH_MAX]; g_snprintf(connector_path, PATH_MAX, "%s/%s", dirname, connector); char * drm_dp_aux_dir; RPT_ATTR_SINGLE_SUBDIR(d0, &drm_dp_aux_dir, str_starts_with, "drm_dp_aux", connector_path); if (drm_dp_aux_dir) { RPT_ATTR_TEXT(d0, &info->drm_dp_aux_name, connector_path, drm_dp_aux_dir, "name"); RPT_ATTR_TEXT(d0, &info->drm_dp_aux_dev, connector_path, drm_dp_aux_dir, "dev"); } char * ddc_path_fn; RPT_ATTR_REALPATH(d0, &ddc_path_fn, connector_path, "ddc"); if (ddc_path_fn) { info->ddc_path = ddc_path_fn; info->linked_ddc_filename = g_path_get_basename(ddc_path_fn); info->connector = g_path_get_basename(connector_path); // == coonector RPT_ATTR_TEXT(d0, &info->ddc_name, ddc_path_fn, "name"); RPT_ATTR_TEXT(d0, &info->ddc_i2c_dev_name, ddc_path_fn, "i2c-dev", info->linked_ddc_filename, "name"); RPT_ATTR_TEXT(d0, &info->ddc_i2c_dev_dev, ddc_path_fn, "i2c-dev", info->linked_ddc_filename, "dev"); } RPT_ATTR_EDID(d1, NULL, dirname, connector, "edid"); RPT_ATTR_TEXT(d1, NULL, dirname, connector, "enabled"); RPT_ATTR_TEXT(d1, NULL, dirname, connector, "status"); } #endif // Process /drm/cardN/cardN- for case that // cardN- is a DisplayPort connector // static void read_drm_dp_card_connector_node( const char * connector_path, I2C_Sys_Info * info, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "connector_path=%s", connector_path); int d0 = (depth < 0 && IS_DBGTRC(debug, TRACE_GROUP)) ? 2 : depth; assert(connector_path); char * ddc_path_fn; RPT_ATTR_REALPATH(d0, &ddc_path_fn, connector_path, "ddc"); if (ddc_path_fn) { info->ddc_path = ddc_path_fn; info->linked_ddc_filename = g_path_get_basename(ddc_path_fn); info->connector = g_path_get_basename(connector_path); RPT_ATTR_TEXT(d0, &info->ddc_name, ddc_path_fn, "name"); RPT_ATTR_TEXT(d0, &info->ddc_i2c_dev_name, ddc_path_fn, "i2c-dev", info->linked_ddc_filename, "name"); RPT_ATTR_TEXT(d0, &info->ddc_i2c_dev_dev, ddc_path_fn, "i2c-dev", info->linked_ddc_filename, "dev"); } char * drm_dp_aux_dir; RPT_ATTR_SINGLE_SUBDIR(d0, &drm_dp_aux_dir, str_starts_with, "drm_dp_aux", connector_path); if (drm_dp_aux_dir) { RPT_ATTR_TEXT(d0, &info->drm_dp_aux_name, connector_path, drm_dp_aux_dir, "name"); RPT_ATTR_TEXT(d0, &info->drm_dp_aux_dev, connector_path, drm_dp_aux_dir, "dev"); free(drm_dp_aux_dir); } possibly_write_detect_to_status_by_connector_path(connector_path); RPT_ATTR_EDID(d0, NULL, connector_path, "edid"); RPT_ATTR_TEXT(d0, NULL, connector_path, "enabled"); RPT_ATTR_TEXT(d0, NULL, connector_path, "status"); DBGTRC_DONE(debug, TRACE_GROUP, ""); } // Process a /drm/cardN/cardN- for case when // cardN- is not a DisplayPort connector // static void read_drm_nondp_card_connector_node( const char * dirname, // e.g /sys/devices/pci.../card0 const char * connector, // e.g card0-DP-1 void * accumulator, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, connector=%s", dirname, connector); int d1 = (depth < 0) ? -1 : depth + 1; if (debug && d1 < 0) d1 = 2; I2C_Sys_Info * info = accumulator; if (info->connector) { // already handled by read_drm_dp_card_connector_node() DBGTRC_DONE(debug, TRACE_GROUP, "Connector already found, skipping"); return; } bool is_dp = RPT_ATTR_SINGLE_SUBDIR(depth, NULL, str_starts_with, "drm_dp_aux", dirname, connector); if (is_dp) { DBGTRC_DONE(debug, TRACE_GROUP, "Is display port connector, skipping"); return; } char i2cN[20]; g_snprintf(i2cN, 20, "i2c-%d", info->busno); bool found_i2c = RPT_ATTR_SINGLE_SUBDIR(depth, NULL, streq, i2cN, dirname, connector, "ddc/i2c-dev"); if (found_i2c) { info->connector = g_strdup(connector); possibly_write_detect_to_status_by_connector_name(connector); RPT_ATTR_TEXT(d1, NULL, dirname, connector, "ddc", "name"); RPT_ATTR_TEXT(d1, NULL, dirname, connector, "ddc/i2c-dev", i2cN, "dev"); RPT_ATTR_TEXT(d1, NULL, dirname, connector, "ddc/i2c-dev", i2cN, "name"); RPT_ATTR_EDID(d1, NULL, dirname, connector, "edid"); RPT_ATTR_TEXT(d1, NULL, dirname, connector, "enabled"); RPT_ATTR_TEXT(d1, NULL, dirname, connector, "status"); } DBGTRC_DONE(debug, TRACE_GROUP, ""); return; } // Dir_Foreach_Func // Process a /drm/cardN node // static void one_drm_card( const char * dirname, // e.g /sys/devices/pci const char * fn, // card0, card1 ... void * info, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dirname=%s, fn=%s", dirname, fn); char buf[PATH_MAX]; g_snprintf(buf, PATH_MAX, "%s/%s", dirname, fn); dir_ordered_foreach( buf, predicate_cardN_connector, gaux_ptr_scomp, read_drm_nondp_card_connector_node, info, depth); DBGTRC_DONE(debug, TRACE_GROUP, ""); } static void read_controller_driver( const char * controller_path, I2C_Sys_Info * info, int depth) { char * driver_path = NULL; RPT_ATTR_REALPATH(depth, &driver_path, controller_path, "driver"); if (driver_path) { info->driver = g_path_get_basename(driver_path); free(driver_path); } } // called only if not DisplayPort // static void read_pci_display_controller_node( const char * nodepath, int busno, I2C_Sys_Info * info, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d, nodepath=%s", busno, nodepath); int d0 = depth; // for this function if (debug && d0 < 0) d0 = 2; int depth1 = (depth < 0) ? -1 : depth + 1; // for called functions char * class; RPT_ATTR_TEXT(d0, &class, nodepath, "class"); if (class && str_starts_with(class, "0x03")) { // this is indeed a display controller node RPT_ATTR_TEXT(d0, NULL, nodepath, "boot_vga"); RPT_ATTR_TEXT(d0, NULL, nodepath, "vendor"); RPT_ATTR_TEXT(d0, NULL, nodepath, "device"); // RPT_ATTR_TEXT(d0, NULL, nodepath, "fw_version"); #ifdef OLD char * driver_path = NULL; RPT_ATTR_REALPATH(d0, &driver_path, nodepath, "driver"); if (driver_path && info->connector) // why the info->connector test? info->driver = g_path_get_basename(driver_path); free(driver_path); #endif read_controller_driver(nodepath, info, depth); // examine all drm/cardN subnodes char buf[PATH_MAX]; g_snprintf(buf, PATH_MAX, "%s/%s", nodepath, "drm"); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Calling dir_ordered_foreach, buf=%s, predicate predicate_cardN_connector()", buf); dir_ordered_foreach(buf, predicate_cardN_connector, i2c_compare, one_drm_card, info, depth1); } free(class); DBGTRC_DONE(debug, TRACE_GROUP, ""); } I2C_Sys_Info * get_i2c_sys_info( int busno, int depth) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busno=%d. depth=%d", busno, depth); I2C_Sys_Info * result = NULL; int d1 = (depth < 0) ? -1 : depth+1; char i2c_N[20]; g_snprintf(i2c_N, 20, "i2c-%d", busno); // Example: char i2c_device_path[50]; // /sys/bus/i2c/devices/i2c-13 char * pci_i2c_device_path = NULL; // /sys/devices/../card0/card0-DP-1/i2c-13 char * pci_i2c_device_parent = NULL; // /sys/devices/.../card0/card0-DP-1 // char * connector_path = NULL; // .../card0/card0-DP-1 // char * drm_dp_aux_dir = NULL; // .../card0/card0-DP-1/drm_dp_aux0 // char * ddc_path_fn = NULL; // .../card0/card0-DP-1/ddc g_snprintf(i2c_device_path, 50, "/sys/bus/i2c/devices/i2c-%d", busno); if (directory_exists(i2c_device_path)) { result = calloc(1, sizeof(I2C_Sys_Info)); result->busno = busno; // real path is in /sys/devices tree RPT_ATTR_REALPATH(d1, &pci_i2c_device_path, i2c_device_path); result->pci_device_path = pci_i2c_device_path; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "pci_i2c_device_path=%s", pci_i2c_device_path); read_i2cN_device_node(pci_i2c_device_path, result, d1); RPT_ATTR_REALPATH(d1, &pci_i2c_device_parent, pci_i2c_device_path, ".."); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "pci_i2c_device_parent=%s", pci_i2c_device_parent); bool has_drm_dp_aux_dir = RPT_ATTR_SINGLE_SUBDIR(d1, NULL, str_starts_with, "drm_dp_aux", pci_i2c_device_parent); // RPT_ATTR_SINGLE_SUBDIR(d1, &drm_dp_aux_dir, str_starts_with, "drm_dp_aux", pci_i2c_device_parent); // if (drm_dp_aux_dir) { if (has_drm_dp_aux_dir) { // pci_i2c_device_parent is a drm connector node result->is_amdgpu_display_port = true; read_drm_dp_card_connector_node(pci_i2c_device_parent, result, d1); char controller_path[PATH_MAX]; g_snprintf(controller_path, PATH_MAX, "%s/../../..", pci_i2c_device_parent); read_controller_driver(controller_path, result, d1); #ifdef OLD char * driver_path = NULL; // look in controller node: RPT_ATTR_REALPATH(d1, &driver_path, pci_i2c_device_parent, "../../..", "driver"); result->driver = g_path_get_basename(driver_path); free(driver_path); #endif // free(drm_dp_aux_dir); } else { // pci_i2c_device_parent is a display controller node read_pci_display_controller_node(pci_i2c_device_parent, busno, result, d1); #ifdef OLD char * driver_path = NULL; RPT_ATTR_REALPATH(d1, &driver_path, pci_i2c_device_parent, "driver"); result->driver = g_path_get_basename(driver_path); free(driver_path); #endif } free(pci_i2c_device_parent); } // ASSERT_IFF(drm_dp_aux_dir, ddc_path_fn); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", result); return result; } /** Emit debug type report of a #I2C_Sys_Info struct * * @param info pointer to struct with relevant /sys information * @param depth logical indentation depth, if < 0 perform no indentation */ // used in i2c_bus_base.c, use eliminated 9/26/2024 void dbgrpt_i2c_sys_info(I2C_Sys_Info * info, int depth) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "info=%p, depth=%d", info, depth); int d1 = (depth < 0) ? 0 : depth + 1; int d2 = (depth < 0) ? 0 : depth + 2; if (depth < 0) depth = 0; if (info) { rpt_vstring(depth, "Extended information for /sys/bus/i2c/devices/i2c-%d...", info->busno); char * busno_pad = (info->busno < 10) ? " " : ""; rpt_vstring(d1, "PCI device path: %s", info->pci_device_path); rpt_vstring(d1, "name: %s", info->device_name); rpt_vstring(d1, "i2c-dev/i2c-%d/dev: %s %s", info->busno, busno_pad, info->i2c_dev_dev); rpt_vstring(d1, "i2c-dev/i2c-%d/name:%s %s", info->busno, busno_pad, info->i2c_dev_name); rpt_vstring(d1, "Connector: %s", info->connector); rpt_vstring(d1, "Driver: %s", info->driver); if (info->is_amdgpu_display_port) { rpt_vstring(d1, "DisplayPort only attributes:"); rpt_vstring(d2, "ddc path: %s", info->ddc_path); // rpt_vstring(d2, "Linked ddc filename: %s", dp_info->linked_ddc_filename); rpt_vstring(d2, "ddc name: %s", info->ddc_name); rpt_vstring(d2, "ddc i2c-dev/%s/dev: %s %s", info->linked_ddc_filename, busno_pad, info->ddc_i2c_dev_dev); rpt_vstring(d2, "ddc i2c-dev/%s/name: %s %s", info->linked_ddc_filename, busno_pad, info->ddc_i2c_dev_name); rpt_vstring(d2, "DP Aux channel dev: %s", info->drm_dp_aux_dev); rpt_vstring(d2, "DP Aux channel name: %s", info->drm_dp_aux_name); } // else { // rpt_vstring(d1, "Not a DisplayPort connection"); // } } DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } static void report_one_bus_i2c( const char * dirname, // const char * fn, // i2c-1, i2c-2, etc., possibly 1-0037, 1-0023, 1-0050 etc void * data, int depth) { bool debug = false; DBGMSF(debug, "dirname=%s, fn=%s", dirname, fn); rpt_nl(); int busno = i2c_name_to_busno(fn); // catches non-i2cN names if (busno < 0) { rpt_vstring(depth, "Ignoring %s/%s", dirname, fn); } else { rpt_vstring(depth, "Examining /sys/bus/i2c/devices/i2c-%d...", busno); int d1 = depth+1; // reports as it collects, no need to call report_i2c_sys_info() I2C_Sys_Info * info = get_i2c_sys_info(busno, d1); // report_i2c_sys_info(info, depth+1); free_i2c_sys_info(info); } } // used in query_sysenv_sysfs.c void dbgrpt_sys_bus_i2c(int depth) { bool debug = FALSE; DBGTRC_STARTING(debug, DDCA_TRC_NONE, ""); rpt_label(depth, "Examining /sys/bus/i2c/devices:"); dir_ordered_foreach("/sys/bus/i2c/devices", NULL, i2c_compare, report_one_bus_i2c, NULL, depth); DBGTRC_DONE(debug, DDCA_TRC_NONE, ""); } void init_i2c_sysfs_i2c_sys_info() { // I2C_Sys_Info RTTI_ADD_FUNC(read_i2cN_device_node); RTTI_ADD_FUNC(read_drm_dp_card_connector_node); RTTI_ADD_FUNC(read_drm_nondp_card_connector_node); RTTI_ADD_FUNC(one_drm_card); RTTI_ADD_FUNC(read_pci_display_controller_node); RTTI_ADD_FUNC(get_i2c_sys_info); RTTI_ADD_FUNC(dbgrpt_i2c_sys_info); RTTI_ADD_FUNC(dbgrpt_sys_bus_i2c); } // *** End of I2C_Sys_Info ddcutil-2.2.0/src/sysfs/sysfs_top.c0000644000175000001440000000336514754153540012772 /** @file sysfs_top.c */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include "util/data_structures.h" #include "util/report_util.h" #include "sysfs_conflicting_drivers.h" #include "sysfs_i2c_info.h" #include "sysfs_sys_drm_connector.h" #include "sysfs_top.h" void consolidated_i2c_sysfs_report(int depth) { int d0 = depth; int d1 = depth+1; rpt_label(d0, "*** Sys_Drm_Connector report: Detailed /sys/class/drm report: ***"); report_sys_drm_connectors(true, d1); rpt_nl(); // not currently used, and leaks memory // rpt_label(d0, "*** Sys_Drm_Connector_FixedInfo report: Simplified /sys/class/drm report: ***"); // report_sys_drm_connectors_fixedinfo(d1); // rpt_nl(); rpt_label(d0, "*** Sysfs_I2C_Info report ***"); GPtrArray * reports = get_all_sysfs_i2c_info(true, -1); dbgrpt_all_sysfs_i2c_info(reports, d1); rpt_nl(); rpt_label(d0, "*** Sysfs I2C devices possibly associated with displays ***"); Bit_Set_256 buses = get_possible_ddc_ci_bus_numbers_using_sysfs_i2c_info(); rpt_vstring(d0, "I2C buses to check: %s", bs256_to_string_t(buses, "x", " ")); rpt_nl(); rpt_label(d0, "*** Sys_Conflicting_Driver report: Check for Conflicting Device Drivers ***"); GPtrArray * conflicts = collect_conflicting_drivers_for_any_bus(-1); if (conflicts && conflicts->len > 0) { report_conflicting_drivers(conflicts, d1); rpt_vstring(d1, "Likely conflicting drivers found: %s\n", conflicting_driver_names_string_t(conflicts)); } else rpt_label(d1, "No conflicting drivers found"); free_conflicting_drivers(conflicts); rpt_nl(); rpt_label(0, "*** Sysfs Reports Done ***"); rpt_nl(); } ddcutil-2.2.0/src/sysfs/sysfs_services.c0000644000175000001440000000131414754153540014003 /** @file sysfs_services.c */ // Copyright (C) 2022-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "sysfs/sysfs_base.h" #include "sysfs/sysfs_conflicting_drivers.h" #include "sysfs/sysfs_dpms.h" #include "sysfs/sysfs_i2c_info.h" #include "sysfs/sysfs_i2c_sys_info.h" #include "sysfs/sysfs_sys_drm_connector.h" #include "sysfs_services.h" /** Master initializer for directory i2c */ void init_sysfs_services() { init_i2c_dpms(); init_i2c_sysfs_base(); init_i2c_sysfs(); init_i2c_sysfs_conflicting_drivers(); init_i2c_sysfs_i2c_sys_info(); init_i2c_sysfs_i2c_info(); } void terminate_sysfs_services() { terminate_i2c_sysfs_i2c_info(); } ddcutil-2.2.0/src/sysfs/sysfs_base.h0000644000175000001440000001000714754576332013106 /** @file sysfs_base.h */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_BASE_H_ #define SYSFS_BASE_H_ #include #include #include #include "base/displays.h" #include "base/i2c_bus_base.h" extern bool force_sysfs_unreliable; extern bool force_sysfs_reliable; extern bool enable_write_detect_to_status; // predicate functions // typedef Dir_Filter_Func bool is_n_nnnn(const char * dirname, const char * simple_fn); GPtrArray * get_sys_video_devices(); void dbgrpt_sysfs_basic_connector_attributes(int depth); char * get_sys_drm_connector_name_by_connector_id(int connector_id); char * get_sys_drm_connector_name_by_busno(int busno); bool all_sys_drm_connectors_have_connector_id_direct(); char * get_driver_for_adapter(char * adapter_path, int depth); // char * find_adapter(char * path, int depth); // MOVED char * find_adapter_and_get_driver(char * path, int depth); char * get_driver_for_busno(int busno); void possibly_write_detect_to_status(const char * driver, const char * connector); void possibly_write_detect_to_status_by_connector_name(const char * connector); void possibly_write_detect_to_status_by_businfo(I2C_Bus_Info * businfo); void possibly_write_detect_to_status_by_dref(Display_Ref * dref); void possibly_write_detect_to_status_by_connector_path(const char * path); typedef struct { int i2c_busno; int base_busno; int connector_id; char * name; } Connector_Bus_Numbers; void dbgrpt_connector_bus_numbers(Connector_Bus_Numbers * cbn, int depth); void free_connector_bus_numbers(Connector_Bus_Numbers * cbn); void get_connector_bus_numbers( const char * dirname, // /drm/cardN const char * fn, // card0-HDMI-1 etc Connector_Bus_Numbers * cbn); typedef struct { GPtrArray * all_connectors; GPtrArray * connectors_having_edid; } Sysfs_Connector_Names; Sysfs_Connector_Names get_sysfs_drm_connector_names(); bool sysfs_connector_names_equal(Sysfs_Connector_Names cn1, Sysfs_Connector_Names cn2); void free_sysfs_connector_names_contents(Sysfs_Connector_Names names_struct); void dbgrpt_sysfs_connector_names(Sysfs_Connector_Names connector_names, int depth); Sysfs_Connector_Names copy_sysfs_connector_names_struct(Sysfs_Connector_Names original); char * find_sysfs_drm_connector_name_by_edid(GPtrArray* connector_names, Byte * edid); bool is_sysfs_reliable_for_driver(const char * driver); bool is_sysfs_reliable_for_busno(int busno); bool is_sysfs_reliable(); // moved from sysfs_i2c_util.h: char * sysfs_find_adapter(char * path); char * get_i2c_sysfs_driver_by_busno( int busno); char * get_i2c_sysfs_driver_by_device_name( char * device_name); char * get_i2c_sysfs_driver_by_fd( int fd); uint32_t get_i2c_device_sysfs_class( int busno); char * get_i2c_device_sysfs_name( int busno); bool sysfs_is_ignorable_i2c_device( int busno); // moved from dw_udev.h: int search_all_businfo_records_by_connector_name(char *connector_name); void init_i2c_sysfs_base(); #ifdef FOR_FUTURE_USE typedef struct { char * connector; int busno; Display_Ref * dref; // currently } Connector_Busno_Dref; extern GPtrArray * cbd_table; typedef GPtrArray Connector_Busno_Dref_Table; Connector_Busno_Dref_Table * create_connector_busnfo_dref_table(); Connector_Busno_Dref * new_cbd0(int busno); Connector_Busno_Dref * new_cbd(const char * connector, int busno); Connector_Busno_Dref * get_cbd_by_connector(const char * connector); Connector_Busno_Dref * get_cbd_by_busno(int busno); // if dref != NULL, replaces, if NULL, just erases void set_cbd_connector(Connector_Busno_Dref * cbd, Display_Ref * dref); void dbgrpt_cbd_table(Connector_Busno_Dref_Table * cbd_table, int depth); #endif #endif /* SYSFS_BASE_H_ */ ddcutil-2.2.0/src/sysfs/sysfs_conflicting_drivers.h0000644000175000001440000000211714754576332016234 /** @file sysfs_conflicting_drivers.h */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_CONFLICTING_DRIVERS_H_ #define SYSFS_CONFLICTING_DRIVERS_H_ #include #include "util/coredefs.h" typedef struct { int i2c_busno; char * n_nnnn; char * name; // n_nnnn/name char * driver_module; // basename(realpath(n_nnnn/driver/module)) char * modalias; // n_nnnn/modalias Byte * eeprom_edid_bytes; gsize eeprom_edid_size; } Sys_Conflicting_Driver; GPtrArray * collect_conflicting_drivers(int busno, int depth); GPtrArray * collect_conflicting_drivers_for_any_bus(int depth); void report_conflicting_drivers(GPtrArray * conflicts, int depth); // for a single busno void free_conflicting_drivers(GPtrArray* conflicts); GPtrArray * conflicting_driver_names(GPtrArray * conflicts); char * conflicting_driver_names_string_t(GPtrArray * conflicts); void init_i2c_sysfs_conflicting_drivers(); #endif /* SYSFS_CONFLICTING_DRIVERS_H_ */ ddcutil-2.2.0/src/sysfs/sysfs_dpms.h0000644000175000001440000000166314754576332013147 /** @file sysfs_dpms.h * DPMS related functions */ // Copyright (C) 2023-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_DPMS_H_ #define SYSFS_DPMS_H_ #include #include "config.h" #include "base/displays.h" #include "base/i2c_bus_base.h" // DPMS Detection #ifdef USE_X11 #define DPMS_STATE_X11_CHECKED 0x01 #define DPMS_STATE_X11_ASLEEP 0x02 #endif #define DPMS_SOME_DRM_ASLEEP 0x04 #define DPMS_ALL_DRM_ASLEEP 0x08 typedef Byte Dpms_State; extern Dpms_State dpms_state; char * interpret_dpms_state_t(Dpms_State state); bool dpms_is_x11_asleep(); bool dpms_check_drm_asleep_by_connector(const char * drm_connector_name); bool dpms_check_drm_asleep_by_businfo(I2C_Bus_Info * businfo); bool dpms_check_drm_asleep_by_dref(Display_Ref * dref); void init_i2c_dpms(); #endif /* SYSFS_DPMS_H_ */ ddcutil-2.2.0/src/sysfs/sysfs_i2c_info.h0000644000175000001440000000215614754576332013672 /** @file sysfs_i2c_info.h */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_I2C_INFO_H_ #define SYSFS_I2C_INFO_H_ #include #include "util/data_structures.h" typedef struct { int busno; char * name; char * adapter_path; char * adapter_class; char * driver; char * driver_version; GPtrArray * conflicting_driver_names; } Sysfs_I2C_Info; void free_sysfs_i2c_info(Sysfs_I2C_Info * info); Sysfs_I2C_Info * get_i2c_driver_info(int busno, int depth); Sysfs_I2C_Info * get_basic_i2c_driver_info(int busno); GPtrArray * get_all_sysfs_i2c_info(bool rescan, int depth); void dbgrpt_sysfs_i2c_info(Sysfs_I2C_Info * info, int depth); void dbgrpt_all_sysfs_i2c_info(GPtrArray * infos, int depth); #ifdef UNUSED char * get_conflicting_drivers_for_bus(int busno); #endif Bit_Set_256 get_possible_ddc_ci_bus_numbers_using_sysfs_i2c_info(); void init_i2c_sysfs_i2c_info(); void terminate_i2c_sysfs_i2c_info(); #endif /* SYSFS_I2C_INFO_H_ */ ddcutil-2.2.0/src/sysfs/sysfs_i2c_sys_info.h0000644000175000001440000000266414754576332014574 /** @file sysfs_sys_info.h */ // Copyright (C) 2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_SYS_INFO_H_ #define SYSFS_SYS_INFO_H_ #include "util/data_structures.h" typedef struct { int busno; bool is_amdgpu_display_port; char * pci_device_path; char * drm_connector_path; char * connector; char * ddc_path; char * linked_ddc_filename; char * device_name; char * drm_dp_aux_name; char * drm_dp_aux_dev; char * i2c_dev_name; char * i2c_dev_dev; char * driver; char * ddc_name; char * ddc_i2c_dev_name; char * ddc_i2c_dev_dev; } I2C_Sys_Info; #ifdef FUTURE // In progress: Simplified I2C_Sys_Info for production as opposed to exploratory use typedef struct { char * pci_device_path; char * driver; char * connector; char * drm_connector_path; char * device_name; int busno; } I2C_Fixed_Sys_Info; #endif // WAS used in i2c_dbgrpt_bus_info() in i2c_bus_base.c: ELIMINATED // get_i2c_sys_info(), free_i2c_sys_info(), dbgrpt_i2c_sys_info() // used in query_sysenv_sysfs.c: dbgrpt_sys_bus_i2c I2C_Sys_Info * get_i2c_sys_info(int busno, int depth); void free_i2c_sys_info(I2C_Sys_Info * info); void dbgrpt_i2c_sys_info(I2C_Sys_Info * info, int depth); void dbgrpt_sys_bus_i2c(int depth); void init_i2c_sysfs_i2c_sys_info(); #endif /* I2C_SYSFS_I2C_SYS_INFO_H_ */ ddcutil-2.2.0/src/sysfs/sysfs_services.h0000644000175000001440000000044414754576332014023 /* @file sysfs_services.h */ // Copyright (C) 2022-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_SERVICES_H_ #define SYSFS_SERVICES_H_ void init_sysfs_services(); void terminate_sysfs_services(); #endif /* SYSFS_SERVICES_H_ */ ddcutil-2.2.0/src/sysfs/sysfs_sys_drm_connector.h0000644000175000001440000000471014754576332015732 /** @file sysfs_sys_drm_connector.h * * Query /sys file system for information on I2C devices */ // Copyright (C) 2020-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_SYS_DRM_CONNECTOR_H_ #define SYSFS_SYS_DRM_CONNECTOR_H_ #include #include #include "util/coredefs_base.h" #include "util/data_structures.h" #include "util/drm_common.h" #include "base/i2c_bus_base.h" extern GPtrArray * sys_drm_connectors; extern bool all_drm_connectors_have_connector_id; typedef struct { char * connector_name; char * connector_path; int i2c_busno; int connector_id; char * name; char * ddc_dir_path; bool is_aux_channel; int base_busno; char * base_name; char * base_dev; Byte * edid_bytes; gsize edid_size; char * enabled; char * status; } Sys_Drm_Connector; // Functions that use the persistent array of Sys_Drm_Connector: GPtrArray* get_sys_drm_connectors(bool rescan); void report_sys_drm_connectors(bool verbose, int depth); Sys_Drm_Connector * find_sys_drm_connector(int busno, Byte * raw_edid, const char * connector_name); Sys_Drm_Connector * find_sys_drm_connector_by_connector_id(int connector_number); Sys_Drm_Connector * find_sys_drm_connector_by_connector_identifier(Drm_Connector_Identifier dci); void free_sys_drm_connector(void * conninfo); Sys_Drm_Connector * find_sys_drm_connector_by_edid(Byte * raw_edid); void free_sys_drm_connectors(); Sys_Drm_Connector * i2c_check_businfo_connector(I2C_Bus_Info * bus_info); int sys_drm_get_busno_by_connector_name(const char * connector_name); bool all_sys_drm_connectors_have_connector_id(bool rescan); Bit_Set_256 buses_having_edid_from_sys_drm_connectors(bool rescan); char * find_drm_connector_name_by_busno(int busno); char * get_drm_connector_name_by_edid(Byte * edid_bytes); Sys_Drm_Connector * find_sys_drm_connector_by_connector_name(const char * name); Sys_Drm_Connector * find_sys_drm_connector_by_busno(int busno); // Functions that access sysfs connector dirs directly, instead of using the // persistent array of Sys_Drm_Connector: Sys_Drm_Connector * one_drm_connector0(const char * dirname, const char * fn, int depth); Sys_Drm_Connector * get_drm_connector(const char * fn, int depth); // Initialization void init_i2c_sysfs(); #endif /* SYSFS_SYS_DRM_CONNECTOR_H_ */ ddcutil-2.2.0/src/sysfs/sysfs_top.h0000644000175000001440000000040214754576332012774 /** @file sysfs_top.h */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_TOP_H_ #define SYSFS_TOP_H_ void consolidated_i2c_sysfs_report(int depth); #endif /* SYSFS_TOP_H_ */ ddcutil-2.2.0/src/sample_clients/0000775000175000001440000000000014754576332012513 5ddcutil-2.2.0/src/sample_clients/Makefile.am0000644000175000001440000000267314441414365014463 # File src/sample_clients/Makefile.am # Makefile for sample and test programs for libddcutil AM_CPPFLAGS= \ -I$(srcdir) \ -I$(top_srcdir)/src/public \ -I$(top_srcdir)/src AM_CFLAGS = -Wall -fPIC # AM_CFLAGS += -Werror check_PROGRAMS = if ENABLE_SHARED_LIB_COND # Sample C client program for shared library: check_PROGRAMS += \ laclient \ demo_capabilities \ demo_display_selection \ demo_feature_list \ demo_get_set_vcp \ demo_global_settings \ demo_profile_features \ demo_redirection \ demo_vcpinfo endif laclient_SOURCES = clmain.c demo_capabilities_SOURCES = demo_capabilities.c demo_display_selection_SOURCES = demo_display_selection.c demo_feature_list_SOURCES = demo_feature_list.c demo_get_set_vcp_SOURCES = demo_get_set_vcp.c demo_global_settings_SOURCES = demo_global_settings.c demo_profile_features_SOURCES = demo_profile_features.c demo_redirection_SOURCES = demo_redirection.c demo_vcpinfo_SOURCES = demo_vcpinfo.c LDADD = ../libddcutil.la AM_LDFLAGS = -pie clean-local: @echo "(src/sample_clients/Makefile) clean-local" mostlyclean-local: @echo "(src/sample_clients/Makefile) mostlyclean-local" distclean-local: @echo "(src/sample_clients/Makefile) distclean-local" # Make this a dependency of something to enable it: show_vars: @echo "src/sample_clients/Makefile" @echo "srcdir: ${srcdir}" @echo "top_srcdir: ${top_srcdir}" .PHONY: show_vars ddcutil-2.2.0/src/sample_clients/Makefile.in0000664000175000001440000006677114754576155014524 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # File src/sample_clients/Makefile.am # Makefile for sample and test programs for libddcutil VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = $(am__EXEEXT_1) # Sample C client program for shared library: @ENABLE_SHARED_LIB_COND_TRUE@am__append_1 = \ @ENABLE_SHARED_LIB_COND_TRUE@ laclient \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_capabilities \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_display_selection \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_feature_list \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_get_set_vcp \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_global_settings \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_profile_features \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_redirection \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_vcpinfo subdir = src/sample_clients ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @ENABLE_SHARED_LIB_COND_TRUE@am__EXEEXT_1 = laclient$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_capabilities$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_display_selection$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_feature_list$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_get_set_vcp$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_global_settings$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_profile_features$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_redirection$(EXEEXT) \ @ENABLE_SHARED_LIB_COND_TRUE@ demo_vcpinfo$(EXEEXT) am_demo_capabilities_OBJECTS = demo_capabilities.$(OBJEXT) demo_capabilities_OBJECTS = $(am_demo_capabilities_OBJECTS) demo_capabilities_LDADD = $(LDADD) demo_capabilities_DEPENDENCIES = ../libddcutil.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_demo_display_selection_OBJECTS = demo_display_selection.$(OBJEXT) demo_display_selection_OBJECTS = $(am_demo_display_selection_OBJECTS) demo_display_selection_LDADD = $(LDADD) demo_display_selection_DEPENDENCIES = ../libddcutil.la am_demo_feature_list_OBJECTS = demo_feature_list.$(OBJEXT) demo_feature_list_OBJECTS = $(am_demo_feature_list_OBJECTS) demo_feature_list_LDADD = $(LDADD) demo_feature_list_DEPENDENCIES = ../libddcutil.la am_demo_get_set_vcp_OBJECTS = demo_get_set_vcp.$(OBJEXT) demo_get_set_vcp_OBJECTS = $(am_demo_get_set_vcp_OBJECTS) demo_get_set_vcp_LDADD = $(LDADD) demo_get_set_vcp_DEPENDENCIES = ../libddcutil.la am_demo_global_settings_OBJECTS = demo_global_settings.$(OBJEXT) demo_global_settings_OBJECTS = $(am_demo_global_settings_OBJECTS) demo_global_settings_LDADD = $(LDADD) demo_global_settings_DEPENDENCIES = ../libddcutil.la am_demo_profile_features_OBJECTS = demo_profile_features.$(OBJEXT) demo_profile_features_OBJECTS = $(am_demo_profile_features_OBJECTS) demo_profile_features_LDADD = $(LDADD) demo_profile_features_DEPENDENCIES = ../libddcutil.la am_demo_redirection_OBJECTS = demo_redirection.$(OBJEXT) demo_redirection_OBJECTS = $(am_demo_redirection_OBJECTS) demo_redirection_LDADD = $(LDADD) demo_redirection_DEPENDENCIES = ../libddcutil.la am_demo_vcpinfo_OBJECTS = demo_vcpinfo.$(OBJEXT) demo_vcpinfo_OBJECTS = $(am_demo_vcpinfo_OBJECTS) demo_vcpinfo_LDADD = $(LDADD) demo_vcpinfo_DEPENDENCIES = ../libddcutil.la am_laclient_OBJECTS = clmain.$(OBJEXT) laclient_OBJECTS = $(am_laclient_OBJECTS) laclient_LDADD = $(LDADD) laclient_DEPENDENCIES = ../libddcutil.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/clmain.Po \ ./$(DEPDIR)/demo_capabilities.Po \ ./$(DEPDIR)/demo_display_selection.Po \ ./$(DEPDIR)/demo_feature_list.Po \ ./$(DEPDIR)/demo_get_set_vcp.Po \ ./$(DEPDIR)/demo_global_settings.Po \ ./$(DEPDIR)/demo_profile_features.Po \ ./$(DEPDIR)/demo_redirection.Po ./$(DEPDIR)/demo_vcpinfo.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(demo_capabilities_SOURCES) \ $(demo_display_selection_SOURCES) $(demo_feature_list_SOURCES) \ $(demo_get_set_vcp_SOURCES) $(demo_global_settings_SOURCES) \ $(demo_profile_features_SOURCES) $(demo_redirection_SOURCES) \ $(demo_vcpinfo_SOURCES) $(laclient_SOURCES) DIST_SOURCES = $(demo_capabilities_SOURCES) \ $(demo_display_selection_SOURCES) $(demo_feature_list_SOURCES) \ $(demo_get_set_vcp_SOURCES) $(demo_global_settings_SOURCES) \ $(demo_profile_features_SOURCES) $(demo_redirection_SOURCES) \ $(demo_vcpinfo_SOURCES) $(laclient_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ -I$(srcdir) \ -I$(top_srcdir)/src/public \ -I$(top_srcdir)/src AM_CFLAGS = -Wall -fPIC laclient_SOURCES = clmain.c demo_capabilities_SOURCES = demo_capabilities.c demo_display_selection_SOURCES = demo_display_selection.c demo_feature_list_SOURCES = demo_feature_list.c demo_get_set_vcp_SOURCES = demo_get_set_vcp.c demo_global_settings_SOURCES = demo_global_settings.c demo_profile_features_SOURCES = demo_profile_features.c demo_redirection_SOURCES = demo_redirection.c demo_vcpinfo_SOURCES = demo_vcpinfo.c LDADD = ../libddcutil.la AM_LDFLAGS = -pie all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/sample_clients/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/sample_clients/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list demo_capabilities$(EXEEXT): $(demo_capabilities_OBJECTS) $(demo_capabilities_DEPENDENCIES) $(EXTRA_demo_capabilities_DEPENDENCIES) @rm -f demo_capabilities$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_capabilities_OBJECTS) $(demo_capabilities_LDADD) $(LIBS) demo_display_selection$(EXEEXT): $(demo_display_selection_OBJECTS) $(demo_display_selection_DEPENDENCIES) $(EXTRA_demo_display_selection_DEPENDENCIES) @rm -f demo_display_selection$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_display_selection_OBJECTS) $(demo_display_selection_LDADD) $(LIBS) demo_feature_list$(EXEEXT): $(demo_feature_list_OBJECTS) $(demo_feature_list_DEPENDENCIES) $(EXTRA_demo_feature_list_DEPENDENCIES) @rm -f demo_feature_list$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_feature_list_OBJECTS) $(demo_feature_list_LDADD) $(LIBS) demo_get_set_vcp$(EXEEXT): $(demo_get_set_vcp_OBJECTS) $(demo_get_set_vcp_DEPENDENCIES) $(EXTRA_demo_get_set_vcp_DEPENDENCIES) @rm -f demo_get_set_vcp$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_get_set_vcp_OBJECTS) $(demo_get_set_vcp_LDADD) $(LIBS) demo_global_settings$(EXEEXT): $(demo_global_settings_OBJECTS) $(demo_global_settings_DEPENDENCIES) $(EXTRA_demo_global_settings_DEPENDENCIES) @rm -f demo_global_settings$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_global_settings_OBJECTS) $(demo_global_settings_LDADD) $(LIBS) demo_profile_features$(EXEEXT): $(demo_profile_features_OBJECTS) $(demo_profile_features_DEPENDENCIES) $(EXTRA_demo_profile_features_DEPENDENCIES) @rm -f demo_profile_features$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_profile_features_OBJECTS) $(demo_profile_features_LDADD) $(LIBS) demo_redirection$(EXEEXT): $(demo_redirection_OBJECTS) $(demo_redirection_DEPENDENCIES) $(EXTRA_demo_redirection_DEPENDENCIES) @rm -f demo_redirection$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_redirection_OBJECTS) $(demo_redirection_LDADD) $(LIBS) demo_vcpinfo$(EXEEXT): $(demo_vcpinfo_OBJECTS) $(demo_vcpinfo_DEPENDENCIES) $(EXTRA_demo_vcpinfo_DEPENDENCIES) @rm -f demo_vcpinfo$(EXEEXT) $(AM_V_CCLD)$(LINK) $(demo_vcpinfo_OBJECTS) $(demo_vcpinfo_LDADD) $(LIBS) laclient$(EXEEXT): $(laclient_OBJECTS) $(laclient_DEPENDENCIES) $(EXTRA_laclient_DEPENDENCIES) @rm -f laclient$(EXEEXT) $(AM_V_CCLD)$(LINK) $(laclient_OBJECTS) $(laclient_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/clmain.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_capabilities.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_display_selection.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_feature_list.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_get_set_vcp.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_global_settings.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_profile_features.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_redirection.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_vcpinfo.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool clean-local \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/clmain.Po -rm -f ./$(DEPDIR)/demo_capabilities.Po -rm -f ./$(DEPDIR)/demo_display_selection.Po -rm -f ./$(DEPDIR)/demo_feature_list.Po -rm -f ./$(DEPDIR)/demo_get_set_vcp.Po -rm -f ./$(DEPDIR)/demo_global_settings.Po -rm -f ./$(DEPDIR)/demo_profile_features.Po -rm -f ./$(DEPDIR)/demo_redirection.Po -rm -f ./$(DEPDIR)/demo_vcpinfo.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-local distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/clmain.Po -rm -f ./$(DEPDIR)/demo_capabilities.Po -rm -f ./$(DEPDIR)/demo_display_selection.Po -rm -f ./$(DEPDIR)/demo_feature_list.Po -rm -f ./$(DEPDIR)/demo_get_set_vcp.Po -rm -f ./$(DEPDIR)/demo_global_settings.Po -rm -f ./$(DEPDIR)/demo_profile_features.Po -rm -f ./$(DEPDIR)/demo_redirection.Po -rm -f ./$(DEPDIR)/demo_vcpinfo.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool clean-local \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-local \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ mostlyclean-local pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am .PRECIOUS: Makefile clean-local: @echo "(src/sample_clients/Makefile) clean-local" mostlyclean-local: @echo "(src/sample_clients/Makefile) mostlyclean-local" distclean-local: @echo "(src/sample_clients/Makefile) distclean-local" # Make this a dependency of something to enable it: show_vars: @echo "src/sample_clients/Makefile" @echo "srcdir: ${srcdir}" @echo "top_srcdir: ${top_srcdir}" .PHONY: show_vars # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/sample_clients/demo_capabilities.c0000644000175000001440000001461614754153540016232 // demo_capabilities.c - Query capabilities string // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "public/ddcutil_c_api.h" #define DDC_ERRMSG(function_name,status_code) \ printf("(%s) %s() returned %d (%s): %s\n", \ __func__, function_name, status_code, \ ddca_rc_name(status_code), \ ddca_rc_desc(status_code)) /* A simple function that opens the first detected display using * DDCA_create_display_ref() to locate the display. * * For more detailed examples of display detection and management, * see demo_display_selection.c * * Arguments: none * Returns: display handle of first detected display, * NULL if not found or can't be opened */ DDCA_Display_Handle * open_first_display_by_dispno() { printf("Opening display 1...\n"); DDCA_Display_Identifier did; DDCA_Display_Ref dref; DDCA_Display_Handle dh = NULL; ddca_create_dispno_display_identifier(1, &did); // always succeeds DDCA_Status rc = ddca_get_display_ref(did, &dref); if (rc != 0) { DDC_ERRMSG("ddca_create_display_ref", rc); } else { rc = ddca_open_display2(dref, false, &dh); if (rc != 0) { DDC_ERRMSG("ddca_open_display", rc); } else { printf("Opened display handle: %s\n", ddca_dh_repr(dh)); } } return dh; } /* This is a simplified version of API function ddca_report_parsed_capabilities(), * illustrating use of DDCA_Capabilities. */ void simple_report_parsed_capabilities(DDCA_Capabilities * pcaps, DDCA_Display_Handle dh) { assert(pcaps && memcmp(pcaps->marker, DDCA_CAPABILITIES_MARKER, 4) == 0); printf("Unparsed capabilities string: %s\n", pcaps->unparsed_string); printf("VCP version: %d.%d\n", pcaps->version_spec.major, pcaps->version_spec.minor); printf("Command codes:\n"); for (int cmd_ndx = 0; cmd_ndx < pcaps->cmd_ct; cmd_ndx++) { uint8_t cur_code = pcaps->cmd_codes[cmd_ndx]; printf(" 0x%02x\n", cur_code); } printf("VCP Feature codes:\n"); for (int code_ndx = 0; code_ndx < pcaps->vcp_code_ct; code_ndx++) { DDCA_Cap_Vcp * cur_vcp = &pcaps->vcp_codes[code_ndx]; assert( memcmp(cur_vcp->marker, DDCA_CAP_VCP_MARKER, 4) == 0); char * feature_name = ""; DDCA_Feature_Value_Entry * feature_value_table = NULL; // DDCA_Feature_Metadata metadata = {{0}}; DDCA_Feature_Metadata * metadata = NULL; // printf("(%s) Before ddca_get_feature_metadata_by_dh(), &metadata=%p", __func__, &metadata); DDCA_Status ddcrc = ddca_get_feature_metadata_by_dh( cur_vcp->feature_code, dh, true, // create_default_if_not_found, &metadata); // printf("(%s) ddca_get_feature_metadata_by_dh() returned: %s\n", __func__, ddca_rc_name(ddcrc)); if (ddcrc == 0) { feature_value_table = metadata->sl_values; feature_name = metadata->feature_name; } printf(" Feature: 0x%02x (%s)\n", cur_vcp->feature_code, feature_name); if (cur_vcp->value_ct > 0) { printf(" Values:\n"); for (int ndx = 0; ndx < cur_vcp->value_ct; ndx++) { char * value_desc = "No lookup table"; uint8_t feature_value = cur_vcp->values[ndx]; if (feature_value_table) { value_desc = "Unrecognized feature value"; for (DDCA_Feature_Value_Entry * entry = feature_value_table; entry->value_name; entry++) { // printf("entry->value_code = 0x%02x, entry->value_name=%s\n", entry->value_code, entry->value_name); if (entry->value_code == feature_value) { value_desc = entry->value_name; break; } } // Alternatively, use convenience function to look up value description // ddca_get_simple_nc_feature_value_name_by_table( // feature_value_table, // cur_vcp->values[ndx], // &value_desc); } printf(" 0x%02x: %s\n", cur_vcp->values[ndx], value_desc); } } ddca_free_feature_metadata(metadata); } } /* Retrieves and reports the capabilities string for the first detected monitor. */ void demo_get_capabilities() { DDCA_Display_Handle dh = open_first_display_by_dispno(); if (!dh) goto bye; DDCA_Status rc = 0; rc = ddca_dfr_check_by_dh(dh); if (rc != 0) { DDCA_Error_Detail * erec = ddca_get_error_detail(); printf("OOPS ddca_dfr_check_by_dh() returned %s\n", ddca_rc_name(rc)); ddca_report_error_detail(erec, 1); ddca_free_error_detail(erec); } char * capabilities = NULL; printf("Calling ddca_get_capabilities_string...\n"); rc = ddca_get_capabilities_string(dh, &capabilities); if (rc != 0) DDC_ERRMSG("ddca_get_capabilities_string", rc); else printf("Capabilities: %s\n", capabilities); printf("Second call to ddca_get_capabilities() should be fast since value cached...\n"); rc = ddca_get_capabilities_string(dh, &capabilities); if (rc != 0) DDC_ERRMSG("ddca_get_capabilities_string", rc); else { printf("Capabilities: %s\n", capabilities); printf("Parse the string...\n"); DDCA_Capabilities * pcaps = NULL; rc = ddca_parse_capabilities_string( capabilities, &pcaps); if (rc != 0) DDC_ERRMSG("ddca_parse_capabilities_string", rc); else { printf("Parsing succeeded.\n"); printf("\nReport the result using local function simple_report_parsed_capabilities()...\n"); simple_report_parsed_capabilities(pcaps, dh); printf("\nReport the result using API function ddca_report_parsed_capabilities()...\n"); DDCA_Output_Level saved_ol = ddca_set_output_level(DDCA_OL_VERBOSE); ddca_report_parsed_capabilities_by_dh( pcaps, dh, 0); ddca_set_output_level(saved_ol); ddca_free_parsed_capabilities(pcaps); } } bye: return; } int main(int argc, char** argv) { demo_get_capabilities(); return 0; } ddcutil-2.2.0/src/sample_clients/demo_display_selection.c0000644000175000001440000001407214441414365017305 /* demo_display_selection.c * * This file contains detailed examples of display selection. */ // Copyright (C) 2017-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "public/ddcutil_c_api.h" #define DDC_ERRMSG(function_name,status_code) \ printf("(%s) %s() returned %d (%s): %s\n", \ __func__, function_name, status_code, \ ddca_rc_name(status_code), \ ddca_rc_desc(status_code)) DDCA_Display_Ref display_selection_using_display_detection(bool include_invalid_displays) { printf("\nCheck for monitors using ddca_get_display_info_list2(), include_invalid_displays=%d...\n", include_invalid_displays); // Inquire about detected monitors. DDCA_Display_Info_List * dlist = NULL; ddca_get_display_info_list2(include_invalid_displays, &dlist); printf(" ddca_get_display_info_list2() done. dlist=%p\n", dlist); // A convenience function to report the result of ddca_get_display_info_list2() // output level has no effect on this debug report printf(" Report the result using ddca_report_display_info_list()...\n"); ddca_report_display_info_list(dlist, 2); DDCA_Output_Level saved_output_level = ddca_set_output_level(DDCA_OL_NORMAL); // A similar function that hooks directly into the "ddcutil detect" command. printf("\n Calling ddca_report_active_displays()...\n"); // Note that ddca_set_output_level() affects detail shown: int displayct = ddca_report_displays(include_invalid_displays, 2); printf(" ddca_report_active_displays() found %d displays\n", displayct); printf("\n Calling ddca_report_display_by_dref() for each dlist entry...\n"); for (int ndx = 0; ndx < dlist->ct; ndx++) { DDCA_Display_Ref dref = dlist->info[ndx].dref; // printf("(%s) dref=%p\n", __func__, dref); ddca_report_display_by_dref(dref, 1); } // This example selects the monitor by its ddcutil assigned display number, // since any working ddcutil installation will have at least 1 display. // In practice, selection could be performed using any of the monitor // description fields in DDCA_Display_Info. DDCA_Display_Ref dref = NULL; int desired_display_number = 1; for (int ndx = 0; ndx < dlist->ct; ndx++) { if (dlist->info[ndx].dispno == desired_display_number) { dref = dlist->info[ndx].dref; break; } } if (dref) { printf("Found display: %s\n", ddca_dref_repr(dref) ); // printf("Detailed debug report:\n"); // ddca_dbgrpt_display_ref( // dref, // 1); // logical indentation depth } else printf("Display number %d not found.\n", desired_display_number); // dref is an (opaque) pointer to an internal ddcutil data structure. // It does not need to be freed. ddca_free_display_info_list(dlist); ddca_set_output_level(saved_output_level); return dref; } DDCA_Display_Ref display_selection_using_display_identifier() { DDCA_Display_Identifier did; DDCA_Display_Ref dref; DDCA_Status rc; printf("\nExamples of display identifier creation:\n"); printf("\nCreate a Display Identifier using I2C bus number\n"); ddca_create_busno_display_identifier(7, &did); // always succeeds printf("Created display identifier: %s\n", ddca_did_repr(did) ); ddca_free_display_identifier(did); printf("\nCreate a Display Identifier using mfg code and model\n"); rc = ddca_create_mfg_model_sn_display_identifier("ACI", "VE247", NULL, &did); assert(rc == 0); printf("Created display identifier: %s\n", ddca_did_repr(did) ); ddca_free_display_identifier(did); printf("\nCalling ddca_create_mfg_model_sn_display_identifier() with an invalid argument fails\n"); rc = ddca_create_mfg_model_sn_display_identifier(NULL, "Model name longer than 13 chars", NULL, &did); if (rc != 0) { printf(" ddca_create_mfg_model_sn_display_identifier() returned %d (%s): %s\n", rc, ddca_rc_name(rc), ddca_rc_desc(rc)); } assert(rc!=0 && !did); printf("\nCreate a Display Identifier for display 1...\n"); ddca_create_dispno_display_identifier(1, &did); // always succeeds printf("Created display identifier: %s\n", ddca_did_repr(did) ); printf("\nFind a display reference for the display identifier...\n"); rc = ddca_get_display_ref(did, &dref); if (rc != 0) { printf(" ddca_get_display_ref() returned %d (%s): %s\n", rc, ddca_rc_name(rc), ddca_rc_desc(rc)); } else { printf("Found display reference: %s\n", ddca_dref_repr(dref) ); } ddca_free_display_identifier(did); return dref; } DDCA_Display_Ref demo_get_display_ref() { bool include_invalid_displays = false; DDCA_Display_Ref dref1 = display_selection_using_display_detection(include_invalid_displays); DDCA_Display_Ref dref2 = display_selection_using_display_identifier(); if (include_invalid_displays) { assert(dref1 == dref2); } // printf("Debug report on display reference:\n"); // ddca_report_display_ref(dref1, 2); return dref1; } void demo_use_display_ref(DDCA_Display_Ref dref) { DDCA_Status rc; DDCA_Display_Handle dh; printf("\nOpen the display reference, creating a display handle...\n"); rc = ddca_open_display2(dref, false, &dh); if (rc != 0) { DDC_ERRMSG("ddca_open_display", rc); } else { printf(" display handle: %s\n", ddca_dh_repr(dh)); DDCA_MCCS_Version_Spec vspec; rc = ddca_get_mccs_version_by_dh(dh, &vspec); if (rc != 0) { DDC_ERRMSG("ddca_get_mccs_version_spec", rc); } else { printf("VCP version: %d.%d\n", vspec.major, vspec.minor); } rc = ddca_close_display(dh); if (rc != 0) DDC_ERRMSG("ddca_close_display", rc); } } int main(int argc, char** argv) { printf("\nStarting display selection example....\n"); DDCA_Display_Ref dref = demo_get_display_ref(); if (dref) { demo_use_display_ref(dref); } } ddcutil-2.2.0/src/sample_clients/demo_feature_list.c0000644000175000001440000000660614441414365016265 /* demo_feature_lists.c * * Demonstrate feature list functions. */ // Copyright (C) 2018-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "public/ddcutil_c_api.h" void assert_ddcrc_ok(DDCA_Status ddcrc, const char * ddc_func, const char * caller) { if (ddcrc) { printf("Error in %s(): %s() returned %d (%s): %s\n", caller, ddc_func, ddcrc, ddca_rc_name(ddcrc), ddca_rc_desc(ddcrc)); exit(1); } } void report_ddcrc_error(DDCA_Status ddcrc, const char * ddc_func, const char * caller) { if (ddcrc) { printf("Error in %s(): %s() returned %d (%s): %s\n", caller, ddc_func, ddcrc, ddca_rc_name(ddcrc), ddca_rc_desc(ddcrc)); } } DDCA_Display_Ref get_dref_by_dispno(int dispno) { printf("Getting display reference for display %d...\n", dispno); DDCA_Display_Identifier did; DDCA_Display_Ref dref = NULL; ddca_create_dispno_display_identifier(1, &did); // always succeeds DDCA_Status rc = ddca_get_display_ref(did, &dref); report_ddcrc_error(rc, "ddca_create_display_ref", __func__); assert( (rc==0 && dref) || (rc!=0 && !dref)); return dref; } void demo_feature_lists_for_dref(DDCA_Display_Ref dref) { DDCA_Status ddcrc = 0; // Note that the defined features vary by MCCS version. // In fact whether a feature is of type Table can vary by // MCCS version. // get the feature list for feature set PROFILE DDCA_Feature_List vcplist1; ddcrc = ddca_get_feature_list_by_dref( DDCA_SUBSET_PROFILE, dref, false, // exclude table features &vcplist1); assert_ddcrc_ok(ddcrc, "ddca_get_feature_list_by_dref",__func__); // this is sample code // alternatively, use convenience function ddca_feature_list_string(), see below printf("\nFeatures in feature set PROFILE:\n "); for (int ndx = 0; ndx < 256; ndx++) { if (ddca_feature_list_contains(vcplist1, ndx)) printf(" %02x", ndx); } puts(""); // Assume we have read the values for the VCP features in PROFILE. // The user then changes the feature set to COLOR DDCA_Feature_List vcplist2; ddcrc = ddca_get_feature_list_by_dref( DDCA_SUBSET_COLOR, dref, false, // exclude table features &vcplist2); assert_ddcrc_ok(ddcrc, "ddca_get_feature_list",__func__); // this is sample code printf("\nFeatures in feature set COLOR:\n "); for (int ndx = 0; ndx < 256; ndx++) { if (ddca_feature_list_contains(vcplist2, ndx)) printf(" %02x", ndx); } puts(""); // We only would need to get read the features that have not yet been read DDCA_Feature_List vcplist3 = ddca_feature_list_and_not(vcplist2, vcplist1); printf("\nFeatures in feature set COLOR but not in PROFILE:\n "); // a convenience function: const char * s = ddca_feature_list_string(vcplist3, /*prefix=*/ "", /*sepstr=*/ " "); printf("%s\n", s); } int main(int argc, char** argv) { // Feature group definitions can be VCP version sensitive. // In real code, we'd get the MCCS version from the monitor information. DDCA_Display_Ref dref = get_dref_by_dispno(1); assert(dref); // there's at least 1 display demo_feature_lists_for_dref(dref); return 0; } ddcutil-2.2.0/src/sample_clients/demo_get_set_vcp.c0000644000175000001440000003063014572333721016074 /* demo_get_set_vcp.c * * Demonstrates getting, setting, and interpreting VCP feature values. */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "public/ddcutil_c_api.h" #include "public/ddcutil_status_codes.h" #define DDC_ERRMSG(function_name,status_code) \ do { \ printf("(%s) %s() returned %d (%s): %s\n", \ __func__, function_name, status_code, \ ddca_rc_name(status_code), \ ddca_rc_desc(status_code)); \ } while(0) #define SBOOL(val) ( (val) ? "true" : "false" ) static bool saved_verify_setvcp = false; void set_standard_settings() { // Read value after setting it as verification saved_verify_setvcp = ddca_enable_verify(true); } void restore_standard_settings() { ddca_enable_verify(saved_verify_setvcp); } void show_any_value( DDCA_Display_Handle dh, DDCA_Vcp_Value_Type value_type, DDCA_Vcp_Feature_Code feature_code) { char * libopts = "--ddc"; // report DDC/CI data errors to the terminal ddca_init(libopts, DDCA_SYSLOG_ERROR, DDCA_INIT_OPTIONS_NONE); DDCA_Status ddcrc; DDCA_Any_Vcp_Value * valrec; ddcrc = ddca_get_any_vcp_value_using_explicit_type( dh, feature_code, value_type, &valrec); if (ddcrc != 0) { DDC_ERRMSG("ddca_get_any_vcp_value_using_explicit_type", ddcrc); goto bye; } if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { printf("Non-Table value: mh=0x%02x, ml=0x%02x, sh=0x%02x, ml=0x%02x\n", valrec->val.c_nc.mh, valrec->val.c_nc.ml, valrec->val.c_nc.sh, valrec->val.c_nc.sl); printf("As continuous value (if applicable): max value = %d, cur value = %d\n", valrec->val.c_nc.mh << 8 | valrec->val.c_nc.ml, // or use macro VALREC_MAX_VAL() valrec->val.c_nc.sh << 8 | valrec->val.c_nc.sl); // or use macro VALREC_CUR_VAL() } else { assert(valrec->value_type == DDCA_TABLE_VCP_VALUE); printf("Table value: 0x"); for (int ndx=0; ndxval.t.bytect; ndx++) printf("%02x", valrec->val.t.bytes[ndx]); puts(""); } bye: return; } DDCA_Status perform_set_non_table_vcp_value( DDCA_Display_Handle dh, DDCA_Vcp_Feature_Code feature_code, uint8_t hi_byte, uint8_t lo_byte) { bool saved_enable_verify = ddca_enable_verify(true); DDCA_Status ddcrc = ddca_set_non_table_vcp_value(dh, feature_code, hi_byte, lo_byte); if (ddcrc == DDCRC_VERIFY) { printf("Value verification failed. Current value is now:\n"); show_any_value(dh, DDCA_NON_TABLE_VCP_VALUE, feature_code); } else if (ddcrc != 0) { DDC_ERRMSG("ddca_set_non_table_vcp_value", ddcrc); } else { printf("Setting new value succeeded.\n"); } ddca_enable_verify(saved_enable_verify); return ddcrc; } bool test_continuous_value( DDCA_Display_Handle dh, DDCA_Vcp_Feature_Code feature_code) { DDCA_Status ddcrc; bool ok = false; const char * feature_name = ddca_get_feature_name(feature_code); printf("\nTesting get and set continuous value. dh=%s, feature_code=0x%02x - %s\n", ddca_dh_repr(dh), feature_code, feature_name); printf("Resetting statistics...\n"); ddca_reset_stats(); bool create_default_if_not_found = false; DDCA_Feature_Metadata* info; ddcrc = ddca_get_feature_metadata_by_dh( feature_code, dh, create_default_if_not_found, &info); if (ddcrc != 0) { DDC_ERRMSG("ddca_get_feature_metadata_by_display", ddcrc); goto bye; } if ( !(info->feature_flags & DDCA_CONT) ) { printf("Feature 0x%02x is not Continuous\n", feature_code); goto bye; } DDCA_Non_Table_Vcp_Value valrec; ddcrc = ddca_get_non_table_vcp_value( dh, feature_code, &valrec); if (ddcrc != 0) { DDC_ERRMSG("ddca_get_non_table_vcp_value", ddcrc); ok = false; goto bye; } uint16_t max_val = valrec.mh << 8 | valrec.ml; uint16_t cur_val = valrec.sh << 8 | valrec.sl; printf("Feature 0x%02x (%s) current value = %d, max value = %d\n", feature_code, feature_name, cur_val, max_val); uint16_t old_value = cur_val; uint16_t new_value = old_value/2; printf("Setting new value %d,,,\n", new_value); uint8_t new_sh = new_value >> 8; uint8_t new_sl = new_value & 0xff; DDCA_Status ddcrc1 = perform_set_non_table_vcp_value(dh, feature_code, new_sh, new_sl); if (ddcrc1 != 0 && ddcrc1 != DDCRC_VERIFY) goto bye; printf("Resetting original value %d...\n", old_value); DDCA_Status ddcrc2 = perform_set_non_table_vcp_value(dh, feature_code, old_value>>8, old_value&0xff); if (ddcrc2 != 0 && ddcrc2 != DDCRC_VERIFY) goto bye; if (ddcrc1 == 0 && ddcrc2 == 0) ok = true; bye: // Uncomment to see statistics: // printf("\nStatistics for one execution of %s()", __func__); // ddca_show_stats(DDCA_STATS_ALL, 0); // printf("(%s) Done. Returning: %d\n", __func__, ok); return ok; } // This variant assumes the appropriate feature value table has already // been looked up. bool show_simple_nc_feature_value_by_table( DDCA_Feature_Value_Entry * feature_table, uint8_t feature_value) { char * feature_value_name = NULL; bool ok = false; printf("Performing value lookup using ddca_get_simple_nc_feature_value_name_by_table\n"); DDCA_Status rc = ddca_get_simple_nc_feature_value_name_by_table( feature_table, feature_value, &feature_value_name); if (rc != 0) { DDC_ERRMSG("ddca_get_nc_feature_value_name_by_table", rc); printf("Unable to get interpretation of value 0x%02x\n", feature_value); printf("Current value: 0x%02x\n", feature_value); ok = false; } else { printf("Current value: 0x%02x - %s\n", feature_value, feature_value_name); ok = true; } return ok; } bool test_simple_nc_value( DDCA_Display_Handle dh, DDCA_Vcp_Feature_Code feature_code, uint8_t new_value) { printf("\nTesting get and set of simple NC value: dh=%s, feature_code=0x%02x - %s\n", ddca_dh_repr(dh), feature_code, ddca_get_feature_name(feature_code)); printf("Resetting statistics...\n"); ddca_reset_stats(); DDCA_Status ddcrc; bool ok = false; DDCA_Feature_Metadata* info; ddcrc = ddca_get_feature_metadata_by_dh( feature_code, dh, false, // create_default_if_not_found &info); if (ddcrc != 0) { DDC_ERRMSG("ddca_get_feature_metadata_by_display", ddcrc); goto bye; } // Issue: currently synthesized values are Complex-Continuous, synthesized // metadata would fail test if create_default_if_not_found == true if ( !(info->feature_flags & DDCA_SIMPLE_NC) ) { printf("Feature 0x%02x is not simple NC\n", feature_code); goto bye; } DDCA_Non_Table_Vcp_Value valrec; ddcrc = ddca_get_non_table_vcp_value( dh, feature_code, &valrec); if (ddcrc != 0) { DDC_ERRMSG("ddca_get_non_table_vcp_value", ddcrc); goto bye; } printf("Feature 0x%02x current value = 0x%02x\n", feature_code, valrec.sl); uint8_t old_value = valrec.sl; ok = show_simple_nc_feature_value_by_table(info->sl_values, old_value); if (!ok) goto bye; printf("Setting new value 0x%02x...\n", new_value); DDCA_Status ddcrc1 = perform_set_non_table_vcp_value(dh, feature_code, 0, new_value); if (ddcrc1 != 0 && ddcrc1 != DDCRC_VERIFY) goto bye; printf("Resetting original value 0x%02x...\n", old_value); DDCA_Status ddcrc2 = perform_set_non_table_vcp_value(dh, feature_code, 0, old_value); if (ddcrc2 != 0 && ddcrc2 != DDCRC_VERIFY) goto bye; if (ddcrc1 == 0 && ddcrc2 == 0) ok = true; bye: // uncomment to show statistics: // printf("\nStatistics for one execution of %s()", __func__); // ddca_show_stats(DDCA_STATS_ALL, 0); // printf("(%s) Done. Returning: %s\n", __func__, SBOOL(ok) ); return ok; } // there's no commonly implemented complex NC feature that's writable. Just read. bool test_complex_nc_value( DDCA_Display_Handle dh, DDCA_Vcp_Feature_Code feature_code) { printf("\nTesting query of complex NC value: dh=%s, feature_code=0x%02x - %s\n", ddca_dh_repr(dh), feature_code, ddca_get_feature_name(feature_code)); printf("Resetting statistics...\n"); ddca_reset_stats(); DDCA_Status ddcrc; bool ok = false; DDCA_Feature_Metadata* info; ddcrc = ddca_get_feature_metadata_by_dh( feature_code, dh, // feature info can be MCCS version dependent false, // create_default_if_not_found &info); if (ddcrc != 0) { DDC_ERRMSG("ddca_get_feature_metadata_by_display", ddcrc); goto bye; } assert(info->feature_flags & (DDCA_COMPLEX_NC|DDCA_NC_CONT)); DDCA_Non_Table_Vcp_Value valrec; ddcrc = ddca_get_non_table_vcp_value( dh, feature_code, &valrec); if (ddcrc != 0) { DDC_ERRMSG("ddca_non_table_vcp_value", ddcrc); goto bye; } printf("Feature 0x%02x current value: mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x\n", feature_code, valrec.mh, valrec.ml, valrec.sh, valrec.sl); char * formatted_value; #ifdef ALT ddcrc = ddca_format_non_table_vcp_value( feature_code, info.vspec, info.mmid, &valrec, &formatted_value); #endif ddcrc = ddca_format_non_table_vcp_value_by_dref( feature_code, ddca_display_ref_from_handle(dh), &valrec, &formatted_value); if (ddcrc != 0) { DDC_ERRMSG("ddca_format_non_table_vcp_value", ddcrc); goto bye; } printf("Formatted value: %s\n", formatted_value); free(formatted_value); ok = true; bye: // uncomment to show statistics: // printf("\nStatistics for one execution of %s()", __func__); // ddca_show_stats(DDCA_STATS_ALL, 0); // printf("(%s) Done. Returning: %d\n", __func__, ok); return ok; } int main(int argc, char** argv) { // printf("\n(%s) Starting. argc = %d\n", __func__, argc); int which_test = 0; if (argc > 1) { which_test = atoi(argv[1]); // live dangerously, it's test code } ddca_reset_stats(); set_standard_settings(); DDCA_Status rc; DDCA_Display_Ref dref; DDCA_Display_Handle dh = NULL; // initialize to avoid clang analyzer warning int MAX_DISPLAYS = 4; // limit the number of displays DDCA_Display_Info_List* dlist = NULL; ddca_get_display_info_list2( false, // don't include invalid displays &dlist); for (int ndx = 0; ndx < dlist->ct && ndx < MAX_DISPLAYS; ndx++) { DDCA_Display_Info * dinfo = &dlist->info[ndx]; printf("\n===> Test loop for display %d\n", dinfo->dispno); // For all the gory details: ddca_report_display_info(dinfo, /* depth=*/ 1); dref = dinfo->dref; // printf("Open display reference %s, creating a display handle...\n", ddca_dref_repr(dref)); rc = ddca_open_display2(dref, false, &dh); if (rc != 0) { DDC_ERRMSG("ddca_open_display", rc); continue; } printf("Opened display handle: %s\n", ddca_dh_repr(dh)); if (which_test == 0 || which_test == 1) test_continuous_value(dh, 0x10); if (which_test == 0 || which_test == 2) { // feature 0xcc = OSD language, value 0x03 = French test_simple_nc_value(dh, 0xcc, 0x03); } if (which_test == 0 || which_test == 3) test_complex_nc_value(dh, 0xDF); // VCP version rc = ddca_close_display(dh); if (rc != 0) DDC_ERRMSG("ddca_close_display", rc); dh = NULL; } ddca_free_display_info_list(dlist); restore_standard_settings(); return 0; } ddcutil-2.2.0/src/sample_clients/demo_global_settings.c0000644000175000001440000000235414572333721016754 /** \file demo_global_settings.c * * Sample program illustrating the use of libddcutil's functions for * querying build information and global settings management. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include "public/ddcutil_c_api.h" #include "public/ddcutil_status_codes.h" void demo_build_information() { printf("\nProbe static build information...\n"); // Get the ddcutil version as a string in the form "major.minor.micro". printf(" ddcutil version by ddca_ddcutil_version_string(): %s\n", ddca_ddcutil_version_string() ); // Get the ddcutil version as a struct of integers DDCA_Ddcutil_Version_Spec vspec = ddca_ddcutil_version(); printf(" ddcutil version by ddca_ddcutil_version(): %d.%d.%d\n", vspec.major, vspec.minor, vspec.micro); // Get build options uint8_t build_options = ddca_build_options(); printf(" Built with USB support: %s\n", (build_options & DDCA_BUILT_WITH_USB) ? "yes" : "no"); printf(" Built with failure simulation: %s\n", (build_options & DDCA_BUILT_WITH_FAILSIM) ? "yes" : "no"); } int main(int argc, char** argv) { demo_build_information(); } ddcutil-2.2.0/src/sample_clients/demo_profile_features.c0000644000175000001440000001005714441414365017130 /* demo_get_set_vcp.c * * Demonstrates save and restore of profile related features. */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "public/ddcutil_c_api.h" #include "public/ddcutil_status_codes.h" #define DDC_ERRMSG(function_name,status_code) \ do { \ printf("(%s) %s() returned %d (%s): %s\n", \ __func__, function_name, status_code, \ ddca_rc_name(status_code), \ ddca_rc_desc(status_code)); \ } while(0) #define SBOOL(val) ( (val) ? "true" : "false" ) DDCA_Display_Ref get_dref_by_dispno(int dispno) { printf("Getting display reference for display %d...\n", dispno); DDCA_Display_Identifier did; DDCA_Display_Ref dref = NULL; ddca_create_dispno_display_identifier(1, &did); // always succeeds DDCA_Status rc = ddca_get_display_ref(did, &dref); if (rc != 0) { DDC_ERRMSG("ddca_create_display_ref", rc); } return dref; } // Parameter restore_using_dh indicates whether an existing open display // handle should be used when restoring feature values. // // Display identification (manufacturre, model, serial number) is included // in the saved profile value string. This can be used to open a display // when restoring values. Normally this is sufficient. // However, it is conceivable that that multiple monitors have the same identifiers, // perhaps because the EDID has been cloned. Therefore, restoration // allows for restoring feature values to a display handle that has // already been opened. DDCA_Status demo_get_set_profile_related_values( DDCA_Display_Ref dref, bool restore_using_dh) { printf("\nGetting and setting profile related values. dref = %s, restore_using_dh=%s\n", ddca_dref_repr(dref), SBOOL(restore_using_dh)); bool saved_verify_setvcp = ddca_enable_verify(true); ddca_reset_stats(); DDCA_Status ddcrc = 0; DDCA_Display_Handle dh = NULL; // printf("Open display reference %s, creating a display handle...\n", ddca_dref_repr(dref)); ddcrc = ddca_open_display2(dref, false, &dh); if (ddcrc != 0) { DDC_ERRMSG("ddca_open_display", ddcrc); goto bye; } printf("Opened display handle: %s\n", ddca_dh_repr(dh)); printf("Saving profile related feature values in a string...\n"); char* profile_values_string; ddcrc = ddca_get_profile_related_values(dh, &profile_values_string); if (ddcrc != 0) { DDC_ERRMSG("ddca_get_profile_related_values", ddcrc); goto bye; } printf("profile values string = %s\n", profile_values_string); // must call ddca_close_display() because ddca_set_profile_related_values() // will determine the display to load from the stored values // and open the display itself if (!restore_using_dh) { printf("Closing display handle...\n"); ddca_close_display(dh); dh = NULL; } if (restore_using_dh) printf("\nRestoring profile related values using existing display handle...\n"); else printf("\nSelecting display for restore based on identifiers in the value string...\n"); ddcrc = ddca_set_profile_related_values(dh, profile_values_string); if (ddcrc != 0) { DDC_ERRMSG("ddca_set_profile_related_values", ddcrc); } else { printf("Profile values successfully restored\n"); } if (restore_using_dh) { printf("Closing display handle...\n"); ddca_close_display(dh); } bye: // uncomment if you want to see stats: // printf("\nStatistics for one execution of %s()", __func__); // ddca_show_stats(DDCA_STATS_ALL, 0); ddca_enable_verify(saved_verify_setvcp); return ddcrc; } int main(int argc, char** argv) { ddca_reset_stats(); DDCA_Display_Ref dref = get_dref_by_dispno(1); demo_get_set_profile_related_values(dref, true); demo_get_set_profile_related_values(dref, false); return 0; } ddcutil-2.2.0/src/sample_clients/demo_redirection.c0000644000175000001440000000367114754153540016107 /** @file demo_redirection.c * * Sample program illustrating the use of libddcutil's functions for * redirecting and capturing program output. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include "public/ddcutil_c_api.h" void capture_output_using_convenience_functions() { printf("\nCapturing output using API convenience functions...\n"); ddca_start_capture(DDCA_CAPTURE_NOOPTS); int logical_indentation_depth = 1; ddca_report_displays(false, logical_indentation_depth); char * output = ddca_end_capture(); printf("Captured output:\n%s\n", output); free(output); } void capture_output_using_basic_functions() { printf("\nCapturing output to in core buffer using basic API functions..\n"); size_t size; char * ptr; // Alternatively, use fmemopen() to use a pre-allocated in-memory buffer // or fopen() to open a file. FILE * f = open_memstream(&ptr, &size); if (!f) { perror("Error opening file "); return; } ddca_set_fout(f); int logical_indentation_depth = 1; ddca_report_displays(false, logical_indentation_depth); // Ensure output actually written to FILE: int rc = fflush(f); if (rc < 0) { perror("fflush() failed"); return; } // size does not include trailing null appended by fmemopen() printf("Size after writing to buffer: %zd\n", size); ddca_set_fout_to_default(); // must copy data before closing buffer char * result = strdup(ptr); rc = fclose(f); if (rc < 0) { perror("Error closing in core buffer"); free(result); return; } printf("Output:\n"); printf("%s\n", result); free(result); } int main(int argc, char** argv) { capture_output_using_convenience_functions(); capture_output_using_basic_functions(); } ddcutil-2.2.0/src/sample_clients/demo_vcpinfo.c0000644000175000001440000001601014754153540015233 /* demo_vcpinfo.c * * Query VCP feature information and capabilities string */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "public/ddcutil_c_api.h" #define DDC_ERRMSG(function_name,status_code) \ do { \ printf("(%s) %s() returned %d (%s): %s\n", \ __func__, function_name, status_code, \ ddca_rc_name(status_code), \ ddca_rc_desc(status_code)); \ } while(0) #ifdef UNUSED /* A simple function that opens the first detected display. * For more detailed examples of display detection and management, * see demo_display_selection.c * * Arguments: none * Returns: display handle of first detected display, * NULL if not found or can't be opened */ DDCA_Display_Handle * open_first_display_by_dlist() { printf("Check for monitors using ddca_get_displays()...\n"); DDCA_Display_Handle dh = NULL; // Inquire about detected monitors. DDCA_Display_Info_List* dlist = NULL; ddca_get_display_info_list2( false, // don't include invalid displays &dlist); assert(dlist); // this is sample code if (dlist->ct == 0) { printf(" No DDC capable displays found\n"); } else { DDCA_Display_Info * dinf = &dlist->info[0]; DDCA_Display_Ref * dref = dinf->dref; printf("Opening display %s\n", dinf->model_name); printf("Model: %s\n", dinf->model_name); printf("Model: %s\n", dinf->mmid.model_name); DDCA_Status rc = ddca_open_display2(dref, false, &dh); if (rc != 0) { DDC_ERRMSG("ddca_open_display2", rc); } } ddca_free_display_info_list(dlist); return dh; } #endif /* Creates a string representation of DDCA_Feature_Flags bitfield. * * Arguments: * flags feature characteristics * * Returns: string representation, caller must free */ char * interpret_feature_flags(DDCA_Version_Feature_Flags flags) { char * buffer = NULL; int rc = asprintf(&buffer, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s", flags & DDCA_RO ? "Read-Only, " : "", flags & DDCA_WO ? "Write-Only, " : "", flags & DDCA_RW ? "Read-Write, " : "", flags & DDCA_STD_CONT ? "Continuous (standard), " : "", flags & DDCA_COMPLEX_CONT ? "Continuous (complex), " : "", flags & DDCA_SIMPLE_NC ? "Non-Continuous (simple), " : "", flags & DDCA_COMPLEX_NC ? "Non-Continuous (complex), " : "", flags & DDCA_NC_CONT ? "Non-Continuous with continuous subrange, " :"", flags & DDCA_WO_NC ? "Non-Continuous (write-only), " : "", flags & DDCA_NORMAL_TABLE ? "Table (readable), " : "", flags & DDCA_WO_TABLE ? "Table (write-only), " : "", flags & DDCA_DEPRECATED ? "Deprecated, " : "", flags & DDCA_SYNTHETIC ? "Synthesized, " : "", flags & DDCA_USER_DEFINED ? "User-defined, " : "" ); assert(rc >= 0); // real life code would check for malloc() failure in asprintf() // remove final comma and blank if (strlen(buffer) > 0) buffer[strlen(buffer)-2] = '\0'; return buffer; } /* Displays the contents of DDCA_Feature_Metadata instance. * * Arguments: * info pointer to DDCA_Feature_Metadata instance */ void show_feature_metadata(DDCA_Feature_Metadata * info) { printf("\nVersion Sensitive Feature Metadata for VCP Feature: 0x%02x - %s\n", info->feature_code, info->feature_name); // printf(" VCP version: %d.%d\n", info->vspec.major, info->vspec.minor); printf(" Description: %s\n", info->feature_desc); char * s = interpret_feature_flags(info->feature_flags); printf(" Feature flags: %s\n", s); free(s); if (info->sl_values) { printf(" SL values: \n"); DDCA_Feature_Value_Entry * cur_entry = info->sl_values; while (cur_entry->value_name) { printf(" 0x%02x - %s\n", cur_entry->value_code, cur_entry->value_name); cur_entry++; } } } /* Retrieves and displays feature information for a specified feature code * and MCCS version. */ void test_single_feature_info( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, bool create_default_if_not_found) { // printf("\n(%s) Getting metadata for feature 0x%02x, mccs version = %d.%d\n", __func__, // feature_code, vspec.major, vspec.minor); // printf("Feature name: %s\n", ddca_feature_name_by_vspec(feature_code, vspec)); DDCA_Feature_Metadata* metadata; DDCA_Status rc = ddca_get_feature_metadata_by_vspec( feature_code, vspec, create_default_if_not_found, &metadata); if (rc != 0) { printf("\nUnable to retrieve version sensitive metadata for VCP Feature 0x%02x, MCCS version %d.%d\n", feature_code, vspec.major, vspec.minor); // printf("ddca_get_feature_info_by_vcp_version() returned DDC_ERRMSG("ddca_get_feature_info_by_vcp_version", rc); } else { if (metadata->feature_flags & DDCA_SYNTHETIC) { if (feature_code >= 0xe0) printf("\nCreated synthetic metadata for manufacturer-specific feature.\n"); else printf("\nCreated synthetic metadata for unrecognized feature code.\n"); } show_feature_metadata(metadata); } // printf("%s) Done.\n", __func__); } void demo_feature_info() { // #ifdef NO DDCA_Vcp_Feature_Code feature_codes[] = { 0x00, // invalid code 0x02, // NC, complex // 0x03, // NC, simple (one simple-nc is enuf) 0x10, // Continuous // 0x43, // Continuous (one Cont is enuf) 0x60, // Simple NC 0xe0}; // mfg specific // #endif // DDCA_Vcp_Feature_Code feature_codes[] = {0x43}; // DDCA_MCCS_Version_Spec vspecs[] = { // DDCA_VSPEC_V10, DDCA_VSPEC_V20,DDCA_VSPEC_V21, // DDCA_VSPEC_V22,DDCA_VSPEC_V30,DDCA_VSPEC_UNKNOWN}; DDCA_MCCS_Version_Spec vspecs[] = {DDCA_VSPEC_V20}; int feature_ct = sizeof(feature_codes)/sizeof(DDCA_Vcp_Feature_Code); int vspec_ct = sizeof(vspecs)/sizeof(DDCA_MCCS_Version_Spec); bool create_default_if_not_found = true; printf("\nCreate default if not found: %s\n", (create_default_if_not_found) ? "true" : "false"); for (int feature_ndx = 0; feature_ndx < feature_ct; feature_ndx++) { for (int vspsec_ndx = 0; vspsec_ndx < vspec_ct; vspsec_ndx++) { test_single_feature_info(feature_codes[feature_ndx], vspecs[vspsec_ndx], create_default_if_not_found); } } } int main(int argc, char** argv) { demo_feature_info(); return 0; } ddcutil-2.2.0/src/sample_clients/clmain.c0000644000175000001440000000557014441414365014035 /* clmain.c * * Framework for test code * * * Copyright (C) 2014-2020 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include "public/ddcutil_c_api.h" #define DDC_ERRMSG(function_name,status_code) \ printf("(%s) %s() returned %d (%s): %s\n", \ __func__, function_name, status_code, \ ddca_rc_name(status_code), \ ddca_rc_desc(status_code)) int main(int argc, char** argv) { printf("\n(%s) Starting.\n", __func__); ddca_reset_stats(); DDCA_Status rc; DDCA_Display_Ref dref; DDCA_Display_Handle dh = NULL; // initialize to avoid clang analyzer warning DDCA_Display_Info_List* dlist = NULL; ddca_get_display_info_list2( false, // don't include invalid displays &dlist); for (int ndx = 0; ndx < dlist->ct; ndx++) { DDCA_Display_Info * dinfo = &dlist->info[ndx]; ddca_report_display_info(dinfo, /* depth=*/ 1); printf("\n(%s) ===> Test loop for display %d\n", __func__, dinfo->dispno); #ifdef ALT DDCA_Display_Identifier did = NULL; printf("Create a Display Identifier for display %d...\n", dispno); rc = ddca_create_dispno_display_identifier(dispno, &did); printf("Create a display reference from the display identifier...\n"); rc = ddca_get_display_ref(did, &dref); assert(rc == 0); rc = ddca_free_display_identifier(did); printf("ddca_free_display_identifier() returned %d\n", rc); #endif dref = dinfo->dref; printf("Open the display reference, creating a display handle...\n"); rc = ddca_open_display2(dref, false, &dh); if (rc != 0) { DDC_ERRMSG("ddca_open_display2", rc); continue; } printf("(%s) Opened display handle: %s\n", __func__, ddca_dh_repr(dh)); // // Insert test code here // rc = ddca_close_display(dh); if (rc != 0) DDC_ERRMSG("ddca_close_display", rc); } ddca_show_stats(DDCA_STATS_ALL, /*by_thread=*/false, 0); return 0; } ddcutil-2.2.0/src/test/0000775000175000001440000000000014754576332010470 5ddcutil-2.2.0/src/test/i2c/0000775000175000001440000000000014754576332011145 5ddcutil-2.2.0/src/test/i2c/i2c_testutil.c0000644000175000001440000001035714572333721013636 // i2c_testutil.c // Copyright (C) 2014-2018 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "util/data_structures.h" #include "util/string_util.h" #include "i2c/wrap_i2c-dev.h" #include "i2c/i2c_bus_core.h" #include "i2c_testutil.h" // Functions and data structures for interpreting the I2C bus functionality flags. // They are overly complex for production use. They were created during development // to facilitate exploratory programming. // Note 2 entries for I2C_FUNC_I2C. Usage must take this into account. Value_Name_Title_Table functionality_table2 = { // flag I2C function name VNT(I2C_FUNC_I2C , "ioctl_write"), VNT(I2C_FUNC_I2C , "ioctl_read"), VNT(I2C_FUNC_10BIT_ADDR , NULL), VNT(I2C_FUNC_PROTOCOL_MANGLING , NULL), VNT(I2C_FUNC_SMBUS_PEC , "i2c_smbus_pec"), VNT(I2C_FUNC_SMBUS_BLOCK_PROC_CALL , "i2c_smbus_block_proc_call"), VNT(I2C_FUNC_SMBUS_QUICK , "i2c_smbus_quick"), VNT(I2C_FUNC_SMBUS_READ_BYTE , "i2c_smbus_read_byte"), VNT(I2C_FUNC_SMBUS_WRITE_BYTE , "i2c_smbus_write_byte"), VNT(I2C_FUNC_SMBUS_READ_BYTE_DATA , "i2c_smbus_read_byte_data"), VNT(I2C_FUNC_SMBUS_WRITE_BYTE_DATA , "i2c_smbus_write_byte_data"), VNT(I2C_FUNC_SMBUS_READ_WORD_DATA , "i2c_smbus_read_word_data"), VNT(I2C_FUNC_SMBUS_WRITE_WORD_DATA , "i2c_smbus_write_word_data"), VNT(I2C_FUNC_SMBUS_PROC_CALL , "i2c_smbus_proc_call"), VNT(I2C_FUNC_SMBUS_READ_BLOCK_DATA , "i2c_smbus_read_block_data"), VNT(I2C_FUNC_SMBUS_WRITE_BLOCK_DATA , "i2c_smbus_write_block_data"), VNT(I2C_FUNC_SMBUS_READ_I2C_BLOCK , "i2c_smbus_read_i2c_block_data"), VNT(I2C_FUNC_SMBUS_WRITE_I2C_BLOCK , "i2c_smbus_write_i2c_block_data"), VNT_END }; // // For test driver use only // static bool is_function_supported(int busno, char * funcname) { bool debug = false; DBGMSF(debug, "Starting. busno=%d, funcname=%s", busno, funcname); bool result = true; if ( !streq(funcname, "read") && !streq(funcname, "write") ) { int32_t func_bit = vnt_find_id( functionality_table2, funcname, true, // search title field false, // ignore_case, 0x00); // default_id); if (!func_bit) { DBGMSG("Unrecognized function name: %s", funcname); result = false; goto bye; } // DBGMSG("functionality=0x%lx, func_table_entry->bit=-0x%lx", bus_infos[busno].functionality, func_table_entry->bit); // Bus_Info * bus_info = i2c_get_bus_info(busno, DISPSEL_NONE); // Bus_Info * bus_info = i2c_get_bus_info_new(busno); I2C_Bus_Info * bus_info = i2c_detect_single_bus(busno); if ( !bus_info ) { DBGMSG("Invalid bus: /dev/i2c-%d", busno); result = false; } else // add unneeded else clause to avoid clang warning result = (bus_info->functionality & func_bit) != 0; i2c_free_bus_info(bus_info); } bye: DBGMSF(debug, "busno=%d, funcname=%s, returning %d", busno, funcname, result); return result; } /** Verify that the specified I2C write and read functions are supported. * * This function is used in test management. * * @param busno I2C bus number * @param write_func_name write function name * @param read_func_name read function name * * @return true/false */ bool i2c_verify_functions_supported(int busno, char * write_func_name, char * read_func_name) { // printf("(%s) Starting. busno=%d, write_func_name=%s, read_func_name=%s\n", // __func__, busno, write_func_name, read_func_name); bool write_supported = is_function_supported(busno, write_func_name); bool read_supported = is_function_supported(busno, read_func_name); if (!write_supported) printf("Unsupported write function: %s\n", write_func_name ); if (!read_supported) printf("Unsupported read function: %s\n", read_func_name ); bool result =write_supported && read_supported; // DBGMSG("returning %d", result); return result; } ddcutil-2.2.0/src/test/i2c/i2c_testutil.h0000664000175000001440000000051414754576332013650 // i2c_testutil.h // Copyright (C) 2014-2018 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #ifndef I2C_TESTUTIL_H_ #define I2C_TESTUTIL_H_ bool i2c_verify_functions_supported(int busno, char * write_func_name, char * read_func_name); #endif /* I2C_TESTUTIL_H_ */ ddcutil-2.2.0/src/test/Makefile.am0000644000175000001440000000060114453523116012423 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = -Wall -Werror CLEANFILES = \ *expand # Intermediate library noinst_LTLIBRARIES = libtestcases.la if INCLUDE_TESTCASES_COND libtestcases_la_SOURCES = \ i2c/i2c_testutil.c \ testcase_table.c \ testcases.c else libtestcases_la_SOURCES = \ testcase_mock_table.c endif ddcutil-2.2.0/src/test/Makefile.in0000664000175000001440000005263214754576155012470 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/test ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libtestcases_la_LIBADD = am__libtestcases_la_SOURCES_DIST = testcase_mock_table.c \ i2c/i2c_testutil.c testcase_table.c testcases.c am__dirstamp = $(am__leading_dot)dirstamp @INCLUDE_TESTCASES_COND_FALSE@am_libtestcases_la_OBJECTS = \ @INCLUDE_TESTCASES_COND_FALSE@ testcase_mock_table.lo @INCLUDE_TESTCASES_COND_TRUE@am_libtestcases_la_OBJECTS = \ @INCLUDE_TESTCASES_COND_TRUE@ i2c/i2c_testutil.lo \ @INCLUDE_TESTCASES_COND_TRUE@ testcase_table.lo testcases.lo libtestcases_la_OBJECTS = $(am_libtestcases_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/testcase_mock_table.Plo \ ./$(DEPDIR)/testcase_table.Plo ./$(DEPDIR)/testcases.Plo \ i2c/$(DEPDIR)/i2c_testutil.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libtestcases_la_SOURCES) DIST_SOURCES = $(am__libtestcases_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = -Wall -Werror CLEANFILES = \ *expand # Intermediate library noinst_LTLIBRARIES = libtestcases.la @INCLUDE_TESTCASES_COND_FALSE@libtestcases_la_SOURCES = \ @INCLUDE_TESTCASES_COND_FALSE@testcase_mock_table.c @INCLUDE_TESTCASES_COND_TRUE@libtestcases_la_SOURCES = \ @INCLUDE_TESTCASES_COND_TRUE@i2c/i2c_testutil.c \ @INCLUDE_TESTCASES_COND_TRUE@testcase_table.c \ @INCLUDE_TESTCASES_COND_TRUE@testcases.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/test/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } i2c/$(am__dirstamp): @$(MKDIR_P) i2c @: > i2c/$(am__dirstamp) i2c/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) i2c/$(DEPDIR) @: > i2c/$(DEPDIR)/$(am__dirstamp) i2c/i2c_testutil.lo: i2c/$(am__dirstamp) i2c/$(DEPDIR)/$(am__dirstamp) libtestcases.la: $(libtestcases_la_OBJECTS) $(libtestcases_la_DEPENDENCIES) $(EXTRA_libtestcases_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libtestcases_la_OBJECTS) $(libtestcases_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) -rm -f i2c/*.$(OBJEXT) -rm -f i2c/*.lo distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testcase_mock_table.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testcase_table.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testcases.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@i2c/$(DEPDIR)/i2c_testutil.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs -rm -rf i2c/.libs i2c/_libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -rm -f i2c/$(DEPDIR)/$(am__dirstamp) -rm -f i2c/$(am__dirstamp) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/testcase_mock_table.Plo -rm -f ./$(DEPDIR)/testcase_table.Plo -rm -f ./$(DEPDIR)/testcases.Plo -rm -f i2c/$(DEPDIR)/i2c_testutil.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/testcase_mock_table.Plo -rm -f ./$(DEPDIR)/testcase_table.Plo -rm -f ./$(DEPDIR)/testcases.Plo -rm -f i2c/$(DEPDIR)/i2c_testutil.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-noinstLTLIBRARIES \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/test/testcase_mock_table.c0000666000175000001440000000206013230570533014530 /* testcase_mock_table.c * * * Copyright (C) 2014-2016 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "testcase_table.h" Testcase_Descriptor testcase_catalog[] = {}; int testcase_catalog_ct = sizeof(testcase_catalog)/sizeof(Testcase_Descriptor); ddcutil-2.2.0/src/test/testcase_table.c0000644000175000001440000000242114453523116013517 /* testcase_table.c * * * Copyright (C) 2014-2022 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "config.h" #include "testcase_table.h" Testcase_Descriptor testcase_catalog[] = { // {"get_luminosity_sample_code", DisplayRefBus, NULL, get_luminosity_sample_code, NULL, NULL}, // {"demo_p2411_problem", DisplayRefBus, NULL, demo_p2411_problem, NULL, NULL} }; int testcase_catalog_ct = sizeof(testcase_catalog)/sizeof(Testcase_Descriptor); ddcutil-2.2.0/src/test/testcases.c0000644000175000001440000000617514441414365012547 /* testcases.c * * Dispatch test cases * * * Copyright (C) 2014-2022 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include #include #include "base/core.h" // #include "adl/adl_shim.h" #include "test/testcase_table.h" #include void show_test_cases() { if (testcase_catalog_ct == 0) { printf("\nNo test cases\n"); } else { printf("\n Test Cases:\n"); int ndx = 0; // int testcase_catalog_ct = get_testcase_catalog_ct(); // Testcase_Descriptor ** testcase_catalog = get_testcase_catalog(); for (;ndx < testcase_catalog_ct; ndx++) { printf(" %d - %s\n", ndx+1, testcase_catalog[ndx].name); } } puts(""); } Testcase_Descriptor * get_testcase_descriptor(int testnum) { Testcase_Descriptor * result = NULL; // int testcase_catalog_ct = get_testcase_catalog_ct(); // Testcase_Descriptor ** testcase_catalog = get_testcase_catalog(); if (testnum > 0 && testnum <= testcase_catalog_ct) { result = &testcase_catalog[testnum-1]; } return result; } bool execute_testcase(int testnum, Display_Identifier* pdid) { bool ok = true; Testcase_Descriptor * pDesc = NULL; if (ok) { pDesc = get_testcase_descriptor(testnum); if (!pDesc) { printf("Invalid test number: %d\n", testnum); ok = false; } } if (ok) { switch (pDesc->drefType) { case DisplayRefNone: pDesc->fp_noarg(); break; case DisplayRefBus: // if (parsedCmd->dref->ddc_io_mode == DDC_IO_ADL) { if (pdid->id_type != DISP_ID_BUSNO) { printf("Test %d requires bus number\n", testnum); ok = false; } else { // pDesc->fp_bus(parsedCmd->dref->busno); pDesc->fp_bus(pdid->busno); } break; case DisplayRefAny: { // pDesc->fp_dr(parsedCmd->dref); Display_Ref* pdref = NULL; pdref = create_bus_display_ref(pdid->busno); pDesc->fp_dr(pdref); } break; default: PROGRAM_LOGIC_ERROR("Impossible display id type: %d\n", pDesc->drefType); ok = false; } // switch } return ok; } ddcutil-2.2.0/src/test/testcase_table.h0000664000175000001440000000347314754576332013552 /* testcase_table.h * * * Copyright (C) 2014-2016 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef TESTCASE_TABLE_H_ #define TESTCASE_TABLE_H_ #include "base/displays.h" // type of display reference required/supported by the command typedef enum {DisplayRefNone, DisplayRefAny, DisplayRefBus, DisplayRefAdl} DisplayRefType; typedef void (*NoArgFunction)(); typedef void (*BusArgFunction)(int busno); typedef void (*AdlArgFunction)(int iAdapterIndex, int iDisplayIndex); typedef void (*DisplayRefArgFunction)(Display_Ref * dref); typedef struct { char * name; // testcase description DisplayRefType drefType; // should really be a union NoArgFunction fp_noarg; BusArgFunction fp_bus; AdlArgFunction fp_adl; DisplayRefArgFunction fp_dr; } Testcase_Descriptor; extern Testcase_Descriptor testcase_catalog[]; extern int testcase_catalog_ct; // Testcase_Descriptor ** get_testcase_catalog(); // int get_testcase_catalog_ct(); #endif /* TESTCASE_TABLE_H_ */ ddcutil-2.2.0/src/test/testcases.h0000664000175000001440000000216314754576332012561 /* testcases.h * * Manages test cases * * * Copyright (C) 2014-2016 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef TESTCASES_H_ #define TESTCASES_H_ #include #include void show_test_cases(); bool execute_testcase(int testnum, Display_Identifier* pdid); #endif /* TESTCASES_H_ */ ddcutil-2.2.0/src/usb/0000775000175000001440000000000014754576332010302 5ddcutil-2.2.0/src/usb/Makefile.am0000644000175000001440000000125714572333721012250 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand clean-local: @echo "(src/usb/Makefile) clean-local" mostlyclean-local: @echo "(src/usb/Makefile) mostlyclean-local" distclean-local: @echo "(src/usb/Makefile) distclean-local" dist-hook: @echo "(src/usb/Makefile) dist-hook. top_distdir=$(top_distdir) distdir=$(distdir)" find $(distdir) -name "*.o" find $(distdir) -name "*.lo" if ENABLE_USB_COND # Intermediate library noinst_LTLIBRARIES = libusb.la libusb_la_SOURCES = \ usb_base.c \ usb_displays.c \ usb_edid.c \ usb_services.c \ usb_vcp.c endif ddcutil-2.2.0/src/usb/Makefile.in0000664000175000001440000005271414754576155012303 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/usb ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libusb_la_LIBADD = am__libusb_la_SOURCES_DIST = usb_base.c usb_displays.c usb_edid.c \ usb_services.c usb_vcp.c @ENABLE_USB_COND_TRUE@am_libusb_la_OBJECTS = usb_base.lo \ @ENABLE_USB_COND_TRUE@ usb_displays.lo usb_edid.lo \ @ENABLE_USB_COND_TRUE@ usb_services.lo usb_vcp.lo libusb_la_OBJECTS = $(am_libusb_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = @ENABLE_USB_COND_TRUE@am_libusb_la_rpath = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/usb_base.Plo \ ./$(DEPDIR)/usb_displays.Plo ./$(DEPDIR)/usb_edid.Plo \ ./$(DEPDIR)/usb_services.Plo ./$(DEPDIR)/usb_vcp.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libusb_la_SOURCES) DIST_SOURCES = $(am__libusb_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate library @ENABLE_USB_COND_TRUE@noinst_LTLIBRARIES = libusb.la @ENABLE_USB_COND_TRUE@libusb_la_SOURCES = \ @ENABLE_USB_COND_TRUE@usb_base.c \ @ENABLE_USB_COND_TRUE@usb_displays.c \ @ENABLE_USB_COND_TRUE@usb_edid.c \ @ENABLE_USB_COND_TRUE@usb_services.c \ @ENABLE_USB_COND_TRUE@usb_vcp.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/usb/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/usb/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libusb.la: $(libusb_la_OBJECTS) $(libusb_la_DEPENDENCIES) $(EXTRA_libusb_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(am_libusb_la_rpath) $(libusb_la_OBJECTS) $(libusb_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/usb_base.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/usb_displays.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/usb_edid.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/usb_services.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/usb_vcp.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/usb_base.Plo -rm -f ./$(DEPDIR)/usb_displays.Plo -rm -f ./$(DEPDIR)/usb_edid.Plo -rm -f ./$(DEPDIR)/usb_services.Plo -rm -f ./$(DEPDIR)/usb_vcp.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-local distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/usb_base.Plo -rm -f ./$(DEPDIR)/usb_displays.Plo -rm -f ./$(DEPDIR)/usb_edid.Plo -rm -f ./$(DEPDIR)/usb_services.Plo -rm -f ./$(DEPDIR)/usb_vcp.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am dist-hook \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-local distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool mostlyclean-local pdf \ pdf-am ps ps-am tags tags-am uninstall uninstall-am .PRECIOUS: Makefile clean-local: @echo "(src/usb/Makefile) clean-local" mostlyclean-local: @echo "(src/usb/Makefile) mostlyclean-local" distclean-local: @echo "(src/usb/Makefile) distclean-local" dist-hook: @echo "(src/usb/Makefile) dist-hook. top_distdir=$(top_distdir) distdir=$(distdir)" find $(distdir) -name "*.o" find $(distdir) -name "*.lo" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/usb/usb_base.c0000644000175000001440000002405514754153540012145 /** \file usb_base.c * * Functions that open and close USB HID devices, and that wrap * hiddev ioctl() calls. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include "util/string_util.h" #include "usb_util/hiddev_util.h" #include "base/core.h" #ifdef ALT_LOCK_REC #include "base/display_lock.h" #endif #include "base/execution_stats.h" #include "base/linux_errno.h" #include "base/rtti.h" #include "usb/usb_base.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_USB; // In keeping with the style of Linux USB code, this file prefers // "struct xxx {}" to "typedef struct {} xxx" // // Basic USB HID Device Operations // #ifdef ALT_LOCK_REC Error_Info * lock_display_by_usb_monitor_info( Usb_Monitor_Info * usbinfo, Display_Lock_Flags flags) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "USB device %s, flags=%s", usbinfo->hiddev_device_name, interpret_display_lock_flags_t(flags)); Display_Lock_Record * lockid = usbinfo->lock_rec; Error_Info * result = lock_display(lockid, flags); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, "device=%s", usbinfo->hiddev_device_name); return result; } Error_Info * unlock_display_by_usb_monitor_info(Usb_Monitor_Info * usbinfo) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "USB device %s", usbinfo->hiddev_device_name); Display_Lock_Record * lockid = usbinfo->lock_rec; Error_Info * result = unlock_display(lockid); DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, result, "device=%s", usbinfo->hiddev_device_name); return result; } #endif /** Open a USB device * * @param hiddev_devname * @param calloptions option flags, checks CALLOPT_RD_ONLY, CALLOPT_ERR_MSG * @return file descriptor (>0) if success, -errno if failure */ int usb_open_hiddev_device( char * hiddev_devname, Call_Options calloptions) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "hiddev_devname=%s, calloptions=0x%02x (%s)", hiddev_devname, calloptions, interpret_call_options_t(calloptions) ); int file; int mode = (calloptions & CALLOPT_RDONLY) ? O_RDONLY : O_RDWR; RECORD_IO_EVENT( -1, IE_OPEN, ( file = open(hiddev_devname, mode) ) ); // per man open: // returns file descriptor if successful // -1 if error, and errno is set if (file < 0) { int errsv = errno; if (calloptions & CALLOPT_ERR_MSG) f0printf(ferr(), "Open failed for %s: errno=%s\n", hiddev_devname, linux_errno_desc(errsv)); file = -errsv; } DBGMSF(debug, "open() finished, file=%d", file); DBGTRC(debug, TRACE_GROUP, "Returning file descriptor: %d", file); return file; } /** Closes an open USB device. * * @param fd file descriptor for open hiddev device * @param device_fn for use in msgs, ok if NULL * @param calloptions CALLOPT_ERR_MSG recognized * @return -errno if close fails */ Status_Errno usb_close_device( int fd, char * device_fn, Call_Options calloptions) { bool debug = false; DBGMSF(debug, "Starting. fd=%d, device_fn=%s, calloptions=0x%02x", fd, device_fn, calloptions); errno = 0; int rc = 0; RECORD_IO_EVENT(fd, IE_CLOSE, ( rc = close(fd) ) ); int errsv = errno; assert(rc<=0); if (rc < 0) { // EBADF fd isn't a valid open file descriptor // EINTR close() interrupted by a signal // EIO I/O error char workbuf[300]; if (device_fn) snprintf(workbuf, 300, "Close failed for USB device %s. errno=%s", device_fn, linux_errno_desc(errsv)); else snprintf(workbuf, 300, "USB device close failed. errno=%s", linux_errno_desc(errsv)); if (calloptions & CALLOPT_ERR_MSG) fprintf(stderr, "%s\n", workbuf); rc = -errsv; } assert(rc <= 0); return rc; } // // Wrapper hiddev ioctl calls // Status_Errno hiddev_get_device_info( int fd, struct hiddev_devinfo * dev_info, Byte calloptions) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Starting."); assert(dev_info); int rc = ioctl(fd, HIDIOCGDEVINFO, dev_info); if (rc != 0) { int errsv = errno; if ( (calloptions & CALLOPT_ERR_MSG) || debug) REPORT_IOCTL_ERROR("HIDIOCGDEVINFO", errsv); rc = -errsv; } assert(rc <= 0); DBGTRC(debug, TRACE_GROUP, "Done. Returning: %s", psc_desc(rc)); return rc; } Status_Errno hiddev_get_report_info(int fd, struct hiddev_report_info * rinfo, Byte calloptions) { assert(rinfo); int rc = ioctl(fd, HIDIOCGREPORTINFO, rinfo); if (rc < -1) { // -1 means no more reports int errsv = errno; if (calloptions & CALLOPT_ERR_MSG) REPORT_IOCTL_ERROR("HIDIOCGREPORTINFO", errsv); rc = -errsv; } return rc; } Status_Errno hiddev_get_field_info(int fd, struct hiddev_field_info * finfo, Byte calloptions) { int saved_field_index = finfo->field_index; int rc = ioctl(fd, HIDIOCGFIELDINFO, finfo); if (rc != 0) { int errsv = errno; if (calloptions & CALLOPT_ERR_MSG) REPORT_IOCTL_ERROR("HIDIOCGFIELDINFO", errsv); } assert(rc == 0); if (finfo->field_index != saved_field_index && (calloptions & CALLOPT_WARN_FINDEX)) { printf("(%s) !!! ioctl(HIDIOCGFIELDINFO) changed field_index from %d to %d\n", __func__, saved_field_index, finfo->field_index); printf("(%s) finfo.maxusage=%d\n", __func__, finfo->maxusage); } return rc; } Status_Errno hiddev_get_usage_code(int fd, struct hiddev_usage_ref * uref, Byte calloptions) { int rc = ioctl(fd, HIDIOCGUCODE, uref); // Fills in usage code if (rc != 0) { int errsv = errno; if (calloptions & CALLOPT_ERR_MSG) REPORT_IOCTL_ERROR("HIDIOCGUCODE", errsv); rc = -errsv; } return rc; } Status_Errno hiddev_get_usage_value(int fd, struct hiddev_usage_ref * uref, Byte calloptions) { int rc = ioctl(fd, HIDIOCGUSAGE, uref); if (rc != 0) { int errsv = errno; if (calloptions & CALLOPT_ERR_MSG) REPORT_IOCTL_ERROR("HIDIOCGUSAGE", errsv); rc = -errsv; } return rc; } Status_Errno hiddev_get_report(int fd, struct hiddev_report_info * rinfo, Byte calloptions) { int rc = ioctl(fd, HIDIOCGUCODE, rinfo); if (rc != 0) { int errsv = errno; if (calloptions & CALLOPT_ERR_MSG) REPORT_IOCTL_ERROR("HIDIOCGREPORT", errsv); rc = -errsv; } return rc; } static Bit_Set_32 ignored_hiddevs; static uint8_t ignored_vid_pid_ct = 0; static Vid_Pid_Value* ignored_vid_pids = NULL; /** Specify /dev/usb/hiddev devices to be ignored, using hiddev bus numbers. * * @param ignored_hiddev_flags bits indicate hiddev device numbers to ignore */ void usb_ignore_hiddevs(Bit_Set_32 ignored_hiddevs_flags) { bool debug = false; ignored_hiddevs = ignored_hiddevs_flags; char buf[BIT_SET_32_MAX+1]; DBGTRC_EXECUTED(debug, TRACE_GROUP, "ignored_hiddevs = 0x%08x = %s", ignored_hiddevs, bs32_to_bitstring(ignored_hiddevs, buf, BIT_SET_32_MAX+1)); } /** Checks if a hiddev device is to ignored, using its /dev/usb/hiddev device number * * @param hiddev_number device number * @return true if device is to be ignored, false if not */ bool usb_is_ignored_hiddev(uint8_t hiddev_number) { bool debug = false; assert(hiddev_number < BIT_SET_32_MAX); bool result = bs32_contains(ignored_hiddevs, hiddev_number); DBGTRC_EXECUTED(debug, TRACE_GROUP, "hiddev_number=%d, returning %s", hiddev_number, sbool(result)); return result; } /** Specify /dev/usb/hiddev devices to be ignored, using vendor and product ids. * * @param ignored_ct number of devices to ignore * @param ignored array of vendor_id/product_id values * * Each value in **ignored** is specified as a combined 4 byte vendor_id/product_id value. */ void usb_ignore_vid_pid_values(uint8_t ignored_ct, Vid_Pid_Value* ignored) { bool debug = false; ignored_vid_pid_ct = ignored_ct; // explicitly handle ignored==NULL case to avoid coverity warning if (ignored_ct > 0) { ignored_vid_pids = calloc(ignored_ct, sizeof(uint32_t)); memcpy(ignored_vid_pids, ignored, ignored_ct*sizeof(uint32_t)); } if (debug || IS_TRACING()) { DBGMSG("ignored_vid_pid_ct = %d", ignored_vid_pid_ct); for (int ndx = 0; ndx < ignored_vid_pid_ct; ndx++) DBGMSG(" ignored_vid_pids[%d] = 0x%08x", ndx, ignored_vid_pids[ndx]); } } /** Checks if a hiddev device is to ignored, based on its vendor id and product id. * * @param vid 2 byte vendor id * @param pid 2 byte product id * @return true if device is to be ignored, false if not */ bool usb_is_ignored_vid_pid(uint16_t vid, uint16_t pid) { bool debug = false; Vid_Pid_Value v = VID_PID_VALUE(vid,pid); bool result = usb_is_ignored_vid_pid_value(v); DBGTRC_EXECUTED(debug, TRACE_GROUP, "vid=0x%04x, pid=0x%04x, returning: %s", vid, pid, result); return result; } /** Checks if a hiddev device is to ignored, based on its vendor id and product id. * * @param vidpid 4 byte combined vendor_id/product_id * @return true if device is to be ignored, false if not */ bool usb_is_ignored_vid_pid_value(Vid_Pid_Value vidpid) { bool debug = false; bool result = false; for (int ndx = 0; ndx < ignored_vid_pid_ct; ndx++) { if (vidpid == ignored_vid_pids[ndx]) { result = true; break; } } DBGTRC_EXECUTED(debug, TRACE_GROUP, "vidpid=0x%08x, returning: %s", vidpid, result); return result; } void init_usb_base() { RTTI_ADD_FUNC(usb_open_hiddev_device); RTTI_ADD_FUNC(usb_ignore_hiddevs); RTTI_ADD_FUNC(usb_is_ignored_hiddev); RTTI_ADD_FUNC(usb_ignore_vid_pid_values); RTTI_ADD_FUNC(usb_is_ignored_vid_pid); RTTI_ADD_FUNC(usb_is_ignored_vid_pid_value); } void terminate_usb_base() { free(ignored_vid_pids); } ddcutil-2.2.0/src/usb/usb_displays.c0000644000175000001440000007643014754153540013067 /** @file usb_displays.c */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include /** \endcond */ #include "util/device_id_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/udev_usb_util.h" #include "util/udev_util.h" #include "usb_util/hiddev_reports.h" #include "usb_util/hiddev_util.h" #include "usb_util/usb_hid_common.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/execution_stats.h" #include "base/linux_errno.h" #include "base/rtti.h" #include "usb/usb_base.h" #include "usb/usb_edid.h" #include "usb/usb_displays.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_USB; // may be unused if all diagnostics turned off // // n. #pragma GCC diagnostic ignored "-Wunused-variable" not working // void usb_core_unused_function_to_avoid_unused_variable_warning() { // printf("0x%02x\n",TRACE_GROUP); // } // // Forward declarations // static GPtrArray * get_usb_monitor_list(); // returns array of Usb_Monitor_Info // Global variables static GPtrArray * usb_monitors = NULL; // array of Usb_Monitor_Info static GPtrArray * usb_open_errors = NULL; #define HID_USAGE_PAGE_MASK 0xffff0000 #define HID_UP_MONITOR 0x00800000 #define HID_UP_MONITOR_ENUM 0x00810000 #define HID_UP_MONITOR_VESA 0x00820000 // In keeping with the style of Linux USB code, this module prefers // "struct xxx {}" to "typedef {} xxx" // // Data Structures // // Report and manage data structures for this module. // Some data structures are defined here, others in usb_core.h // /** Emits a debugging report of a #Usb_Monitor_Vcp_Rec struct describing * a single USB "report" * * @param vcprec pointer to struct * @param depth logical indentation depth */ static void dbgrpt_usb_monitor_vcp_rec(Usb_Monitor_Vcp_Rec * vcprec, int depth) { const int d1 = depth+1; rpt_structure_loc("Usb_Monitor_Vcp_Rec", vcprec, depth); rpt_vstring(d1, "%-20s: %-4.4s", "marker", vcprec->marker); rpt_vstring(d1, "%-20s: 0x%02x", "vcp_code", vcprec->vcp_code); rpt_vstring(d1, "%-20s: %d", "report_type", vcprec->report_type); rpt_vstring(d1, "%-20s: %d", "report_id", vcprec->report_id); rpt_vstring(d1, "%-20s: %d", "field_index", vcprec->field_index); rpt_vstring(d1, "%-20s: %d", "usage_index", vcprec->usage_index); // to be completed rpt_structure_loc("struct hiddev_report_info", vcprec->rinfo, d1); rpt_structure_loc("struct hiddev_field_info ", vcprec->finfo, d1); rpt_structure_loc("struct hiddev_usage_ref ", vcprec->uref, d1); } static void free_usb_monitor_vcp_rec(gpointer p) { struct usb_monitor_vcp_rec * vrec = p; bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_USB, "vrec = %p", vrec); if (vrec) { assert(memcmp(vrec->marker, USB_MONITOR_VCP_REC_MARKER, 4) == 0); free(vrec->rinfo); free(vrec->finfo); free(vrec->uref); vrec->marker[3] = 'x'; free(vrec); } DBGTRC_DONE(debug, DDCA_TRC_USB, ""); } /** Emits a debugging report of a #Usb_Monitor_Info struct * * @param moninfo pointer to instance * @param depth logical indentation depth */ void dbgrpt_usb_monitor_info(Usb_Monitor_Info * moninfo, int depth) { const int d1 = depth+1; const int d2 = depth+2; rpt_structure_loc("Usb_Monitor_Info", moninfo, d1); rpt_vstring(d1, "%-20s: %-4.4s", "marker", moninfo->marker); rpt_vstring(d1, "%-20s: %s", "hiddev_device_name", moninfo->hiddev_device_name); rpt_vstring(d1, "%-20s: %p", "edid", moninfo->edid); rpt_vstring(d1, "%-20s: %p", "hiddev_devinfo", moninfo->hiddev_devinfo); rpt_title("Non-empty vcp_codes entries:", d1); int feature_code; for (feature_code = 0; feature_code < 256; feature_code++) { GPtrArray * monrecs = moninfo->vcp_codes[feature_code]; if (monrecs) { rpt_vstring(d1, "vcp_codes[0x%02x]=%p is a GPtrArray with %d records:", feature_code, monrecs, monrecs->len); for (int ndx=0; ndxlen; ndx++) { dbgrpt_usb_monitor_vcp_rec( g_ptr_array_index(monrecs, ndx), d2); } } } } static void free_usb_monitor_info(gpointer p) { struct usb_monitor_info * moninfo = p; bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "moninfo = %p", moninfo); if (moninfo) { assert(memcmp(moninfo->marker, USB_MONITOR_INFO_MARKER, 4) == 0); if (debug) dbgrpt_usb_monitor_info(moninfo, 2); free(moninfo->hiddev_device_name); DBGMSF(debug, "Freeing moninfo->edid = %p", moninfo->edid); free_parsed_edid(moninfo->edid); free(moninfo->hiddev_devinfo); for (int ndx = 0; ndx < 256; ndx++) { if (moninfo->vcp_codes[ndx]) { g_ptr_array_set_free_func(moninfo->vcp_codes[ndx], free_usb_monitor_vcp_rec); g_ptr_array_free(moninfo->vcp_codes[ndx], true); } } moninfo->marker[3] = 'x'; free(moninfo); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } /** Reports on an array of #Usb_Monitor_info structs * * @param monitors pointer to GPtrArray of pointer to struct #Usb_Monitor_Info * @param depth logical indentation depth */ static void report_usb_monitors(GPtrArray * monitors, int depth) { const int d1 = depth+1; rpt_vstring(depth, "GPtrArray of %d Usb_Monitor_Info at %p", monitors->len, monitors); for (int ndx = 0; ndx < monitors->len; ndx++) { dbgrpt_usb_monitor_info( g_ptr_array_index(monitors, ndx), d1); } } // // HID Report Inquiry // Usb_Monitor_Vcp_Rec * create_usb_monitor_vcp_rec(Byte feature_code) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "feature_code=0x%02x", feature_code); Usb_Monitor_Vcp_Rec * vcprec = calloc(1, sizeof(Usb_Monitor_Vcp_Rec)); memcpy(vcprec->marker, USB_MONITOR_VCP_REC_MARKER, 4); vcprec->vcp_code = feature_code; DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", vcprec); return vcprec; } /** Locates all USB HID reports for a device that relate to querying and * setting VCP feature values. * * @param fd file descriptor of open HID device * @return array of #Usb_Monitor_Vcp_Rec for each usage */ static GPtrArray * collect_vcp_reports(int fd) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); GPtrArray * vcp_reports = g_ptr_array_new(); for (__u32 report_type = HID_REPORT_TYPE_MIN; report_type <= HID_REPORT_TYPE_MAX; report_type++) { int reportinfo_rc = 0; struct hiddev_report_info rinfo = { .report_type = report_type, .report_id = HID_REPORT_ID_FIRST }; while (reportinfo_rc >= 0) { // printf("(%s) Report counter %d, report_id = 0x%08x %s\n", // __func__, rptct, rinfo.report_id, interpret_report_id(rinfo.report_id)); errno = 0; reportinfo_rc = hiddev_get_report_info(fd, &rinfo, CALLOPT_ERR_MSG); //HIDIOCGDEVINFO // reportinfo_rc = ioctl(fd, HIDIOCGREPORTINFO, &rinfo); if (reportinfo_rc != 0) { // no more reports assert( reportinfo_rc == -1); break; } // result->report_id = rinfo.report_id; if (rinfo.num_fields == 0) break; int fndx, undx; for (fndx = 0; fndx < rinfo.num_fields; fndx++) { // printf("(%s) field index = %d\n", __func__, fndx); struct hiddev_field_info finfo = { .report_type = rinfo.report_type, .report_id = rinfo.report_id, .field_index = fndx }; Byte callopts = CALLOPT_ERR_MSG; if (debug) callopts |= CALLOPT_WARN_FINDEX; int rc = hiddev_get_field_info(fd, &finfo, callopts); if (rc < 0) continue; if (finfo.application != 0x00800001) // USB Monitor Page/Monitor Control continue; for (undx = 0; undx < finfo.maxusage; undx++) { struct hiddev_usage_ref uref = { .report_type = rinfo.report_type, // rinfo.report_type; .report_id = rinfo.report_id, // rinfo.report_id; .field_index = fndx, .usage_index = undx }; int rc = hiddev_get_usage_code(fd, &uref, CALLOPT_ERR_MSG); if (rc < 0) continue; if ( (uref.usage_code & 0xffff0000) != 0x00820000) // Monitor VESA Virtual Controls page continue; Byte vcp_feature = uref.usage_code & 0xff; Usb_Monitor_Vcp_Rec * vcprec = create_usb_monitor_vcp_rec(vcp_feature); vcprec->report_type = report_type; vcprec->report_id = rinfo.report_id; vcprec->field_index = fndx; vcprec->usage_index = undx; struct hiddev_report_info * infoptr = malloc(sizeof(struct hiddev_report_info)); memcpy(infoptr, &rinfo, sizeof(struct hiddev_report_info)); vcprec->rinfo = infoptr; struct hiddev_field_info * fptr = malloc(sizeof(struct hiddev_field_info)); memcpy(fptr, &finfo, sizeof(struct hiddev_field_info)); vcprec->finfo = fptr; struct hiddev_usage_ref * uptr = malloc(sizeof(struct hiddev_usage_ref)); memcpy(uptr, &uref, sizeof(struct hiddev_usage_ref)); vcprec->uref = uptr;; g_ptr_array_add(vcp_reports, vcprec); } // loop over usages } // loop over fields rinfo.report_id |= HID_REPORT_ID_NEXT; } } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %d VCP reports", vcp_reports->len); return vcp_reports; } // // Capabilities // /** Creates a capabilities string for the USB device. * * @param pointer to #Usb_Monitor_Info instance * @return synthesized capabilities string, containing only a vcp segment * * It is the responsibility of the caller to free the returned string * * @remark * Note that the USB HID Monitor spec does not define a capabilities report. */ static char * usb_synthesize_capabilities_string(Usb_Monitor_Info * moninfo) { assert(moninfo); char buf[1000]; strcpy(buf,"(vcp("); bool firstcode = true; int curlen = 5; for (int feature_code=0; feature_code < 256; feature_code++) { if (moninfo->vcp_codes[feature_code]) { if (firstcode) firstcode = false; else { strcpy(buf+curlen, " "); curlen++; } sprintf(buf+curlen, "%02x", feature_code); curlen += 2; } } strcpy(buf+curlen, "))"); char * result = g_strdup(buf); return result; } /** Checks the interfaces for a device to determine if it may * be a keyboard or mouse, in which case it should not be probed. * * @param interfaces interface ids, separated by ":" * @return true/false */ static bool avoid_device_by_usb_interfaces_property_string(const char * interfaces) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "interfaces = |%s|", interfaces); Null_Terminated_String_Array pieces = strsplit(interfaces, ":"); // if (debug) // ntsa_show(pieces); bool avoid = false; int ndx = 0; while (pieces[ndx]) { // Interface Class 03 Human Interface Device // Interface Subclass 01 Boot Interface Subclass // Interface Protocol 02 Mouse // Interface Protocol 01 Keyboard // // Q: is it even possible to have a interface protocol mouse when // sublass is not Boot Interface? We're extra careful if ( // streq( pieces[ndx], "030102" ) || // mouse // streq( pieces[ndx], "030101") || // keyboard (strncmp(pieces[ndx], "03", 2) != 0 ) || // not a HID device (why were re even called?) (strncmp(pieces[ndx], "0301", 4) == 0 ) || // any HID boot interface subclass device (strncmp(pieces[ndx]+4, "01", 2) == 0 ) || // any keyboard (strncmp(pieces[ndx]+4, "02", 2) == 0 ) // any mouse ) { avoid = true; DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Avoiding device with interface %s", pieces[ndx]); break; } ndx++; } ntsa_free(pieces, true); DBGTRC_RET_BOOL(debug, TRACE_GROUP, avoid, ""); return avoid; } /** * Verifies that the device class of the Monitor is 3 (HID Device) and * that the subclass and interface do not indicate a mouse or keyboard. * * @param hiddev device name * @return true/false */ bool is_possible_monitor_by_hiddev_name(const char * hiddev_name) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "hiddev_name = %s", hiddev_name); Usb_Detailed_Device_Summary * devsum = NULL; bool avoid = false; DBGTRC(debug, TRACE_GROUP, "Before lookup call"); devsum = lookup_udev_usb_device_by_devname(hiddev_name, /* verbose = */ false); if (devsum) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "detailed_device_summary: "); if (debug || IS_TRACING()) { report_usb_detailed_device_summary(devsum, 2); } char * interfaces = devsum->prop_usb_interfaces; avoid = avoid_device_by_usb_interfaces_property_string(interfaces); free_usb_detailed_device_summary(devsum); } else { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Lookup failed"); avoid = true; } // can only pass a variable, not an expression, to DBGTRC_RET_BOOL() // because failure simulation may assign a new value to the variable bool result = !avoid; DBGTRC_RET_BOOL(debug, TRACE_GROUP, result, ""); return result; } Usb_Monitor_Info * create_usb_monitor_info(const char * hiddev_name) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "hiddev_name |%s|", hiddev_name); Usb_Monitor_Info * moninfo = calloc(1,sizeof(Usb_Monitor_Info)); memcpy(moninfo->marker, USB_MONITOR_INFO_MARKER, 4); moninfo->hiddev_device_name = g_strdup(hiddev_name); #ifdef ALT_LOCK_REC moninfo->lock_rec = create_display_lock_record(usb_io_path(hiddev_name_to_number(hiddev_name))); #endif DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", moninfo); return moninfo; } static void destroy_bus_open_error(gpointer p) { Bus_Open_Error * boe = p; free(boe->detail); free(boe); } // // Probe HID devices, create USB_Mon_Info data structures // /** Examines all hiddev devices to see if they are USB HID compliant monitors. * If so, obtains the EDID, determines which reports to use for VCP feature * values, etc. * * @return: array of pointers to USB_Mon_Info records * * As a side effect, collects a GPtrArray of errors in global variable * usb_open_errors. * * The result is cached in global variables usb_monitors and usb_open_errors. */ GPtrArray * get_usb_monitor_list() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); if (usb_monitors) // already initialized? { DBGTRC_DONE(debug, TRACE_GROUP, "Returning previously calculated monitor list"); return usb_monitors; } usb_monitors = g_ptr_array_new(); usb_open_errors = g_ptr_array_new_with_free_func(destroy_bus_open_error); GPtrArray * hiddev_names = get_hiddev_device_names(); for (int devname_ndx = 0; devname_ndx < hiddev_names->len; devname_ndx++) { char * hiddev_fn = g_ptr_array_index(hiddev_names, devname_ndx); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Examining device: %s", hiddev_fn); if (usb_is_ignored_hiddev(hiddev_name_to_number(hiddev_fn))) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Explicitly ignored: %s", hiddev_fn); continue; } // Ensures we don't touch a keyboard, mouse or some non-HID device. // Probing a keyboard or mouse can hang the system. if (!is_possible_monitor_by_hiddev_name(hiddev_fn)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Not a possible monitor: %s", hiddev_fn); continue; } bool deny_checked = false; char * detail = NULL; Bus_Open_Error * boe = NULL; Usb_Detailed_Device_Summary * devsum = lookup_udev_usb_device_by_devname(hiddev_fn, /* verbose = */ false); if (devsum) { // report_usb_detailed_device_summary(devsum, 4); detail = g_strdup_printf(" USB bus %s, device %s, vid:pid: %s:%s - %s:%s", devsum->busnum_s, devsum->devnum_s, devsum->vendor_id, devsum->product_id, devsum->vendor_name, devsum->product_name); bool denied = deny_hid_monitor_by_vid_pid(devsum->vid, devsum->pid); denied |= usb_is_ignored_vid_pid(devsum->vid, devsum->pid); deny_checked = true; if (denied) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Denied monitor %s:%s", devsum->vendor_id, devsum->product_id); } free_usb_detailed_device_summary(devsum); if (denied) continue; } DBGTRC_NOPREFIX(debug, TRACE_GROUP, "detail = |%s|", detail); int fd = usb_open_hiddev_device(hiddev_fn, CALLOPT_RDONLY); if (fd < 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Open failed"); f0printf(ferr(), "Open failed for %s: errno=%s %s\n", hiddev_fn, linux_errno_desc(-fd), (detail) ? detail : ""); boe = calloc(1, sizeof(Bus_Open_Error)); boe->io_mode = DDCA_IO_USB; boe->devno = hiddev_name_to_number(hiddev_fn); // is this simple or fully qualified? boe->error = fd; boe->detail = detail; g_ptr_array_add(usb_open_errors, boe); } else { // fd == 0 should never occur assert(fd != 0); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "open succeeded"); free(detail); // Declare variables here and initialize them to NULL so that code at label close: works struct hiddev_devinfo * devinfo = NULL; char * cgname = NULL; Parsed_Edid * parsed_edid = NULL; GPtrArray * vcp_reports = NULL; Usb_Monitor_Info * moninfo = NULL; cgname = get_hiddev_name(fd); // HIDIOCGNAME devinfo = calloc(1,sizeof(struct hiddev_devinfo)); Status_Errno rc2 = hiddev_get_device_info(fd, devinfo, CALLOPT_ERR_MSG); // HIDIOCGDEVINFO if (rc2 != 0) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "hiddev_get_device_info() failed. rc=%d", rc2); goto close; } if (!deny_checked) { bool deny = deny_hid_monitor_by_vid_pid(devinfo->vendor, devinfo->product); deny |= usb_is_ignored_vid_pid(devinfo->vendor, devinfo->product); if (deny) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Denied monitor 0x%04x:0x%04x", devinfo->vendor, devinfo->product); goto close; } } // DBGMSF(debug, "Calling is_hiddev_monitor()..."); bool is_hid_monitor = is_hiddev_monitor(fd); // HIDIOCGCOLLECTIONINFO DBGTRC_NOPREFIX(debug, TRACE_GROUP, "is_hiddev_monitor() returned %s", sbool(is_hid_monitor)); if (!is_hid_monitor) goto close; // Solves problem of ddc detect not getting edid unless ddcutil env called first DBGMSF(debug, "calling ioctl(,HIDIOCINITREPORT)..."); int rc = ioctl(fd, HIDIOCINITREPORT); DBGMSF(debug, "ioctl() returned %d", rc); if (rc < 0) { int errsv = errno; // call should never fail. always write an error message REPORT_IOCTL_ERROR("HIDIOCINITGREPORT", errsv); goto close; } parsed_edid = get_hiddev_edid_with_fallback(fd, devinfo); if (!parsed_edid) { f0printf(ferr(), "Monitor on device %s reports no EDID or has invalid EDID. Ignoring.\n", hiddev_fn); goto close; } DBGTRC(debug, TRACE_GROUP, "Collecting USB reports..."); vcp_reports = collect_vcp_reports(fd); // HIDIOCGDEVINFO moninfo = create_usb_monitor_info(hiddev_fn); moninfo->edid = parsed_edid; moninfo->hiddev_devinfo = devinfo; devinfo = NULL; // so that struct not freed // Distribute the accumulated vcp reports by feature code for (int ndx = 0; ndx < vcp_reports->len; ndx++) { Usb_Monitor_Vcp_Rec * cur_vcp_rec = g_ptr_array_index(vcp_reports, ndx); Byte curvcp = cur_vcp_rec->vcp_code; GPtrArray * cur_code_table_entry = moninfo->vcp_codes[curvcp]; if (!cur_code_table_entry) { cur_code_table_entry = g_ptr_array_new(); moninfo->vcp_codes[curvcp] = cur_code_table_entry; } g_ptr_array_add(cur_code_table_entry, cur_vcp_rec); } // free vcp_reports without freeing the entries, which are now pointed to // by moninfo->vcp_codes // n. no free function set g_ptr_array_free(vcp_reports, true); g_ptr_array_add(usb_monitors, moninfo); if (debug) { DBGMSG("Added monitor:"); dbgrpt_usb_monitor_info(moninfo, 3); } close: if (devinfo) free(devinfo); if (cgname) free(cgname); // TODO, free device summary usb_close_device(fd, hiddev_fn, CALLOPT_NONE); // return error if failure DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Closed"); } // monitor opened } // loop over device names g_ptr_array_set_free_func(hiddev_names, g_free); g_ptr_array_free(hiddev_names, true); // if ( debug || IS_TRACING() ) { // DBGTRC_DONE(debug, TRACE_GROUP, "Returning %d monitors ", usb_monitors->len); // report_usb_monitors(usb_monitors,1); // } DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "usb_monitors",report_usb_monitors, usb_monitors); return usb_monitors; } GPtrArray * get_usb_open_errors() { return usb_open_errors; } void discard_usb_monitor_list() { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "usb_monitors=%p, usb_open_errors=%p", usb_monitors, usb_open_errors); if (usb_monitors) { g_ptr_array_set_free_func(usb_monitors, free_usb_monitor_info); DBGMSF(debug, "Freeing usb_monitors = %p", usb_monitors); g_ptr_array_free(usb_monitors, true); usb_monitors = NULL; DBGMSF(debug, "Freeing usb_open_errors = %p", usb_open_errors); g_ptr_array_free(usb_open_errors, true); usb_open_errors = NULL; } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Functions to find Usb_Monitor_Info for a display // static Usb_Monitor_Info * usb_find_monitor_by_busnum_devnum(int busnum, int devnum) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busnum=%d, devnum=%d", busnum, devnum); assert(usb_monitors); Usb_Monitor_Info * result = NULL; for (int ndx = 0; ndx < usb_monitors->len; ndx++) { struct usb_monitor_info * curmon = g_ptr_array_index(usb_monitors, ndx); struct hiddev_devinfo * devinfo = curmon->hiddev_devinfo; if (busnum == devinfo->busnum && devnum == devinfo->devnum) { result = curmon; break; } } DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", result); return result; } static Usb_Monitor_Info * usb_find_monitor_by_dref(Display_Ref * dref) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dref = %s", dref_repr_t(dref)); assert(dref->io_path.io_mode == DDCA_IO_USB); Usb_Monitor_Info * result = usb_find_monitor_by_busnum_devnum(dref->usb_bus, dref->usb_device); DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", result); return result; } /** Gets the #Usb_Monitor_Info struct for a display * * @param dh display handle * @return pointer to #Usb_Monitor_Info struct, NULL if not found */ Usb_Monitor_Info * usb_find_monitor_by_dh(Display_Handle * dh) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "dh = %s", dh_repr(dh)); assert(dh && dh->dref); assert(dh->dref->io_path.io_mode == DDCA_IO_USB); Usb_Monitor_Info * result = usb_find_monitor_by_busnum_devnum(dh->dref->usb_bus, dh->dref->usb_device); DBGTRC_DONE(debug, TRACE_GROUP, "Returning %p", result); return result; } #ifdef APPARENTLY_UNUSED char * get_hiddev_devname_by_dref(Display_Ref * dref) { Usb_Monitor_Info * moninfo = usb_find_monitor_by_dref(dref); char * result = moninfo->hiddev_device_name; DBGMSG("dref=%s, returning: %s", dref_short_name(dref), result); return result; } #endif // // Display_Info_list Functions // #ifdef UNUSED /* Returns a list of all valid USB HID compliant monitors, * in a form expected by higher levels of ddcutil, namely * a collection of Display_Refs * * Arguments: none * * Returns: Display_Info_List of Display_Refs */ Display_Info_List usb_get_valid_displays() { // static GPtrArray * usb_monitors; // array of Usb_Monitor_Info bool debug = false; GPtrArray * all_usb_monitors = get_usb_monitor_list(); Display_Info_List info_list = {0,NULL}; Display_Info info_recs[256]; // coverity flags uninitialized scalar DBGMSF(debug, "Found %d USB displays", __func__, usb_monitors->len); info_list.info_recs = calloc(usb_monitors->len,sizeof(Display_Info)); for (int ndx=0; ndxlen; ndx++) { Usb_Monitor_Info * curmon = g_ptr_array_index(usb_monitors,ndx); Display_Ref * dref = create_usb_display_ref( curmon->hiddev_devinfo->busnum, curmon->hiddev_devinfo->devnum, curmon->hiddev_device_name); info_recs[ndx].dispno = -1; // not yet set info_recs[ndx].dref = dref; info_recs[ndx].edid = curmon->edid; memcpy(info_recs[ndx].marker, DISPLAY_INFO_MARKER, 4); } memcpy(info_list.info_recs, info_recs, (usb_monitors->len)*sizeof(Display_Info)); info_list.ct = usb_monitors->len; if (debug) { DBGMSG("Done. Returning:"); report_display_info_list(&info_list, 1); } return info_list; } #endif // *** Functions to return a Display_Ref for a USB monitor *** #ifdef UNUSED bool usb_is_valid_display_ref(Display_Ref * dref, bool emit_error_msg) { bool result = true; if (!usb_find_monitor_by_dref(dref)) { result = false; if (emit_error_msg) fprintf(stderr, "Invalid Display_Ref\n"); } return result; } #endif /** Output of DETECT command for a USB connected monitor. * * @param dref display reference * @param depth logical indentation depth */ void usb_show_active_display_by_dref(Display_Ref * dref, int depth) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "dref = %s", dref_repr_t(dref) ); DDCA_Output_Level output_level = get_output_level(); rpt_vstring(depth, "USB bus:device: %d:%d", dref->usb_bus, dref->usb_device); Usb_Monitor_Info * moninfo = usb_find_monitor_by_dref(dref); if (output_level == DDCA_OL_TERSE) { rpt_vstring(depth, "Monitor: %s:%s:%s", moninfo->edid->mfg_id, moninfo->edid->model_name, moninfo->edid->serial_ascii); } else { assert(output_level >= DDCA_OL_NORMAL); Pci_Usb_Id_Names usb_names = devid_get_usb_names(moninfo->hiddev_devinfo->vendor, moninfo->hiddev_devinfo->product, 0, 2); char vname[80] = {'\0'}; char dname[80] = {'\0'}; if (usb_names.vendor_name) snprintf(vname, 80, "(%s)", usb_names.vendor_name); if (usb_names.device_name) snprintf(dname, 80, "(%s)", usb_names.device_name); rpt_vstring(depth, "Device name: %s", dref->usb_hiddev_name); rpt_vstring(depth, "Vendor id: %04x %s", moninfo->hiddev_devinfo->vendor & 0xffff, vname); rpt_vstring(depth, "Product id: %04x %s", moninfo->hiddev_devinfo->product & 0xffff, dname); bool dump_edid = (output_level >= DDCA_OL_VERBOSE); report_parsed_edid(moninfo->edid, dump_edid /* verbose */, depth); } DBGTRC_DONE(debug, TRACE_GROUP, ""); } // // Get monitor information by Display_Ref or Display_Handle // (for hiding Usb_Monitor_Info from higher software levels) // Parsed_Edid * usb_get_parsed_edid_by_dref(Display_Ref * dref) { Usb_Monitor_Info * moninfo = usb_find_monitor_by_dref(dref); return moninfo->edid; } Parsed_Edid * usb_get_parsed_edid_by_dh(Display_Handle * dh) { Usb_Monitor_Info * moninfo = usb_find_monitor_by_dh(dh); return moninfo->edid; } char * usb_get_capabilities_string_by_dh(Display_Handle * dh) { Usb_Monitor_Info * moninfo = usb_find_monitor_by_dh(dh); assert(dh); return usb_synthesize_capabilities_string(moninfo); } // // *** Miscellaneous services *** // /** Tests if a hiddev device (specified by its name) appears to * be a USB HID compliant monitor. * * This stripped down test implements the ddcutil chkusbmon command, * which is intended for use in a udev rules test. * * @param device_name e.g. /dev/usb/hiddev3 * @retval true device is a monitor, * @retval false device is not a monitor, or unable to open device * * @remark * Note that messages will not appear when this function runs as part * of normal udev execution. They are intended to aid in debugging. */ bool check_usb_monitor( char * device_name ) { assert(device_name); bool debug = false; DDCA_Output_Level ol = get_output_level(); if (debug) ol = DDCA_OL_VERBOSE; DBGMSF(debug, "Examining device: %s", device_name); bool result = false; #ifdef OLD if (is_possible_monitor_by_hiddev_name(device_name)) { // only check if a HID device that isn't a mouse or keyboard int fd = open(device_name, O_RDONLY); if (fd < 1) { if (ol >= DDCA_OL_VERBOSE) printf("Unable to open device %s: %s\n", device_name, strerror(errno)); } else { result = is_hiddev_monitor(fd); } close(fd); } #endif result = is_possible_monitor_by_hiddev_name(device_name); if (ol >= DDCA_OL_VERBOSE) { if (result) printf("Device %s may be a USB HID compliant monitor.\n", device_name); else printf("Device %s is not a USB HID compliant monitor.\n", device_name); } return result; } void init_usb_displays() { RTTI_ADD_FUNC(avoid_device_by_usb_interfaces_property_string); RTTI_ADD_FUNC(collect_vcp_reports); RTTI_ADD_FUNC(create_usb_monitor_info); RTTI_ADD_FUNC(create_usb_monitor_vcp_rec); RTTI_ADD_FUNC(discard_usb_monitor_list); RTTI_ADD_FUNC(free_usb_monitor_info); RTTI_ADD_FUNC(free_usb_monitor_vcp_rec); RTTI_ADD_FUNC(get_usb_monitor_list); RTTI_ADD_FUNC(is_possible_monitor_by_hiddev_name); RTTI_ADD_FUNC(usb_find_monitor_by_busnum_devnum); RTTI_ADD_FUNC(usb_find_monitor_by_dh); RTTI_ADD_FUNC(usb_find_monitor_by_dref); RTTI_ADD_FUNC(usb_show_active_display_by_dref); } void terminate_usb_displays() { // discard_usb_monitor_list(); // unnecessary, already called } ddcutil-2.2.0/src/usb/usb_edid.c0000644000175000001440000003113014754153540012130 /** @file usb_edid.c * * Functions to get EDID for USB connected monitors */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "util/device_id_util.h" #include "util/report_util.h" #include "util/string_util.h" #ifdef USE_X11 #include "util/x11_util.h" // for EDID fallback #endif #include "public/ddcutil_types.h" #include "usb_util/hiddev_reports.h" #include "usb_util/hiddev_util.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/execution_stats.h" #include "base/linux_errno.h" #include "base/rtti.h" #include "i2c/i2c_bus_core.h" // for EDID fallback #include "i2c/i2c_bus_selector.h" // for EDID fallback #include "usb/usb_base.h" #include "usb/usb_edid.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_USB; // void usb_edid_unused_function_to_avoid_unused_variable_warning() { // printf("0x%02x\n",TRACE_GROUP); // } // struct model_sn_pair struct model_sn_pair { char * model; char * sn; }; void free_model_sn_pair(struct model_sn_pair * p) { if (p) { free(p->model); free(p->sn); free(p); } } void report_model_sn_pair(struct model_sn_pair * p, int depth) { int d1 = depth+1; rpt_structure_loc("struct model_sn_pair",p, depth); rpt_vstring(d1, "model: %s", p->model); rpt_vstring(d1, "sn: %s", p->sn); } // // EIZO Specific Functions // /* Locates the EIZO specific HID report that returns the model and serial number. * * Arguments: * fd file descriptor for open USB HID device * * Returns: pointer to a newly allocated struct hid_field_locator */ struct hid_field_locator * find_eizo_model_sn_report(int fd) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); struct hid_field_locator * loc = NULL; struct hiddev_devinfo dev_info; int rc = hiddev_get_device_info(fd, &dev_info, CALLOPT_ERR_MSG); if (rc != 0) goto bye; if (dev_info.vendor == 0x056d && dev_info.product == 0x0002) { loc = hiddev_find_report(fd, HID_REPORT_TYPE_FEATURE, 0xff000035, /*match_all_ucodes=*/false); } bye: DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", (void*)loc); // if (loc ) { // report_hid_field_locator(loc,2); // } return loc; } #ifdef UNUSED bool is_eizo_monitor(int fd) { bool debug = false; bool result = false; struct hiddev_devinfo dev_info; int rc = ioctl(fd, HIDIOCGDEVINFO, &dev_info); if (rc != 0) { REPORT_IOCTL_ERROR("HIDIOCGDEVINFO", rc); goto bye; } if (dev_info.vendor == 0x056d && dev_info.product == 0x0002) result = true; bye: DBGMSF(debug, "Returning %s", bool_repr(result)); return result; } #endif /* Gets the model and serial number of an Eizo monitor using an Eizo specific report. * * Finds the specific report, then reads it. * * Alternatively: * Obtains the values by requesting the value of the usage code for the strings, * leaving it to hiddev to find the required report. * * Arguments: * fd file descriptor of open USB HID device for an Eizo monitor * * Returns: model and serial number strings */ struct model_sn_pair * get_eizo_model_sn_by_report(int fd) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); struct model_sn_pair* result = NULL; Buffer * modelsn = NULL; Buffer * modelsn2 = NULL; struct hid_field_locator * loc = find_eizo_model_sn_report(fd); // DBGMSF(debug, "find_eizo_model_sn_report() returned: %p", loc); if (loc) modelsn = hiddev_get_multibyte_report_value_by_hid_field_locator(fd, loc); modelsn2 = hiddev_get_multibyte_value_by_ucode( fd, 0xff000035, // usage code 16); // num_values if (modelsn2 && modelsn2->len >= 16) buffer_set_length(modelsn2, 16); // printf("modelsn:\n"); // buffer_dump(modelsn); // printf("modelsn2:\n"); // buffer_dump(modelsn2); assert(buffer_eq(modelsn, modelsn2)); if (modelsn2) buffer_free(modelsn2, __func__); if (modelsn) { assert(modelsn->len >= 16); result = calloc(1, sizeof(struct model_sn_pair)); result->model = calloc(1,9); result->sn = calloc(1,9); memcpy(result->sn, modelsn->bytes,8); result->sn[8] = '\0'; memcpy(result->model, modelsn->bytes+8, 8); result->model[8] = '\0'; rtrim_in_place(result->sn); rtrim_in_place(result->model); free(modelsn); } if (loc) free_hid_field_locator(loc); if (result) { DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p -> model=|%s|, sn=|%s|", (void*) result, result->model, result->sn); // if (debug || IS_TRACING()) // report_model_sn_pair(result, 1); } else { DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", (void*) result); } return result; } // // EDID Retrieval // #ifdef USE_X11 /* Obtains EDID from X11. * * Arguments: * model_name * sn_ascii * * Returns: parsed EDID if found */ Parsed_Edid * get_x11_edid_by_model_sn(char * model_name, char * sn_ascii) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "model_name=|%s|, sn_ascii=|%s|", model_name, sn_ascii); Parsed_Edid * parsed_edid = NULL; GPtrArray* edid_recs = get_x11_edids(/*use_screen_resources_current=*/ true); // puts(""); // printf("EDIDs reported by X11 for connected xrandr outputs:\n"); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Got %d X11_Edid_Recs", edid_recs->len); for (int ndx=0; ndx < edid_recs->len; ndx++) { X11_Edid_Rec * prec = g_ptr_array_index(edid_recs, ndx); // printf(" Output name: %s -> %p\n", prec->output_name, prec->edid); // hex_dump(prec->edid, 128); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Comparing EDID for xrandr output: %s", prec->output_name); parsed_edid = create_parsed_edid2(prec->edidbytes, "X11"); if (parsed_edid) { if (debug) { bool verbose_edid = false; report_parsed_edid(parsed_edid, verbose_edid, 2 /* depth */); } if (streq(parsed_edid->model_name, model_name) && streq(parsed_edid->serial_ascii, sn_ascii) ) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Found matching EDID from X11"); break; } free_parsed_edid(parsed_edid); } else { if (debug || IS_TRACING() || get_output_level() >= DDCA_OL_VERBOSE) { DBGMSG("Unparsable EDID for output name: %s -> %p", prec->output_name, prec->edidbytes); rpt_hex_dump(prec->edidbytes, 128, /*depth=*/ 1); } } } #ifdef MOCK_DATA_FOR_DEVELOPMENT if (!parsed_edid && edid_recs->len > 0) { printf("(%s) HACK FOR TESTING: Using last X11 EDID\n", __func__); X11_Edid_Rec * prec = g_ptr_array_index(edid_recs, edid_recs->len-1); parsed_edid = create_parsed_edid(prec->edidbytes); } #endif g_ptr_array_free(edid_recs, true); DBGTRC_DONE(debug, TRACE_GROUP, "returning %p", parsed_edid); return parsed_edid; } #endif Parsed_Edid * get_fallback_hiddev_edid(int fd, struct hiddev_devinfo * dev_info) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busnum=%d, devnum=%d, vendor=-x%08x, product=0x%08x", dev_info->busnum, dev_info->devnum, dev_info->vendor, dev_info->product); Parsed_Edid * parsed_edid = NULL; char * edid_source; struct model_sn_pair * model_sn = NULL; // Special handling for Eizo monitors // if (dev_info->vendor == 0x056d && dev_info->product == 0x0002) { // if is EIZO monitor? if (dev_info->vendor == 0x056d) { // if is EIZO monitor? DBGMSG("*** Special fixup for Eizo monitor ***"); model_sn = get_eizo_model_sn_by_report(fd); if (model_sn) { // Should there be a ddc level function to find non-usb EDID? I2C_Bus_Info * bus_info = i2c_find_bus_info_by_mfg_model_sn( NULL, // mfg_id model_sn->model, model_sn->sn, DISPSEL_NONE); if (bus_info) { DBGMSG("Using EDID for /dev/i2c-%d", bus_info->busno); parsed_edid = bus_info->edid; edid_source = "I2C"; // STRLCPY(parsed_edid->edid_source, "I2C", EDID_SOURCE_FIELD_SIZE); // result = NULL; // for testing - both i2c and X11 methods work } else { // ADL #ifdef OLD Display_Ref * dref = adlshim_find_display_by_mfg_model_sn( NULL, // mfg_id model_sn->model, model_sn->sn); parsed_edid = adlshim_get_parsed_edid_by_dref(dref); DDCA_Adlno adlno = adlshim_find_adlno_by_mfg_model_sn( NULL, // mfg_id model_sn->model, model_sn->sn); if (adlno.iAdapterIndex >= 0) { // {-1,-1} means unset parsed_edid = adlshim_get_parsed_edid_by_adlno(adlno.iAdapterIndex, adlno.iDisplayIndex); edid_source = "ADL"; // STRLCPY(parsed_edid->edid_source, "ADL", EDID_SOURCE_FIELD_SIZE); } // memory leak: not freeing dref because don't want to clobber parsed_edid // need to review Display_Ref lifecycle #endif PROGRAM_LOGIC_ERROR("ADL implementation removed"); } } } #ifdef USE_X11 if (!parsed_edid && model_sn) { parsed_edid = get_x11_edid_by_model_sn(model_sn->model, model_sn->sn); edid_source = "X11"; } #endif if (model_sn) free_model_sn_pair(model_sn); if (parsed_edid) STRLCPY(parsed_edid->edid_source, edid_source, EDID_SOURCE_FIELD_SIZE); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", parsed_edid); return parsed_edid; } /* Retrieves the EDID (128 bytes) from a hiddev device representing a HID * compliant monitor. * * Arguments: * fd file descriptor * * Returns: * pointer to Buffer struct containing the EDID * * It is the responsibility of the caller to free the returned buffer. */ Parsed_Edid * get_hiddev_edid_with_fallback(int fd, struct hiddev_devinfo * dev_info) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "busnum=%d, devnum=%d, vendor=-x%08x, product=0x%08x", dev_info->busnum, dev_info->devnum, dev_info->vendor, dev_info->product); if (debug || IS_TRACING()) dbgrpt_hiddev_devinfo(dev_info, true, 1); Parsed_Edid * parsed_edid = NULL; Buffer * edid_buffer = hiddev_get_edid(fd); // in hiddev_util.c DBGTRC_NOPREFIX(debug, TRACE_GROUP, "hiddev_get_edid() returned %p", edid_buffer); // try alternative - both work, pick one Buffer * edid_buf2 = hiddev_get_multibyte_value_by_ucode(fd, 0x00800002, 128); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "hiddev_get_multibyte_value_by_ucode() returned %p", edid_buf2); if (edid_buffer && edid_buffer->len > 128) buffer_set_length(edid_buffer,128); // printf("edid_buffer:\n"); // buffer_dump(edid_buffer); // printf("edid_buf2:\n"); // buffer_dump(edid_buf2); assert(buffer_eq(edid_buffer, edid_buf2)); if (edid_buf2) buffer_free(edid_buf2, __func__); if (edid_buffer) { if (debug || IS_TRACING()) rpt_hex_dump(edid_buffer->bytes, edid_buffer->len, 2); } if (edid_buffer) { parsed_edid = create_parsed_edid2(edid_buffer->bytes, "USB"); // copies bytes if (!parsed_edid) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "get_hiddev_edid() returned invalid EDID"); // if debug or verbose, dump the bad edid ?? // rpt_hex_dump(edid_buffer->bytes, edid_buffer->len, 2); } buffer_free(edid_buffer, __func__); edid_buffer = NULL; } if (!parsed_edid) parsed_edid = get_fallback_hiddev_edid(fd, dev_info); DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %p", parsed_edid); return parsed_edid; } void init_usb_edid() { RTTI_ADD_FUNC(find_eizo_model_sn_report); RTTI_ADD_FUNC(get_eizo_model_sn_by_report); #ifdef USE_X11 RTTI_ADD_FUNC(get_x11_edid_by_model_sn); #endif RTTI_ADD_FUNC(get_fallback_hiddev_edid); RTTI_ADD_FUNC(get_hiddev_edid_with_fallback); } ddcutil-2.2.0/src/usb/usb_services.c0000644000175000001440000000073714572333721013056 /** @file usb_services.c */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "usb_base.h" #include "usb_displays.h" #include "usb_edid.h" #include "usb_services.h" void init_usb_services() { init_usb_base(); init_usb_displays(); init_usb_edid(); } void terminate_usb_services() { // terminate_usb_displays(); // already called from termindate_ddc_services terminate_usb_base(); } ddcutil-2.2.0/src/usb/usb_vcp.c0000644000175000001440000005416714441414365012030 /* \file usb_vcp.c * * Get and set VCP feature codes for USB connected monitors. */ // Copyright (C) 2016-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include /** \endcond */ #include "util/report_util.h" #include "util/string_util.h" #include "usb_util/hiddev_reports.h" #include "usb_util/hiddev_util.h" #include "base/core.h" #include "base/ddc_errno.h" #include "base/execution_stats.h" #include "base/linux_errno.h" #include "usb/usb_displays.h" #include "usb/usb_vcp.h" // Trace class for this file static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_USB; // // Get and set HID usage values, parameterized only by HID data structures // /* Gets the value of usage by specifying the usage code * * Arguments: * fd file descriptor for open hiddev device * report_type HID_REPORT_TYPE_FEATURE or HID_REPORT_TYPE_OUTPUT * usage_code usage code to get * maxval where to return maximum values * curval where to return current value * * Returns: status code */ Public_Status_Code usb_get_usage_value_by_report_type_and_ucode( int fd, __u32 report_type, __u32 usage_code, __s32 * maxval, __s32 * curval) { bool debug = false; DBGMSF(debug, "Starting. fd=%d, report_type=%d, usage_code=0x%08x", fd, report_type, usage_code); Public_Status_Code psc = 0; Status_Errno rc; *curval = 0; // so there's a definite value in case of failure ... *maxval = 0; // avoids complaints by clang analyzer assert(report_type == HID_REPORT_TYPE_FEATURE || report_type == HID_REPORT_TYPE_INPUT); // *** CG19 *** struct hiddev_usage_ref uref = {0}; uref.report_type = report_type; uref.report_id = HID_REPORT_ID_UNKNOWN; uref.usage_code = usage_code; rc = hiddev_get_usage_value(fd, &uref, CALLOPT_NONE); // rc = ioctl(fd, HIDIOCGUSAGE, &uref); // Fills in usage value if (rc != 0) { // Problem: errno=22 (invalid argument) can mean the usage code is invalid, // i.e. invalid feature code, or another arg error which indicates a programming error // occasionally errno = 22 invalid argument - for Battery System Page: Run Time to Empty if (rc == -EINVAL) { if (debug) REPORT_IOCTL_ERROR("HIDIOCGUSAGE", -rc); psc = DDCRC_DETERMINED_UNSUPPORTED; } else { REPORT_IOCTL_ERROR("HIDIOCGUSAGE", -rc); // occasionally see -1, errno = 22 invalid argument - for Battery System Page: Run Time to Empty psc = rc; } if (debug) { DBGMSG("After hid_get_usage_value():"); dbgrpt_hiddev_usage_ref(&uref, 1); } goto bye; } *curval = uref.value; if (debug) dbgrpt_hiddev_usage_ref(&uref, 1); struct hiddev_field_info finfo = {0}; finfo.report_type = uref.report_type; finfo.report_id = uref.report_id; finfo.field_index = uref.field_index; // ? if (ioctl(fd, HIDIOCGFIELDINFO, &finfo) < 0) { // Fills in usage value int errsv = errno; REPORT_IOCTL_ERROR("HIDIOCGFIELDINFO", errsv); // occasionally see -1, errno = 22 invalid argument - for Battery System Page: Run Time to Empty psc = -errsv; goto bye; } if (debug) dbgrpt_hiddev_field_info(&finfo, 1); // per spec, logical max/min bound the values in the report, // physical min/max bound the "real world" units // if physical min/max = 0, set physical to logical // So we should use logical max as ddc maxval. // But logical_minimum can be < 0 per USB spec, // in which case the value in the report is interpreted as a // 2's complement number. How to handle this? // Map to a range >= 0? e.g. -128..127 -> 0..255 __s32 maxval1 = finfo.logical_maximum; __s32 maxval2 = finfo.physical_maximum; DBGMSF(debug, "logical_maximum: %d", maxval1); DBGMSF(debug, "physical_maximum: %d", maxval2); *maxval = finfo.logical_maximum; if (finfo.logical_minimum < 0) { DBGMSG("Unexpected: logical_minimum (%d) for field is < 0", finfo.logical_minimum); } psc = 0; bye: DBGMSF(debug, "Returning: %s", psc_desc(psc)); return psc; } /* Sets the value of usage, with explicit report field, and usage indexes * * Arguments: * fd file descriptor for open hiddev device * report_type HID_REPORT_TYPE_FEATURE or HID_REPORT_TYPE_OUTPUT * report_id report number * field_idx field number * usage_idx usage number * value value to set * * Returns: status code * * Adapted from usbmonctl */ Status_Errno set_control_value(int fd, int report_type, int report_id, int field_ndx, int usage_ndx, int value) { bool debug = false; DBGMSF(debug, "Starting. fd=%d, report_type=%d, report_id=%d, field_ndx=%d, usage_ndx=%d, value=%d", fd, report_type, report_type, field_ndx, usage_ndx, value); Status_Errno result = 0; struct hiddev_report_info rinfo = { .report_type = report_type, .report_id = report_id, }; struct hiddev_usage_ref uref = { .report_type = report_type, .report_id = report_id, .field_index = field_ndx, .usage_index = usage_ndx, .value = value, }; if (debug) { DBGMSG("Before HIDIOCSUSAGE"); dbgrpt_hiddev_usage_ref(&uref, 1); } if (ioctl(fd, HIDIOCSUSAGE, &uref) < 0) { result = -errno; REPORT_IOCTL_ERROR("HIDIOCSUSAGE", errno); goto bye; } if (ioctl(fd, HIDIOCSREPORT, &rinfo) < 0) { result = -errno; REPORT_IOCTL_ERROR("HIDIOCGUSAGE", errno); goto bye; } result = 0; bye: DBGMSF(debug, "Returning: %d", result); return result; } /* Sets the value of usage based on its usage code. * It is left to hiddev to determine the actual report field, and usage indexes * * Arguments: * fd file descriptor for open hiddev device * report_type HID_REPORT_TYPE_FEATURE or HID_REPORT_TYPE_OUTPUT * report_id report number * field_idx field number * usage_idx usage number * value value to set * * Returns: status code */ Public_Status_Code set_usage_value_by_report_type_and_ucode( int fd, __u32 report_type, __u32 usage_code, __s32 value) { bool debug = false; DBGMSF(debug, "Starting. fd=%d, report_type=%d, usage_code=0x%08x, value=%d", fd, report_type, usage_code, value); Public_Status_Code psc = 0; struct hiddev_usage_ref uref = { .report_type = report_type, .report_id = HID_REPORT_ID_UNKNOWN, .usage_code = usage_code, .value = value, }; if (debug) { DBGMSG("Before HIDIOCSUSAGE"); dbgrpt_hiddev_usage_ref(&uref, 1); } if (ioctl(fd, HIDIOCSUSAGE, &uref) < 0) { psc = -errno; REPORT_IOCTL_ERROR("HIDIOCSUSAGE", errno); goto bye; } // if (debug) { // DBGMSG("HIDIOCSUSAGE succeeded"); // report_hiddev_usage_ref(&uref, 1); // } // need to get the actual report_id - HIDIOCSREPORT fails if HID_REPORT_ID_UNKNOWN psc = hiddev_get_usage_value(fd, &uref, CALLOPT_ERR_MSG); // should never fail, deleted CALLOPT_ERR_ABORT // if (debug) { // DBGMSG("After get_hid_usage_value()"); // report_hiddev_usage_ref(&uref, 1); // } if (psc < 0) // should never occur goto bye; struct hiddev_report_info rinfo = { .report_type = report_type, .report_id = uref.report_id }; if (ioctl(fd, HIDIOCSREPORT, &rinfo) < 0) { psc = -errno; REPORT_IOCTL_ERROR("HIDIOCSREPORT", errno); goto bye; } psc = 0; bye: DBGMSF(debug, "Returning: %s", psc_desc(psc) ); return psc; } // // Get and set based on a Usb_Monitor_Vcp_Rec // /* Gets the current value of a usage, as identified by a Usb_Monitor_Vcp_Rec * * Arguments: * fd file descriptor for open hiddev device * vcprec pointer to a Usb_Monitor_Vcp_Rec identifying the value to retrieve * maxval address at which to return max value of the usage * curval address at which to return the current value of the usage * * Returns: status code * * Calls to this function are valid only for Feature or Input reports. */ Public_Status_Code usb_get_usage_value_by_vcprec( int fd, Usb_Monitor_Vcp_Rec * vcprec, __s32 * maxval, __s32 * curval) { bool debug = false; DBGMSF(debug, "Starting. fd=%d, vcprec=%p", fd, vcprec); Public_Status_Code psc = 0; int rc; assert(vcprec->rinfo->report_type == vcprec->report_type); assert(vcprec->rinfo->report_type == HID_REPORT_TYPE_FEATURE || vcprec->rinfo->report_type == HID_REPORT_TYPE_INPUT); // *** CG19 *** assert(vcprec->rinfo->report_id == vcprec->report_id); DBGMSF(debug, "report_type=%d (%s), report_id=%d, field_index=%d, usage_index=%d", vcprec->report_type, hiddev_report_type_name(vcprec->report_type), vcprec->report_id, vcprec->field_index, vcprec->usage_index); rc = hiddev_get_report(fd, vcprec->rinfo, CALLOPT_ERR_MSG); // |CALLOPT_ERR_ABORT); if (rc < 0) { psc = rc; goto bye; } __s32 maxval1 = vcprec->finfo->logical_maximum; __s32 maxval2 = vcprec->finfo->physical_maximum; DBGMSF(debug, "logical_maximum: %d", maxval1); DBGMSF(debug, "physical_maximum: %d", maxval2); *maxval = vcprec->finfo->logical_maximum; if (vcprec->finfo->logical_minimum < 0) { DBGMSG("Unexpected: logical_minmum (%d) is < 0", vcprec->finfo->logical_minimum); } struct hiddev_usage_ref * uref = vcprec->uref; #ifdef DISABLE uref->report_type = vcprec->report_type; uref->report_id = vcprec->report_id; uref->field_index = vcprec->field_index; uref->usage_index = vcprec->usage_index; #endif if (debug) dbgrpt_hiddev_usage_ref(uref, 1); psc = hiddev_get_usage_value(fd, uref, CALLOPT_ERR_MSG); // rc = ioctl(fd, HIDIOCGUSAGE, uref); // Fills in usage value if (psc != 0) { // REPORT_IOCTL_ERROR("HIDIOCGUSAGE", rc); // occasionally see -1, errno = 22 invalid argument - for Battery System Page: Run Time to Empty // gsc = modulate_rc(-errsv, RR_ERRNO); } else { DBGMSF(debug, "usage_index=%d, value = 0x%08x",uref->usage_index, uref->value); *curval = uref->value; } bye: DBGMSF(debug, "Returning: %s", psc_desc(psc) ); return psc; } /* Sets the value of a usage, as identified by a Usb_Monitor_Vcp_Rec * * Arguments: * fd file descriptor for open hiddev device * vcprec pointer to a Usb_Monitor_Vcp_Rec identifying the usage to set * new_value new value * * Returns: status code * * Calls to this function are valid only for Feature or Output reports. */ Public_Status_Code usb_set_usage_value_by_vcprec( int fd, Usb_Monitor_Vcp_Rec * vcprec, __s32 new_value) { bool debug = false; DBGMSF(debug, "Starting. fd=%d, vcprec=%p", fd, vcprec); Public_Status_Code psc = 0; assert(vcprec->rinfo->report_type == vcprec->report_type); assert(vcprec->report_type == HID_REPORT_TYPE_FEATURE || vcprec->report_type == HID_REPORT_TYPE_OUTPUT); // CG19 assert(vcprec->rinfo->report_id == vcprec->report_id); DBGMSF(debug, "report_type=%d (%s), report_id=%d, field_index=%d, usage_index=%d, new_value=%d", vcprec->report_type, hiddev_report_type_name(vcprec->report_type), vcprec->report_id, vcprec->field_index, vcprec->usage_index, new_value); Status_Errno rc = set_control_value(fd, vcprec->report_type, vcprec->report_id, vcprec->field_index, vcprec->usage_index, new_value); if (rc < 0) psc = rc; // to simplify // gsc = modulate_rc(rc, RR_ERRNO); DBGMSF(debug, "Returning: %s", psc_desc(psc)); return psc; } // // High level getters/setters // /* Gets the value for a non-table feature. * * Arguments: * dh handle for open display * feature_code * ppInterpretedCode where to return result * * Returns: * status code */ Public_Status_Code usb_get_nontable_vcp_value( Display_Handle * dh, Byte feature_code, Parsed_Nontable_Vcp_Response** ppInterpretedCode) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Reading feature 0x%02x, dh=%p, dh->dref=%p", feature_code, dh, dh->dref); assert(dh->dref->io_path.io_mode == DDCA_IO_USB); // if (!dh->dref) { // DGBMSF(debug, "HACK: getting value for uninitialized dh->dref"); // --- // } Public_Status_Code psc = DDCRC_REPORTED_UNSUPPORTED; // = 0; // Output_Level output_level = get_output_level(); Parsed_Nontable_Vcp_Response * parsed_response = NULL; Usb_Monitor_Info * moninfo = usb_find_monitor_by_dh(dh); assert(moninfo); __s32 maxval = 0; // initialization logically unnecessary, but avoids clang scan warning __s32 curval = 0; // ditto bool use_alt_method = true; if (use_alt_method) { __u32 usage_code = 0x0082 << 16 | feature_code; psc = usb_get_usage_value_by_report_type_and_ucode( dh->fd, HID_REPORT_TYPE_FEATURE, usage_code, &maxval, &curval); if (psc != 0) psc = usb_get_usage_value_by_report_type_and_ucode( dh->fd, HID_REPORT_TYPE_INPUT, usage_code, &maxval, &curval); } else { // find the field record GPtrArray * vcp_recs = moninfo->vcp_codes[feature_code]; if (!vcp_recs) { DBGMSF(debug, "Unrecognized feature code 0x%02x", feature_code); psc = DDCRC_REPORTED_UNSUPPORTED; } else { // DBGMSF(debug, "reading value"); // for testing purposes, try using each entry // usage 0 returns correct value, usage 1 returns 0 // is usage 1 for writing? for (int ndx=0; ndxlen; ndx++) { int ndx = 0; Usb_Monitor_Vcp_Rec * vcprec = g_ptr_array_index(vcp_recs,ndx); assert( memcmp(vcprec->marker, USB_MONITOR_VCP_REC_MARKER,4) == 0 ); if (vcprec->report_type == HID_REPORT_TYPE_OUTPUT) continue; psc = usb_get_usage_value_by_vcprec(dh->fd, vcprec, &maxval, &curval); DBGMSF(debug, "usb_get_usage() usage index: %d returned %d, maxval=%d, curval=%d", vcprec->usage_index, psc, maxval, curval); if (psc == 0) break; } } } if (psc == 0) { parsed_response = calloc(1, sizeof(Parsed_Nontable_Vcp_Response)); parsed_response->vcp_code = feature_code; parsed_response->valid_response = true; parsed_response->supported_opcode = true; // parsed_response->cur_value = curval; // parsed_response->max_value = maxval; parsed_response->mh = (maxval >> 8) & 0xff; parsed_response->ml = maxval & 0xff; parsed_response->sh = (curval >> 8) & 0xff; parsed_response->sl = curval & 0xff; } DBGTRC(debug, TRACE_GROUP, "Returning %s, *ppinterpreted_code=%p", psc_desc(psc), parsed_response); *ppInterpretedCode = parsed_response; return psc; } /* Gets the value of a VCP feature. * * Arguments: * dh handle for open display * feature_code feature code id * call_type indicates whether table or non-table * pvalrec location where to return newly allocated result * * Returns: * status code * * The caller is responsible for freeing the value result returned. */ // only changes from get_vcp_value are function names Public_Status_Code usb_get_vcp_value( Display_Handle * dh, Byte feature_code, DDCA_Vcp_Value_Type call_type, DDCA_Any_Vcp_Value ** pvalrec) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Starting. Reading feature 0x%02x", feature_code); Public_Status_Code psc = 0; #ifdef FUTURE Buffer * buffer = NULL; #endif Parsed_Nontable_Vcp_Response * parsed_nontable_response = NULL; DDCA_Any_Vcp_Value * valrec = NULL; switch (call_type) { case (DDCA_NON_TABLE_VCP_VALUE): psc = usb_get_nontable_vcp_value( dh, feature_code, &parsed_nontable_response); if (psc == 0) { valrec = create_nontable_vcp_value( feature_code, parsed_nontable_response->mh, parsed_nontable_response->ml, parsed_nontable_response->sh, parsed_nontable_response->sl); free(parsed_nontable_response); } break; case (DDCA_TABLE_VCP_VALUE): #ifdef FUTURE psc = usb_get_table_vcp_value( dh, feature_code, &buffer); if (psc == 0) { valrec = create_table_vcp_value_by_buffer(feature_code, buffer); buffer_free(buffer, __func__); } #endif psc = DDCRC_REPORTED_UNSUPPORTED; // TEMP - should test known features first break; } *pvalrec = valrec; DBGTRC(debug, TRACE_GROUP, "Done. Returning: %s", psc_desc(psc) ); if (psc == 0 && debug) dbgrpt_single_vcp_value(valrec,1); assert( (psc == 0 && *pvalrec) || (psc != 0 && !*pvalrec) ); return psc; } /* Sets the value for a non-table feature. * * Arguments: * dh handle for open display * feature_code * new_value value to set * * Returns: * status code */ Public_Status_Code usb_set_nontable_vcp_value( Display_Handle * dh, Byte feature_code, int new_value) { bool debug = false; DBGTRC(debug, TRACE_GROUP, "Setting feature 0x%02x, dh=%p, dh->dref=%p, new_value=%d", feature_code, dh, dh->dref, new_value); Public_Status_Code psc = DDCRC_REPORTED_UNSUPPORTED; // = 0; assert(dh->dref->io_path.io_mode == DDCA_IO_USB); Usb_Monitor_Info * moninfo = usb_find_monitor_by_dh(dh); assert(moninfo); bool use_alt = true; if (use_alt) { __u32 usage_code = 0x0082 << 16 | feature_code; psc = set_usage_value_by_report_type_and_ucode( dh->fd, HID_REPORT_TYPE_FEATURE, usage_code, new_value); // if (gsc != 0) // gsc = set_usage_value_by_report_type_and_ucode(dh->fh, HID_REPORT_TYPE_OUTPUT, usage_code, new_value); // if (gsc == modulate_rc(EINVAL, RR_ERRNO)) // gsc = DDCRC_REPORTED_UNSUPPORTED; if (psc == -EINVAL) psc = DDCRC_REPORTED_UNSUPPORTED; } else { // find the field record GPtrArray * vcp_recs = moninfo->vcp_codes[feature_code]; if (!vcp_recs) { DBGMSF(debug, "Unrecognized feature code 0x%02x", feature_code); psc = DDCRC_REPORTED_UNSUPPORTED; } else { DBGMSF(debug, "setting value"); // for testing purposes, try using each entry // for reading, usage 0 returns correct value, usage 1 returns 0 // is usage 1 for writing? // when writing, usage 0 works properly // usage 1, at least for brightness, sets control to max value for (int ndx=0; ndxlen; ndx++) { Usb_Monitor_Vcp_Rec * vcprec = g_ptr_array_index(vcp_recs,ndx); assert( memcmp(vcprec->marker, USB_MONITOR_VCP_REC_MARKER,4) == 0 ); if (vcprec->report_type == HID_REPORT_TYPE_INPUT) continue; psc = usb_set_usage_value_by_vcprec(dh->fd, vcprec, new_value); DBGMSF(debug, "usb_set_usage() usage index: %d returned %s", vcprec->usage_index, psc_desc(psc) ); if (psc == 0) break; } } } DBGTRC(debug, TRACE_GROUP, "Returning %s", psc_desc(psc)); return psc; } /* Sets a VCP feature value. * * Arguments: * dh display handle for open display * vrec pointer to value record * * Returns: * status code */ Public_Status_Code usb_set_vcp_value( // changed from set_vcp_value() Display_Handle * dh, DDCA_Any_Vcp_Value * vrec) { Public_Status_Code psc = 0; if (vrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { psc = usb_set_nontable_vcp_value(dh, vrec->opcode, VALREC_CUR_VAL(vrec)); // function name changed } else { assert(vrec->value_type == DDCA_TABLE_VCP_VALUE); // gsc = usb_set_table_vcp_value(dh, vrec->opcode, vrec->val.t.bytes, vrec->val.t.bytect); psc = DDCRC_UNIMPLEMENTED; } return psc; } // // Special case: get VESA version // // 7/2016: this code is based on USB HID Monitor spec. // have yet to see a monitor that supports VESA Version usage code __s32 usb_get_vesa_version_by_report_type(int fd, __u32 report_type) { bool debug = false; __s32 maxval; __s32 curval; Public_Status_Code psc = usb_get_usage_value_by_report_type_and_ucode( fd, report_type, 0x00800004, &maxval, &curval); if (psc != 0 && debug) { DBGMSG("report_type=%s, usb_get_usage_alt() status code %s", hiddev_report_type_name(report_type), psc_desc(psc) ); } // DBGMSF(debug, "report_type=%s, returning: 0x%08x", report_type_name(report_type), curval); return curval; } __s32 usb_get_vesa_version(int fd) { bool debug = false; __s32 vesa_ver = usb_get_vesa_version_by_report_type(fd, HID_REPORT_TYPE_FEATURE); if (!vesa_ver) vesa_ver = usb_get_vesa_version_by_report_type(fd, HID_REPORT_TYPE_INPUT); // DBGMSF(debug, "VESA version from usb_get_vesa_version_by_report_type(): 0x%08x", vesa_ver); DBGMSF(debug, "returning: 0x%08x", vesa_ver); return vesa_ver; } ddcutil-2.2.0/src/usb/usb_vcp.h0000664000175000001440000000250514754576332012036 /* \file usb_vcp.h * * Get and set VCP feature codes for USB connected monitors. */ // Copyright (C) 2016-2018 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef USB_VCP_H_ #define USB_VCP_H_ #include #include "ddcutil_types.h" #include "util/coredefs.h" #include "base/displays.h" #include "base/ddc_packets.h" #include "vcp/vcp_feature_values.h" Public_Status_Code usb_get_usage_value_by_report_type_and_ucode( int fd, __u32 report_type, __u32 usage_code, __s32 * maxval, __s32 * curval); Public_Status_Code usb_get_nontable_vcp_value( Display_Handle * dh, Byte feature_code, Parsed_Nontable_Vcp_Response** ppInterpretedCode); Public_Status_Code usb_get_vcp_value( Display_Handle * dh, Byte feature_code, DDCA_Vcp_Value_Type call_type, DDCA_Any_Vcp_Value ** pvalrec); Public_Status_Code usb_set_nontable_vcp_value( Display_Handle * dh, Byte feature_code, int new_value); Public_Status_Code usb_set_vcp_value( Display_Handle * dh, DDCA_Any_Vcp_Value * pvalrec); __s32 usb_get_vesa_version(int fd); #endif /* USB_VCP_H_ */ ddcutil-2.2.0/src/usb/usb_edid.h0000644000175000001440000000065014754576332012150 /** @file usb_edid.h * * Functions to get EDID for USB connected monitors */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef USB_EDID_H_ #define USB_EDID_H_ #include #include "util/edid.h" Parsed_Edid * get_hiddev_edid_with_fallback(int fd, struct hiddev_devinfo * dev_info); void init_usb_edid(); #endif /* USB_EDID_H_ */ ddcutil-2.2.0/src/usb/usb_services.h0000644000175000001440000000042314754576332013064 /** @file usb_services.h */ // Copyright (C) 2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef USB_SERVICES_H_ #define USB_SERVICES_H_ void init_usb_services(); void terminate_usb_services(); #endif /* USB_SERVICES_H_ */ ddcutil-2.2.0/src/usb/usb_base.h0000644000175000001440000000512714754576332012161 /** usb_base.h */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef USB_BASE_H_ #define USB_BASE_H_ #include #include #include #include "util/coredefs.h" #include "util/data_structures.h" #include "util/edid.h" #ifdef ALT_LOCK_REC #include "base/display_lock.h" #endif #include "base/status_code_mgt.h" #ifdef UNUSED #define REPORT_IOCTL_ERROR_AND_QUIT(_ioctl_name, _rc) \ do { \ printf("(%s) ioctl(%s) returned %d (0x%08x), errno=%d: %s\n", \ __func__, \ _ioctl_name, \ _rc, \ _rc, \ errno, \ strerror(errno) \ ); \ ddc_abort(errno); \ } while(0) #endif /* Describes a USB connected monitor. */ #define USB_MONITOR_INFO_MARKER "UMNF" typedef struct usb_monitor_info { char marker[4]; char * hiddev_device_name; Parsed_Edid * edid; #ifdef ALT_LOCK_REC Display_Lock_Record * lock_rec; #endif struct hiddev_devinfo * hiddev_devinfo; // a flagrant waste of space, avoid premature optimization GPtrArray * vcp_codes[256]; // array of Usb_Monitor_Vcp_Rec * } Usb_Monitor_Info; int usb_open_hiddev_device(char * hiddev_devname, Byte calloptions); Status_Errno usb_close_device(int fd, char * device_fn, Byte calloptions); Status_Errno hiddev_get_device_info(int fd, struct hiddev_devinfo * dinfo, Byte calloptions); Status_Errno hiddev_get_report_info(int fd, struct hiddev_report_info * rinfo, Byte calloptions); Status_Errno hiddev_get_field_info( int fd, struct hiddev_field_info * finfo, Byte calloptions); Status_Errno hiddev_get_usage_code( int fd, struct hiddev_usage_ref * uref, Byte calloptions); Status_Errno hiddev_get_usage_value(int fd, struct hiddev_usage_ref * uref, Byte calloptions); Status_Errno hiddev_get_report( int fd, struct hiddev_report_info * rinfo, Byte calloptions); typedef uint32_t Vid_Pid_Value; #define VID_PID_VALUE_TO_VID(_vid_pid) (_vid_pid >> 16) #define VID_PID_VALUE_TO_PID(_vid_pid) (_vid_pid & 0xff) #define VID_PID_VALUE(_vid,_pid) ( _vid << 16 | _pid) void usb_ignore_hiddevs(Bit_Set_32 ignored_hiddevs); bool usb_is_ignored_hiddev(uint8_t hiddev_number); void usb_ignore_vid_pid_values(uint8_t ignored_ct, Vid_Pid_Value* ignored_vid_pids); bool usb_is_ignored_vid_pid(uint16_t vid, uint16_t pid); bool usb_is_ignored_vid_pid_value(Vid_Pid_Value vidpid); void init_usb_base(); void terminate_usb_base(); #endif /* USB_BASE_H_ */ ddcutil-2.2.0/src/usb/usb_displays.h0000644000175000001440000000416414754576332013077 /** @file usb_displays.h */ // Copyright (C) 2016-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef USB_DISPLAYS_H_ #define USB_DISPLAYS_H_ /** \cond */ #include #include // for __u32 /** \endcond */ #include "util/coredefs.h" #include "base/core.h" #include "base/display_lock.h" #include "base/displays.h" #include "base/ddc_packets.h" #ifdef ALT_DISPLAY_LOCK #include "base/display_lock.h" #endif #include "vcp/vcp_feature_values.h" #include "usb/usb_base.h" bool check_usb_monitor( char * device_name ); #ifdef OLD Display_Info_List usb_get_valid_displays(); #endif bool usb_is_valid_display_ref( Display_Ref * dref, bool emit_error_msg); void usb_show_active_display_by_dref( Display_Ref * dref, int depth); Parsed_Edid * usb_get_parsed_edid_by_dref( Display_Ref * dref); Parsed_Edid * usb_get_parsed_edid_by_dh( Display_Handle * dh); char * usb_get_capabilities_string_by_dh(Display_Handle * dh); // struct defs here for sharing with usb_vcp /* Used to record hiddev settings for reading and * writing a VCP feature code */ #define USB_MONITOR_VCP_REC_MARKER "UMVR" typedef struct usb_monitor_vcp_rec { char marker[4]; Byte vcp_code; __u32 report_type; // type? // have both indexes and struct pointers - redundant int report_id; int field_index; int usage_index; struct hiddev_report_info * rinfo; struct hiddev_field_info * finfo; struct hiddev_usage_ref * uref; } Usb_Monitor_Vcp_Rec; void dbgrpt_usb_monitor_info(Usb_Monitor_Info * moninfo, int depth); Usb_Monitor_Info * usb_find_monitor_by_dh(Display_Handle * dh); bool is_possible_monitor_by_hiddev_name(const char * hiddev_name); GPtrArray * get_usb_monitor_list(); GPtrArray * get_usb_open_errors(); void discard_usb_monitor_list(); void init_usb_displays(); void terminate_usb_displays(); #endif /* USB_DISPLAYS_H_ */ ddcutil-2.2.0/src/usb_util/0000775000175000001440000000000014754576332011337 5ddcutil-2.2.0/src/usb_util/Makefile.am0000644000175000001440000000170714441414365013304 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src AM_CFLAGS = $(AM_CFLAGS_STD) # lots of arguments for %p in format strings need (void*) casts if -Wpedantic # AM_CFLAGS += -Wpedantic CLEANFILES = \ *expand clean-local: @echo "(src/usbutil/Makefile) clean-local" mostlyclean-local: @echo "(src/usbutil/Makefile) mostlyclean-local" distclean-local: @echo "(src/usbutil/Makefile) distclean-local" # The dist-hook find statements here find nothing, but the corresponding # statements in src/Makefile.am do. why? dist-hook: @echo "(src/usbutil/Makefile) dist-hook. top_distdir=$(top_distdir) distdir=$(distdir)" find $(distdir) -name "*.o" find $(distdir) -name "*.lo" if ENABLE_USB_COND # Intermediate Libraries noinst_LTLIBRARIES = libusbutil.la libusbutil_la_SOURCES = \ usb_hid_common.c \ hiddev_reports.c \ hiddev_util.c \ hidraw_util.c \ libusb_reports.c \ libusb_util.c \ base_hid_report_descriptor.c \ hid_report_descriptor.c endif ddcutil-2.2.0/src/usb_util/Makefile.in0000664000175000001440000005554414754576155013344 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/usb_util ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libusbutil_la_LIBADD = am__libusbutil_la_SOURCES_DIST = usb_hid_common.c hiddev_reports.c \ hiddev_util.c hidraw_util.c libusb_reports.c libusb_util.c \ base_hid_report_descriptor.c hid_report_descriptor.c @ENABLE_USB_COND_TRUE@am_libusbutil_la_OBJECTS = usb_hid_common.lo \ @ENABLE_USB_COND_TRUE@ hiddev_reports.lo hiddev_util.lo \ @ENABLE_USB_COND_TRUE@ hidraw_util.lo libusb_reports.lo \ @ENABLE_USB_COND_TRUE@ libusb_util.lo \ @ENABLE_USB_COND_TRUE@ base_hid_report_descriptor.lo \ @ENABLE_USB_COND_TRUE@ hid_report_descriptor.lo libusbutil_la_OBJECTS = $(am_libusbutil_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = @ENABLE_USB_COND_TRUE@am_libusbutil_la_rpath = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/base_hid_report_descriptor.Plo \ ./$(DEPDIR)/hid_report_descriptor.Plo \ ./$(DEPDIR)/hiddev_reports.Plo ./$(DEPDIR)/hiddev_util.Plo \ ./$(DEPDIR)/hidraw_util.Plo ./$(DEPDIR)/libusb_reports.Plo \ ./$(DEPDIR)/libusb_util.Plo ./$(DEPDIR)/usb_hid_common.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libusbutil_la_SOURCES) DIST_SOURCES = $(am__libusbutil_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src AM_CFLAGS = $(AM_CFLAGS_STD) # lots of arguments for %p in format strings need (void*) casts if -Wpedantic # AM_CFLAGS += -Wpedantic CLEANFILES = \ *expand # Intermediate Libraries @ENABLE_USB_COND_TRUE@noinst_LTLIBRARIES = libusbutil.la @ENABLE_USB_COND_TRUE@libusbutil_la_SOURCES = \ @ENABLE_USB_COND_TRUE@usb_hid_common.c \ @ENABLE_USB_COND_TRUE@hiddev_reports.c \ @ENABLE_USB_COND_TRUE@hiddev_util.c \ @ENABLE_USB_COND_TRUE@hidraw_util.c \ @ENABLE_USB_COND_TRUE@libusb_reports.c \ @ENABLE_USB_COND_TRUE@libusb_util.c \ @ENABLE_USB_COND_TRUE@base_hid_report_descriptor.c \ @ENABLE_USB_COND_TRUE@hid_report_descriptor.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/usb_util/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/usb_util/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libusbutil.la: $(libusbutil_la_OBJECTS) $(libusbutil_la_DEPENDENCIES) $(EXTRA_libusbutil_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(am_libusbutil_la_rpath) $(libusbutil_la_OBJECTS) $(libusbutil_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/base_hid_report_descriptor.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hid_report_descriptor.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hiddev_reports.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hiddev_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hidraw_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libusb_reports.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libusb_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/usb_hid_common.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/base_hid_report_descriptor.Plo -rm -f ./$(DEPDIR)/hid_report_descriptor.Plo -rm -f ./$(DEPDIR)/hiddev_reports.Plo -rm -f ./$(DEPDIR)/hiddev_util.Plo -rm -f ./$(DEPDIR)/hidraw_util.Plo -rm -f ./$(DEPDIR)/libusb_reports.Plo -rm -f ./$(DEPDIR)/libusb_util.Plo -rm -f ./$(DEPDIR)/usb_hid_common.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-local distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/base_hid_report_descriptor.Plo -rm -f ./$(DEPDIR)/hid_report_descriptor.Plo -rm -f ./$(DEPDIR)/hiddev_reports.Plo -rm -f ./$(DEPDIR)/hiddev_util.Plo -rm -f ./$(DEPDIR)/hidraw_util.Plo -rm -f ./$(DEPDIR)/libusb_reports.Plo -rm -f ./$(DEPDIR)/libusb_util.Plo -rm -f ./$(DEPDIR)/usb_hid_common.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am dist-hook \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-local distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool mostlyclean-local pdf \ pdf-am ps ps-am tags tags-am uninstall uninstall-am .PRECIOUS: Makefile clean-local: @echo "(src/usbutil/Makefile) clean-local" mostlyclean-local: @echo "(src/usbutil/Makefile) mostlyclean-local" distclean-local: @echo "(src/usbutil/Makefile) distclean-local" # The dist-hook find statements here find nothing, but the corresponding # statements in src/Makefile.am do. why? dist-hook: @echo "(src/usbutil/Makefile) dist-hook. top_distdir=$(top_distdir) distdir=$(distdir)" find $(distdir) -name "*.o" find $(distdir) -name "*.lo" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/usb_util/usb_hid_common.c0000644000175000001440000001267014754576332014414 /** @file usb_hid_common.c * * Functions that are common to the wrappers for multiple USB HID * packages such as libusb, hiddev */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include "util/string_util.h" /** \endcond */ #include "usb_util/usb_hid_common.h" /* Return's the name of a collection type in a HID report descriptor. * * Per USB HID Specification v1.11, Section 6.2.2.6 */ const char * collection_type_name(uint8_t collection_type) { static char * collection_type_names[] = { "Physical", // 0 "Application", // 1 "Logical", // 2 "Report", // 3 "Named Array", // 4 "Usage Switch", // 5 "Usage_Modifier", // 6 }; char * result = NULL; if (collection_type < 7) result = collection_type_names[collection_type]; else if (collection_type & 0x80) result = "Vendor defined"; else result = "Reserved for future use."; return result; } /* Check for specific USB devices that should be treated as * monitors, even though the normal monitor check fails. * * This is a hack. * * Arguments: * vid USB vendor id * pid USB product id * * Returns true/false */ bool force_hid_monitor_by_vid_pid(int16_t vid, int16_t pid) { struct vid_pid { uint16_t vid; uint16_t pid; }; bool debug = false; if (debug) printf("(%s) Starting. vid=0x%04x, pid=0x%04x\n", __func__, vid, pid); bool result = false; struct vid_pid exceptions[] = { {0x0424, 0x3328}, // Std Micrososystems USB HID I2C - HP LP2480 {0x056d, 0x0002}, // Eizo, HID Monitor Controls {0x0451, 0xca01}, // Texas Instruments USB to I2C Solution - what is this // NEC monitors {0x0409, 0x040d}, // P232W {0x0409, 0x02b7}, // P241W {0x0409, 0x042c}, // P242W {0x0409, 0x02bb}, // PA231W {0x0409, 0x02b7}, // PA241W (mine) {0x0409, 0x02b8}, // PA241W (seen at RIT) {0x0409, 0x042d}, // PA242W {0x0409, 0x02b9}, // PA271W {0x0409, 0x042e}, // PA272W {0x0409, 0x02ba}, // PA301W {0x0409, 0x042f}, // PA302W {0x0409, 0x02bc}, // MD301C4 {0x0409, 0x040a}, // MD211G3 {0x0409, 0x040b}, // MD211C3 {0x0409, 0x040c}, // MD211C2 {0x0409, 0x042b}, // MD242C2 {0x0409, 0x044f}, // EA244UHD {0x0409, 0x042b}, // EA304WMi {0x0409, 0x046b}, // PA322UHD {0x0409, 0x047d}, // X841UHD {0x0409, 0x04ac}, // X981UHD {0x0409, 0x04ad}, // X651UHD {0x0409, 0x046c}, // MD322C8 {0x0409, 0x04Ae}, // P212 {0x0409, 0x050c}, // PA322UHD2 // additional values from usb.ids {0x0419, 0x8002}, // Samsung, Syncmaster HID Monitor Control {0x0452, 0x0021}, // Misubishi, HID Monitor Controls {0x04a6, 0x0181}, // Nokia, HID Monitor Controls {0x04ca, 0x1766}, // Lite-on, HID Monitor Controls }; const int vid_pid_ct = sizeof(exceptions)/sizeof(struct vid_pid); for (int ndx = 0; ndx < vid_pid_ct && !result; ndx++) { if (vid == exceptions[ndx].vid) { // there used to be some buggy code here looking at case of exceptions[ndx].pid == 0, why? if ( pid == exceptions[ndx].pid) { result = true; // if (debug) printf("(%s) Matched exception vid=0x%04x, pid=0x%04x\n", __func__, exceptions[ndx].vid, exceptions[ndx].pid); } } } if (debug) printf("(%s) vid=0x%04x, pid=0x%04x, returning: %s\n", __func__, vid, pid, sbool(result)); return result; } // This function was introduced because of a user bug report that display detection // caused the trackpoint on a Lenovo SK-8855 Thinkpad keyboard with pointing device // to stop working. It appears not to have solved the problem. (The reporting user ceased // running test builds.) /* Check for specific USB devices to not probe. * * This is a hack. * * Arguments: * vid USB vendor id * pid USB product id * * Returns true/false */ bool deny_hid_monitor_by_vid_pid(int16_t vid, int16_t pid) { struct vid_pid { uint16_t vid; uint16_t pid; }; bool debug = false; if (debug) printf("(%s) Starting. vid=0x%04x, pid=0x%04x\n", __func__, vid, pid); bool result = false; struct vid_pid exceptions[] = { {0x17ef, 0x6009}, // ThinkPad USB Keyboard with TrackPoint }; const int vid_pid_ct = sizeof(exceptions)/sizeof(struct vid_pid); for (int ndx = 0; ndx < vid_pid_ct && !result; ndx++) { if (vid == exceptions[ndx].vid) { // there used to be some buggy code here looking at case of exceptions[ndx].pid == 0, why? if ( pid == exceptions[ndx].pid) { result = true; // if (debug) printf("(%s) Matched exception vid=0x%04x, pid=0x%04x\n", __func__, exceptions[ndx].vid, exceptions[ndx].pid); } } } if (debug) printf("(%s) vid=0x%04x, pid=0x%04x, returning: %s\n", __func__, vid, pid, sbool(result)); return result; } ddcutil-2.2.0/src/usb_util/hiddev_reports.c0000644000175000001440000006560014754576332014451 /** @file hiddev_reports.c */ // Copyright (C) 2016-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include #include // #include #include "util/device_id_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "usb_util/hiddev_util.h" // numerous functions and macro definitions #include "usb_util/hiddev_reports.h" /* Wrap ioctl(HIDIOCGSTRING) to retrieve a string. * * It is the responsibility of the caller to free the returned string. * * Arguments: fd * index string index number * * Returns: string, NULL if invalid index number * * Notes: */ char * get_hiddev_string(int fd, __s32 index) { struct hiddev_string_descriptor desc; desc.index = index; // strcpy(desc.value,"Unset"); // for debugging Apple display issue // Returns string length if found, -1 if not // Apple Cinema display never returns -1, always seems to be last valid value errno = 0; // Very slow call on Apple Cinema display int rc = ioctl(fd, HIDIOCGSTRING, &desc); // if (rc != 0) // REPORT_IOCTL_ERROR("HIDIOCGSTRING", rc); char * result = NULL; if (rc > 0) result = g_strdup(desc.value); return result; } /* Reports all defined strings. * * Arguments: * fd file descriptor * max_ct maximum number of strings to report * depth logical indentation depth * * Returns: nothing * * Note: Parm max_ct exists because at least the Apple Cinema display * does not report that a string index is out of range, it just * reports the last valid value. */ void report_hiddev_strings(int fd, int max_ct, int depth) { rpt_title("Device strings returned by ioctl(HIDIOCGSTRING):", depth); int d1 = depth+1; int string_index = 1; char * string_value = NULL; for (; (string_value = get_hiddev_string(fd, string_index)); string_index++) { // for (; string_index < 10; string_index++) { // string_value = get_hiddev_string(fd, string_index); if (max_ct >= 0 && string_index > max_ct) { free(string_value); break; } rpt_vstring(d1, "String index: %d, value = |%s|", string_index, string_value); free(string_value); } } /* Outputs debug report for struct hiddev_devinfo * * Arguments: * dinfo pointer to struct hiddev_devinfo * lookup_names if true, ids for usb vendor and product ids are looked up * depth logical indentation depth * * Returns: nothing */ void dbgrpt_hiddev_devinfo(struct hiddev_devinfo * dinfo, bool lookup_names, int depth) { int d1 = depth+1; Pci_Usb_Id_Names names = {"","",""}; if (lookup_names) { devid_get_usb_names( dinfo->vendor, dinfo->product, 0, 2); } rpt_structure_loc("hiddev_devinfo", dinfo, depth); // bus types are defined in . No need to define a lookup table of types // to names, since the bus type is always USB rpt_vstring(d1,"%-20s: %u %s", "bustype", dinfo->bustype, (dinfo->bustype == 3) ? "BUS_USB" : ""); rpt_vstring(d1,"%-20s: %u", "busnum", dinfo->busnum); rpt_vstring(d1,"%-20s: %u", "devnum", dinfo->devnum); rpt_vstring(d1,"%-20s: %u", "ifnum", dinfo->ifnum); rpt_vstring(d1,"%-20s: 0x%04x %s", "vendor", dinfo->vendor, names.vendor_name); // strip high bytes? dinfo->product & 0x0000ffff // dinfo->product and dinfo->vendor are __s16, before conversion to hex string, they're // promoted to int, in which case the sign bit is extended, rpt_vstring(d1,"%-20s: 0x%04x %s", "product", dinfo->product & 0xffff, names.device_name); rpt_vstring(d1,"%-20s: %2x.%02x", "version", dinfo->version>>8, dinfo->version & 0x0f); // BCD rpt_vstring(d1,"%-20s: %u", "num_applications", dinfo->num_applications); } char * interpret_collection_type(__u32 type) { char * result = NULL; // Per USB HID spec section 6.2.2.4 Main Items // and section 6.2.2.6 Collection, End Collection Items switch(type) { case(0x00): result = "Physical"; break; case(0x01): result = "Application"; break; case(0x02): result = "Logical"; break; case(0x03): result = "Report"; break; case(0x04): result = "Named Array"; break; case(0x05): result = "Usage Switch"; break; case(0x06): result = "Usage Modifier"; break; default: if (type >= 0x80 && type <= 0xff) result = "Vendor-defined"; else result = "Reserved"; // should never occur } //switch return result; } /* Outputs debug report for struct hiddev_collection info * * Arguments: * cinfo pointer to struct hiddev_collecion_info * depth logical indentation depth * * Returns: nothing */ void report_hiddev_collection_info(struct hiddev_collection_info * cinfo, int depth) { int d1 = depth+1; rpt_structure_loc("hiddev_collection_info", cinfo, depth); rpt_vstring(d1, "%-20s: %u", "index", cinfo->index); rpt_vstring(d1, "%-20s: %u %s", "type", cinfo->type, interpret_collection_type(cinfo->type)); rpt_vstring(d1, "%-20s: 0x%08x %s", "usage", cinfo->usage, hiddev_interpret_usage_code(cinfo->usage)); rpt_vstring(d1, "%-20s: %u", "level", cinfo->level); } /* Outputs debug report for struct hiddev_string_descriptor * * Arguments: * desc pointer to struct hiddev_string_descriptor * depth logical indentation depth * * Returns: nothing */ void report_hiddev_string_descriptor(struct hiddev_string_descriptor * desc, int depth) { int d1 = depth+1; rpt_structure_loc("hiddev_string_descriptor", desc, depth); rpt_vstring(d1, "%-20s: %d", "index", desc->index); rpt_vstring(d1, "%-20s: |%s|", "value", desc->value); } #ifdef REF #define HID_FIELD_CONSTANT 0x001 #define HID_FIELD_VARIABLE 0x002 #define HID_FIELD_RELATIVE 0x004 #define HID_FIELD_WRAP 0x008 #define HID_FIELD_NONLINEAR 0x010 #define HID_FIELD_NO_PREFERRED 0x020 #define HID_FIELD_NULL_STATE 0x040 #define HID_FIELD_VOLATILE 0x080 #define HID_FIELD_BUFFERED_BYTE 0x100 #endif /* Produces a string representation of the HID field flag bits * * Arguments: flags word of flags * * Returns: String representation of flags. * * The value is built in an internal buffer and is valid * until the next call of this function. */ char * interpret_field_bits(__u32 flags) { #define FLAG_BIT(_bitname) \ if (flags & _bitname) \ curpos += sprintf(curpos, #_bitname "|") static char field_bits_buffer[200]; field_bits_buffer[0] = '\0'; char * curpos = field_bits_buffer; FLAG_BIT(HID_FIELD_CONSTANT); FLAG_BIT(HID_FIELD_VARIABLE); FLAG_BIT(HID_FIELD_RELATIVE); FLAG_BIT(HID_FIELD_WRAP); FLAG_BIT(HID_FIELD_NONLINEAR); FLAG_BIT(HID_FIELD_NO_PREFERRED); FLAG_BIT(HID_FIELD_NULL_STATE); FLAG_BIT(HID_FIELD_VOLATILE); FLAG_BIT(HID_FIELD_BUFFERED_BYTE); assert( (curpos-field_bits_buffer) < sizeof(field_bits_buffer) ); if (curpos != field_bits_buffer) *(curpos-1) = '\0'; return field_bits_buffer; #undef FLAG_BIT } /* Outputs debug report for struct hiddev_report_info * * Arguments: * desc pointer to struct hiddev_report_info * depth logical indentation depth * * Returns: nothing */ void dbgrpt_hiddev_report_info(struct hiddev_report_info * rinfo, int depth) { int d1 = depth+1; rpt_structure_loc("hiddev_report_info", rinfo, depth); rpt_vstring(d1, "%-20s: %u %s", "report_type", rinfo->report_type, hiddev_report_type_name(rinfo->report_type)); rpt_vstring(d1, "%-20s: %s 0x%08x", "report_id", hiddev_interpret_report_id(rinfo->report_id), rinfo->report_id); // may have next flag set in high order bit rpt_vstring(d1, "%-20s: %u", "num_fields", rinfo->num_fields); } #ifdef REF #define HID_REPORT_ID_UNKNOWN 0xffffffff #define HID_REPORT_ID_FIRST 0x00000100 #define HID_REPORT_ID_NEXT 0x00000200 #define HID_REPORT_ID_MASK 0x000000ff #define HID_REPORT_ID_MAX 0x000000ff #endif /* Returns a string representation of a report id value * * Arguments: report_id * * Returns: string representation of id * * The value is built in an internal buffer and is valid * until the next call of this function. */ char * hiddev_interpret_report_id(__u32 report_id) { static char report_id_buffer[100]; report_id_buffer[0] = '\0'; if (report_id == HID_REPORT_ID_UNKNOWN) strcpy(report_id_buffer, "HID_REPORT_ID_UNKNOWN"); else { if (report_id & HID_REPORT_ID_FIRST) strcpy(report_id_buffer, "HID_REPORT_ID_FIRST|"); if (report_id & HID_REPORT_ID_NEXT) strcat(report_id_buffer, "HID_REPORT_ID_NEXT|"); sprintf(report_id_buffer + strlen(report_id_buffer), "%u", report_id & HID_REPORT_ID_MASK); } return report_id_buffer; } /* Returns a string representation of a HID usage code * * Arguments: usage_code * * Returns: string representation of usage code * * The value is built in an internal buffer and is valid * until the next call of this function. */ char * hiddev_interpret_usage_code(int usage_code ) { static char usage_buffer[100]; usage_buffer[0] = '\0'; if (usage_code == 0) { // sprintf(usage_buffer, "0x%08x", usage_code); usage_buffer[0] = '\0'; } else { unsigned short usage_page = usage_code >> 16; unsigned short usage_id = usage_code & 0xffff; char * page_name; char * page_value_name; if (usage_page >= 0xff00) { page_name = "Manufacturer"; page_value_name = ""; } else { page_name = devid_usage_code_page_name(usage_page); if (!page_name) { page_name = ""; page_value_name = ""; } else { page_value_name = devid_usage_code_id_name(usage_page, usage_id); if (!page_value_name) page_value_name = ""; } } snprintf(usage_buffer, sizeof(usage_buffer), // "0x%08x page=0x%04x (%s), id=0x%04x (%s)", // usage_code, "page=0x%04x (%s), id=0x%04x (%s)", usage_page, page_name, usage_id, page_value_name); } return usage_buffer; } /* Outputs debug report for struct hiddev_field_info * * Arguments: * desc pointer to struct hiddev_field_info * depth logical indentation depth * * Returns: nothing */ void dbgrpt_hiddev_field_info(struct hiddev_field_info * finfo, int depth) { int d1 = depth+1; rpt_structure_loc("hiddev_field_info", finfo, depth); rpt_vstring(d1, "%-20s: %u %s", "report_type", finfo->report_type, hiddev_report_type_name(finfo->report_type)); // const char * s0 = names_reporttag(finfo->report_id); // const char * s1 = names_huts(finfo->physical>>16); // const char * s2 = names_hutus(finfo->physical); rpt_vstring(d1, "%-20s: %s (0x%08x)", "report_id", hiddev_interpret_report_id(finfo->report_id), finfo->report_id); rpt_vstring(d1, "%-20s: %u", "field_index", finfo->field_index); rpt_vstring(d1, "%-20s: %u", "maxusage", finfo->maxusage); rpt_vstring(d1, "%-20s: 0x%08x %s", "flags", finfo->flags, interpret_field_bits(finfo->flags) ); // rpt_vstring(d1, "%-20s: %u 0x%08x huts=|%s|, hutus=|%s| (physical usage for this field)", "physical", // finfo->physical, finfo->physical, s1, s2); rpt_vstring(d1, "%-20s: 0x%08x %s", "physical (usage)", finfo->physical, hiddev_interpret_usage_code(finfo->physical) ); rpt_vstring(d1, "%-20s: 0x%08x %s", "logical (usage)", finfo->logical, hiddev_interpret_usage_code(finfo->logical) ); rpt_vstring(d1, "%-20s: 0x%08x %s", "application (usage)", finfo->application, hiddev_interpret_usage_code(finfo->application) ); rpt_vstring(d1, "%-20s: %d", "logical_minimum", finfo->logical_minimum); rpt_vstring(d1, "%-20s: %d", "logical_maximum", finfo->logical_maximum); rpt_vstring(d1, "%-20s: %d", "physical_minimum", finfo->physical_minimum); rpt_vstring(d1, "%-20s: %d", "physical_maximum", finfo->physical_maximum); rpt_vstring(d1, "%-20s: %u", "unit_exponent", finfo->unit_exponent); rpt_vstring(d1, "%-20s: 0x%08x", "unit", finfo->unit); } /* Outputs debug report for struct hiddev_usage_ref * * Arguments: * desc pointer to struct hiddev_usage_ref * depth logical indentation depth * * Returns: nothing */ void dbgrpt_hiddev_usage_ref(struct hiddev_usage_ref * uref, int depth) { int d1 = depth+1; rpt_structure_loc("hiddev_usage_ref", uref, depth); rpt_vstring(d1, "%-20s: %u %s", "report_type", uref->report_type, hiddev_report_type_name(uref->report_type)); // const char * s0 = names_reporttag(uref->report_id); // char * s1 = names_huts(uref->usage_code>>16); // char * s2 = names_hutus(uref->usage_code); rpt_vstring(d1, "%-20s: %u %s", "report_id", uref->report_id, hiddev_interpret_report_id(uref->report_id)); rpt_vstring(d1, "%-20s: %u", "field_index", uref->field_index); rpt_vstring(d1, "%-20s: %u", "usage_index", uref->usage_index); // rpt_vstring(d1, "%-20s: 0x%08x huts=|%s|, hutus=|%s|", "usage_code", uref->usage_code, s1, s2); // rpt_usage_code("usage_code", NULL, uref->usage_code, d1); rpt_vstring(d1, "%-20s: 0x%08x %s", "usage_code", uref->usage_code, hiddev_interpret_usage_code(uref->usage_code) ); rpt_vstring(d1, "%-20s: %d", "value", uref->value); } void dbgrpt_hiddev_usage_ref_multi(struct hiddev_usage_ref_multi * uref_multi, int depth) { int d1 = depth+1; // int d2 = depth+2; rpt_structure_loc("hiddev_usage_ref_multi", uref_multi, depth); dbgrpt_hiddev_usage_ref(&uref_multi->uref, d1); rpt_vstring(d1, "%-20s: %d", "num_values", uref_multi->num_values); rpt_vstring(d1, "%-20s at %p", "values", &uref_multi->values); // rpt_hex_dump(&uref_multi->values, uref_multi->num_values, d2); } /** Reports a usage code for a field, based on the index, and also optionally the * usage value of the field. * */ void report_field_usage( int fd, int report_type, int report_id, int field_index, int usage_index, bool show_value, int depth) { int d0 = depth; int d1 = depth+1; int rc; // printf("(%s) field index = %d, usage index=%d\n", __func__, i, j); struct hiddev_usage_ref uref = {0}; // initialize to make valgrind happy uref.report_type = report_type; // rinfo.report_type; uref.report_id = report_id; // rinfo.report_id; uref.field_index = field_index; // i; uref.usage_index = usage_index; // j; rpt_vstring(d0, "report_id: %d, field_index: %d, usage_index: %d", uref.report_id, uref.field_index, uref.usage_index); errno = 0; rc = ioctl(fd, HIDIOCGUCODE, &uref); // Fills in usage code if (rc != 0) REPORT_USB_IOCTL_ERROR("HIDIOCGUCODE", errno); // assert(rc == 0); if (rc == 0) { rpt_vstring(d1, "Usage code = 0x%08x %s", uref.usage_code, hiddev_interpret_usage_code(uref.usage_code)); int collection_index = ioctl(fd, HIDIOCGCOLLECTIONINDEX, &uref); rpt_vstring(d1, "Collection index for usage code: %d", collection_index); if (show_value) { // Gets the current value of the field rc = ioctl(fd, HIDIOCGUSAGE, &uref); // Fills in usage value if (rc != 0) REPORT_USB_IOCTL_ERROR("HIDIOCGUSAGE", errno); // occasionally see -1, errno = 22 invalid argument - for Battery System Page: Run Time to Empty if (rc == 0) rpt_vstring(d1, "Current value (value) = %d (0x%08x)", uref.value, uref.value); else rpt_vstring(d1, "Error getting current value"); } } } /* Reports all report descriptors of a particular type for an open HID device. * * Arguments: * fd file descriptor for open hiddev device * report_type HID_REPORT_TYPE_INPUT, HID_REPORT_TYPE_OUTPUT, or HID_REPORT_TYPE_FEATURE * depth logical indentation depth * * Returns: nothing */ void report_report_descriptors_for_report_type(int fd, __u32 report_type, int depth) { int ret; const int d0 = depth; const int d1 = d0 + 1; const int d2 = d0 + 2; const int d3 = d0 + 3; const int d4 = d0 + 4; struct hiddev_report_info rinfo = {0}; // initialize to make valgrind happy rinfo.report_type = report_type; rinfo.report_id = HID_REPORT_ID_FIRST; puts(""); rpt_vstring(d0, "Getting descriptors for report_type=%s", hiddev_report_type_name(report_type)); ret = ioctl(fd, HIDIOCGREPORTINFO, &rinfo); if (ret != 0) { // no more reports if (ret != -1) REPORT_USB_IOCTL_ERROR("HIDIOCGREPORTINFO", errno); rpt_vstring(d1, "No reports defined"); return; } int rptct = 0; // count of reports seen, for our local interest while (ret >= 0) { // printf("(%s) Report counter %d, report_id = 0x%08x %s\n", // __func__, rptct, rinfo.report_id, interpret_report_id(rinfo.report_id)); puts(""); rpt_vstring(d0, "Report %s:", hiddev_interpret_report_id(rinfo.report_id)); dbgrpt_hiddev_report_info(&rinfo, d1); rptct++; if (rinfo.report_type != HID_REPORT_TYPE_OUTPUT) { // So that usage value filled in int rc = ioctl(fd, HIDIOCGREPORT, &rinfo); if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGREPORT", errno); printf("(%s) Unable to get report %d\n", __func__, rinfo.report_id); break; } } int fndx, undx; if (rinfo.num_fields > 0) rpt_vstring(d1, "Scanning fields of report %s", hiddev_interpret_report_id(rinfo.report_id)); for (fndx = 0; fndx < rinfo.num_fields; fndx++) { // printf("(%s) field index = %d\n", __func__, i); bool edidfg = hiddev_is_field_edid(fd, &rinfo, fndx); if (edidfg) { rpt_vstring(d2, "Report id: %d, Field index: %d contains EDID:", rinfo.report_id, fndx); } struct hiddev_field_info finfo = {0}; memset(&finfo, 0, sizeof(finfo)); finfo.report_type = rinfo.report_type; finfo.report_id = rinfo.report_id; finfo.field_index = fndx; rpt_vstring(d2, "Report id: %d, Field index %d:", finfo.report_id, fndx); int rc = ioctl(fd, HIDIOCGFIELDINFO, &finfo); if (rc != 0) { // should never occur REPORT_USB_IOCTL_ERROR("HIDIOCGFIELDINFO", errno); break; // just stop checking fields } rpt_vstring(d2, "Description of field %d:", fndx); if (finfo.field_index != fndx) { rpt_vstring(d3, "!! Note that HIDIOCGFIELDINFO changed field_index to %d", finfo.field_index); } dbgrpt_hiddev_field_info(&finfo, d3); bool usage_values_reported = false; __u32 common_ucode = 0; if (finfo.maxusage > 1) common_ucode = hiddev_get_identical_ucode(fd, &finfo, fndx); if (common_ucode) { rpt_vstring(d2, "Identical ucode for all usages: 0x%08x %s", common_ucode, hiddev_interpret_usage_code(common_ucode)); } // Get values for Feature or Input report if (finfo.report_type != HID_REPORT_TYPE_OUTPUT) { if (common_ucode) { if (finfo.flags & HID_FIELD_BUFFERED_BYTE) { rpt_vstring(d2, "Retrieving values using HIDIOCGUSAGES"); struct hiddev_usage_ref_multi uref_multi; uref_multi.uref.report_type = finfo.report_type; uref_multi.uref.report_id = finfo.report_id; uref_multi.uref.field_index = fndx; uref_multi.uref.usage_index = 0; uref_multi.num_values = finfo.maxusage; // needed? yes! rc = ioctl(fd, HIDIOCGUSAGES, &uref_multi); // Fills in usage values if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGUSAGES", errno); } else { // printf("(%s) Value retrieved by HIDIOCGUSAGES:\n", __func__); Byte * buf = calloc(1, finfo.maxusage); for (int ndx=0; ndxbytes, buf->len, d2); usage_values_reported = true; buffer_free(buf, __func__); } } } // common_ucode == true if (!usage_values_reported) { rpt_vstring(d2, "Usages for report_id: %d, field_index %d:", finfo.report_id, fndx /*finfo.field_index */); for (undx = 0; undx < finfo.maxusage; undx++) { report_field_usage(fd, finfo.report_type, finfo.report_id, fndx, undx, /*show_value=*/ true, d4); } //loop over undx } // common_ucode == false or !usage_values_collected } // HID_REPORT_TYPE_OUTPUT } // loop over fndx rinfo.report_id |= HID_REPORT_ID_NEXT; ret = ioctl(fd, HIDIOCGREPORTINFO, &rinfo); } if (rptct == 0) rpt_title("None", d1); } /* Reports all report descriptors for an open HID device. * * Arguments: * fd file descriptor * depth logical indentation depth * * Returns: nothing */ void report_all_report_descriptors(int fd, int depth) { report_report_descriptors_for_report_type(fd, HID_REPORT_TYPE_INPUT, depth); report_report_descriptors_for_report_type(fd, HID_REPORT_TYPE_OUTPUT, depth); report_report_descriptors_for_report_type(fd, HID_REPORT_TYPE_FEATURE, depth); } /* Reports all collection information for an open HID device. * * Arguments: * fd file descriptor * depth logical indentation depth * * Returns: nothing */ void report_all_collections(int fd, int depth) { int d1 = depth+1; // int d2 = depth+2; rpt_title("All collections for device:", depth); int cndx = 0; // collection indexes start at 0 int ioctl_rc = 0; for (cndx=0; ioctl_rc != -1; cndx++) { struct hiddev_collection_info cinfo; memset(&cinfo, 0, sizeof(cinfo)); errno = 0; cinfo.index = cndx; ioctl_rc = ioctl(fd, HIDIOCGCOLLECTIONINFO, &cinfo); if (ioctl_rc != -1) { rpt_vstring(d1,"Collection %d:", cinfo.index); report_hiddev_collection_info(&cinfo, d1); } } } /* Reports all information about an open HID device. * * Arguments: * fd file descriptor * depth logical indentation depth * * Returns: nothing */ void dbgrpt_hiddev_device_by_fd(int fd, int depth) { const int d1 = depth+1; const int d2 = depth+2; struct hiddev_devinfo dev_info; int rc; int version; rc = ioctl(fd, HIDIOCGVERSION, &version); // no need to test return code, always succeeds // ioctl(HIDIOCGVERSION) never fails, but add check of return code to avoid coverity flagging a problem assert(rc == 0); rpt_vstring(depth, "hiddev driver version (reported by HIDIOCGVERSION): %d.%d.%d", version>>16, (version >> 8) & 0xff, version & 0xff); #ifdef REDUNDANT_INFORMATION char * cgname = get_hiddev_name(fd); // HIDIOCGNAME // printf("(%s) get_hiddev_name() returned: |%s|\n", __func__, cgname); rpt_vstring(depth, "device name (reported by HIDIOCGNAME): |%s|", cgname); free(cgname); #endif rc = ioctl(fd, HIDIOCGDEVINFO, &dev_info); if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGDEVINFO", errno); return; } dbgrpt_hiddev_devinfo(&dev_info, /*lookup_names=*/true, depth); // if (!is_interesting_device(&dev_info)) { // printf("(%s) Uninteresting device\n", __func__); // return; // } int string_id_limit = -1; if (dev_info.vendor == 0x05ac) { // string_id_limit = 3; // Apple never returns invalid index. rpt_vstring(depth, "Skipping string retrieval for Apple Cinema display due to limitations."); string_id_limit = 0; // disable entirely - string retrieval painfully slow for Apple Cinema } puts(""); if (string_id_limit != 0) { report_hiddev_strings(fd,string_id_limit,depth); // HIDIOCGSTRING puts(""); } rpt_title("Usages for each application associated with the device:", depth); if (dev_info.num_applications == 0) { // should never occur, but just in case rpt_title("No applications", d2); } else { for (int ndx = 0; ndx < dev_info.num_applications; ndx++) { int usage = ioctl(fd, HIDIOCAPPLICATION, ndx); // printf("(%s) HIDIOCAPPLICATION returned 0x%08x for application %d\n", __func__, usage, i); if (usage == -1) { continue; } rpt_vstring(d1, "Application %d: Usage code: 0x%08x %s", ndx, usage, hiddev_interpret_usage_code(usage)); } } puts(""); rpt_title("Collection information is a superset of application information.", depth); rpt_title("Querying collections returns information on all collections the device has,", depth); rpt_title("not just application collections.", depth); puts(""); report_all_collections(fd,depth); puts(""); rpt_vstring(depth, "Identified as HID monitor: %s", sbool(is_hiddev_monitor(fd)) ); // puts(""); report_all_report_descriptors(fd, depth); #ifdef FUTURE puts(""); if (dev_info.vendor == 0x05ac) // Apple get_edid(fd); if (is_hiddev_monitor(fd)) { find_edid_report(fd); } #endif } #ifdef NOT_NEEDED // pci_usb_ids functions now call pciusb_ids_ensure_initialized() as necessary void init_hiddev_reports() { pciusb_id_ensure_initialized(); // names_init(); } #endif ddcutil-2.2.0/src/usb_util/hiddev_util.c0000644000175000001440000007253314754576332013733 /** @file hiddev_util.c */ // Copyright (C) 2016-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "util/coredefs.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/utilrpt.h" /** \endcond */ #include "usb_util/usb_hid_common.h" #include "usb_util/hiddev_reports.h" #include "usb_util/hiddev_util.h" static const char* report_type_id_table[] = { "invalid value", "HID_REPORT_TYPE_INPUT", "HID_REPORT_TYPE_OUTPUT", "HID_REPORT_TYPE_FEATURE" }; // To do: converge with similar function hid_report_type_name() // name hid_report_type_name() is more appropriate since there is nothing hiddev // specific about this function /* Returns a string representation of a report type id * * Arguments: report_type * * Returns: string representation of id */ const char * hiddev_report_type_name(__u32 report_type) { if (report_type < HID_REPORT_TYPE_MIN || report_type > HID_REPORT_TYPE_MAX) report_type = 0; return report_type_id_table[report_type]; } // // *** Functions to identify hiddev devices representing monitors *** // /* Filter to find hiddevN files for scandir() */ static int is_hiddev(const struct dirent *ent) { return !strncmp(ent->d_name, "hiddev", strlen("hiddev")); } /* Scans /dev to obtain list of hiddev device names * * Returns: GPtrArray of device device names. */ GPtrArray * get_hiddev_device_names_using_filesys() { bool debug = false; if (debug) printf("(%s) Starting...\n", __func__); const char *hidraw_paths[] = { "/dev/", "/dev/usb/", NULL }; GPtrArray * dev_names = get_filenames_by_filter(hidraw_paths, is_hiddev); if (debug) { printf("(%s) Done. Found %d hiddev devices:\n", __func__, dev_names->len); for (int ndx = 0; ndx < dev_names->len; ndx++) { printf(" %s\n", (char *) g_ptr_array_index(dev_names,ndx)); } } return dev_names; } /* Find hiddev device names using udev. * * Slightly more robust than get_hiddev_device_names_using_filesys() since doesn't * make assumptions as to where hiddev devices are found in the /dev tree. * * Arguments: none * Returns: array of hiddev path names in /dev */ GPtrArray * get_hiddev_device_names_using_udev() { bool debug = false; if (debug) printf("(%s) Starting...\n", __func__); GPtrArray * dev_names = g_ptr_array_sized_new(10); g_ptr_array_set_free_func(dev_names, g_free); struct udev *udev; struct udev_enumerate *enumerate; struct udev_list_entry * devices, *dev_list_entry; struct udev_device *dev; char * subsystem = "usbmisc"; // hiddev devices are in usbmisc subsystem /* Create the udev object */ udev = udev_new(); if (!udev) { printf("Can't create udev\n"); goto bye; } /* Create a list of the devices in the subsystem. */ enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, subsystem); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); /* udev_list_entry_foreach is a macro which expands to a loop. The loop will be executed for each member in devices, setting dev_list_entry to a list entry which contains the device's path in /sys. */ udev_list_entry_foreach(dev_list_entry, devices) { const char *path; /* Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it */ path = udev_list_entry_get_name(dev_list_entry); dev = udev_device_new_from_syspath(udev, path); const char * sysname = udev_device_get_sysname(dev); if (str_starts_with(sysname, "hiddev")) { g_ptr_array_add(dev_names, g_strdup(udev_device_get_devnode(dev))); } udev_device_unref(dev); } g_ptr_array_sort(dev_names, gaux_ptr_scomp); udev_enumerate_unref(enumerate); // free the enumerator object udev_unref(udev); bye: if (debug) { printf("(%s) Done. Found %d hiddev devices:\n", __func__, dev_names->len); for (int ndx = 0; ndx < dev_names->len; ndx++) { printf(" %s\n", (char *) g_ptr_array_index(dev_names,ndx)); } } return dev_names; } /* Find hiddev device names. * * Arguments: none * Returns: array of hiddev path names in /dev * * Allows for easily switching between alternative implementations. */ GPtrArray * get_hiddev_device_names() { // temp, call both for testing GPtrArray * result = get_hiddev_device_names_using_udev(); // g_ptr_array_free(result1, true); // GPtrArray * result2 = get_hiddev_device_names_using_filesys(); return result; } /* Check for specific USB devices that should be treated as * monitors, even though the normal monitor check fails. * * This is a hack. * * Arguments: * fd file descriptor * * Returns true/false */ bool force_hiddev_monitor(int fd) { bool debug = false; bool result = false; struct hiddev_devinfo dev_info; int rc = ioctl(fd, HIDIOCGDEVINFO, &dev_info); if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGDEVINFO", errno); goto bye; } result = force_hid_monitor_by_vid_pid( dev_info.vendor, dev_info.product); bye: if (debug) printf("(%s) vid=0x%04x, pid=0x%04x, returning: %s\n", __func__, dev_info.vendor, dev_info.product, sbool(result)); return result; } /* Check if an open hiddev device represents a USB compliant monitor. * * Arguments: * fd file descriptor * * Returns: true/false * * Per USB Monitor Control Class Specification section 5.5, * "to identify a HID class device as a monitor, the devices's * HID Report Descriptor must contain a top-level collection with * a usage of Monitor Control from the USB Monitor Usage Page." */ bool is_hiddev_monitor(int fd) { bool debug = false; if (debug) printf("(%s) Starting\n", __func__); int monitor_collection_index = -1; int cndx = 0; // indexes start at 0 int ioctl_rc = 0; for (cndx=0; ioctl_rc != -1; cndx++) { struct hiddev_collection_info cinfo; memset(&cinfo, 0, sizeof(cinfo)); errno = 0; cinfo.index = cndx; ioctl_rc = ioctl(fd, HIDIOCGCOLLECTIONINFO, &cinfo); if (ioctl_rc == -1) continue; assert(ioctl_rc == 0); if (debug) printf("(%s) cndx=%d, cinfo.level=%d, cinfo.usage=0x%08x\n", __func__, cndx, cinfo.level, cinfo.usage); if (cinfo.level == 0 && cinfo.usage == 0x00800001) { // USB Monitor Usage Page/Monitor Control monitor_collection_index = cndx; break; } } bool result = (monitor_collection_index >= 0); // FOR TESTING // if (!result) // result = force_hiddev_monitor(fd); if (debug) printf("(%s) Returning: %s\n", __func__, sbool(result)); return result; } /* Checks that all usages of a field have the same usage code. * * Arguments: * fd file descriptor of open hiddev device * finfo pointer to hiddev_field_info struct describing the field * field_index actual field index, value in finfo may have been changed by * HIDIOCGFIELDINFO call, that filled in hiddev_field_info * * Returns: usage code if all are identical, 0 if not */ __u32 hiddev_get_identical_ucode(int fd, struct hiddev_field_info * finfo, __u32 field_index) { // assert(finfo->flags & HID_FIELD_BUFFERED_BYTE); __u32 result = 0; for (int undx = 0; undx < finfo->maxusage; undx++) { struct hiddev_usage_ref uref = { .report_type = finfo->report_type, .report_id = finfo->report_id, .field_index = field_index, // actual field index, not value changed by HIDIOCGFIELDINFO .usage_index = undx }; // printf("(%s) report_type=%d, report_id=%d, field_index=%d, usage_index=%d\n", // __func__, rinfo->report_type, rinfo->report_id, field_index=saved_field_index, undx); int rc = ioctl(fd, HIDIOCGUCODE, &uref); // Fills in usage code if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGUCODE", errno); result = 0; break; } // printf("(%s) uref.field_index=%d, uref.usage_code = 0x%08x\n", // __func__, uref.field_index, uref.usage_code); if (undx == 0) result = uref.usage_code; else if (uref.usage_code != result) { result = 0; break; } } // loop over usages return result; } /* Collects all the usage values for a field and returns them in a Buffer. * * The field must meet the following requirements: * All usages must have the same usage code * All values must be single byte * * The function should only be called for INPUT and FEATURE reports. (assertion check) * * This function assumes that HIDIOCGREPORT has already been called * * Arguments: * fd file descriptor * finfo pointer to filled in hiddev_field_info for the field * field_index actual field index to use * * Returns: Buffer with accumulated value, * NULL if multiple usage codes or some usage value is > 0xff * It is the responsibility of the caller to free the returned buffer. */ Buffer * hiddev_collect_single_byte_usage_values( int fd, struct hiddev_field_info * finfo, __u32 field_index) { bool debug = false; Buffer * result = buffer_new(finfo->maxusage, __func__); bool ok = true; __s32 common_usage_code; // n.b. assumes HIDIOCGREPORT has been called assert(finfo->report_type != HID_REPORT_TYPE_OUTPUT); // bound is < finfo->maxusage, not <= finfo->maxusage // undx == finfo->maxusage returns errno=22, invalid argument for (int undx = 0; undx < finfo->maxusage; undx++) { struct hiddev_usage_ref uref = { .report_type = finfo->report_type, // rinfo.report_type; .report_id = finfo->report_id, // rinfo.report_id; .field_index = field_index, // use original value, not value changed by HIDIOCGFIELDINFO .usage_index = undx }; // printf("(%s) report_type=%d, report_id=%d, field_index=%d, maxusage=%d, usage_index=%d\n", // __func__, finfo->report_type, finfo->report_id, finfo->field_index, finfo->maxusage, undx); int rc = ioctl(fd, HIDIOCGUCODE, &uref); // Fills in usage code if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGUCODE", errno); ok = false; break; } // printf("(%s) uref.field_index=%d, uref.usage_code = 0x%08x\n", // __func__, uref.field_index, uref.usage_code); if (undx == 0) { common_usage_code = uref.usage_code; } else if (uref.usage_code != common_usage_code) { ok = false; if (debug) printf("(%s) Multiple usage codes", __func__); break; } rc = ioctl(fd, HIDIOCGUSAGE, &uref); // Fills in usage value if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGUSAGE", errno); ok = false; break; } if (uref.value &0xffffff00) { // if high order bytes non-zero if (true) printf("(%s) High order bytes of value for usage %d are non-zero\n", __func__, undx); ok = false; break; } Byte b = uref.value; buffer_add(result, b); if (false) printf("(%s) usage = %d, value=0x%08x, byte = 0x%02x\n", __func__, undx, uref.value, uref.value&0xff); } // loop over usages if (!ok && result) { buffer_free(result, __func__); result = NULL; } if (debug) { printf("(%s) Returning: %p\n", __func__, result); // if (result) // buffer_dump(result); } return result; } // // *** Functions for EDID retrieval *** // /* Checks if a field in a HID report represents an EDID * * Arguments: * fd file descriptor for open hiddev device * rinfo pointer to hiddev_report_info struct * field_index index number of field to check * * Returns: true if the field represents an EDID, false if not * * The field must have at least 128 usages, and the usage code for each must * be USB Monitor/EDID information */ bool hiddev_is_field_edid(int fd, struct hiddev_report_info * rinfo, int field_index) { bool debug = false; if (debug) printf("(%s) report_type=%d, report_id=%d, field index = %d\n", __func__, rinfo->report_type, rinfo->report_id, field_index); bool all_usages_edid = false; int rc; struct hiddev_field_info finfo = { .report_type = rinfo->report_type, .report_id = rinfo->report_id, .field_index = field_index }; int saved_field_index = field_index; rc = ioctl(fd, HIDIOCGFIELDINFO, &finfo); if (rc != 0) REPORT_USB_IOCTL_ERROR("HIDIOCGFIELDINFO", errno); assert(rc == 0); if (debug) { if (finfo.field_index != saved_field_index && debug) { printf("(%s) !!! ioctl(HIDIOCGFIELDINFO) changed field_index from %d to %d\n", __func__, saved_field_index, finfo.field_index); printf("(%s) rinfo.num_fields=%d, finfo.maxusage=%d\n", __func__, rinfo->num_fields, finfo.maxusage); } } if (finfo.maxusage >= 128) all_usages_edid = ( hiddev_get_identical_ucode(fd, &finfo, field_index) == 0x00800002 ); if (debug) printf("(%s) Returning: %s", __func__, sbool(all_usages_edid)); return all_usages_edid; } #define EDID_SIZE 128 // // hid_field_locator functions // void free_hid_field_locator(struct hid_field_locator * location) { if (location) { if (location->finfo) free(location->finfo); free(location); } } void report_hid_field_locator(struct hid_field_locator * ploc, int depth) { int d1 = depth+1; rpt_structure_loc("struct hid_field_locator", ploc, depth); if (ploc) { rpt_vstring(d1, "%-20s %u", "report_type:", ploc->report_type ); rpt_vstring(d1, "%-20s %u", "report_id:", ploc->report_id ); rpt_vstring(d1, "%-20s %u", "field_index:", ploc->field_index); // report_hiddev_report_info(ploc->rinfo, d1); dbgrpt_hiddev_field_info(ploc->finfo, d1); } } /* Test if all, or alternatively at least 1, usage codes of a field match a specified usage code. * * Arguments: * fd file descriptor of open hiddev device * report_type HID_REPORT_TYPE_INPUT, HID_REPORT_TYPE_OUTPUT, or HID_REPORT_TYPE_FEATURE * report_id report number * field_index field index * ucode usage code to test against * require_all_match if true, all usages must be the specified value * * Returns: field information if true, NULL if false */ struct hiddev_field_info * test_field_ucode( int fd, __u32 report_type, __u32 report_id, __u32 field_index, __u32 ucode, bool require_all_match) { bool debug = false; if (debug) printf("(%s) report_type=%d, report_id=%d, field index=%d, ucode=0x%08x, require_all_match=%s\n", __func__, report_type, report_id, field_index, ucode, sbool(require_all_match)); struct hiddev_field_info * result = NULL; int rc; struct hiddev_field_info finfo = { .report_type = report_type, .report_id = report_id, .field_index = field_index }; int saved_field_index = field_index; rc = ioctl(fd, HIDIOCGFIELDINFO, &finfo); if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGFIELDINFO", errno); goto bye; } if (debug) { if (finfo.field_index != saved_field_index && debug) printf("(%s) !!! ioctl(HIDIOCGFIELDINFO) changed field_index from %d to %d\n", __func__, saved_field_index, finfo.field_index); } // result->field_id = fndx; bool is_matched = false; if (require_all_match) { __u32 ucode_found = hiddev_get_identical_ucode(fd, &finfo, field_index); if (ucode_found == ucode) is_matched = true; } else { // loop over all usage codes int undx; for (undx = 0; undx < finfo.maxusage; undx++) { struct hiddev_usage_ref uref = { .report_type = report_type, .report_id = report_id, .field_index = field_index, .usage_index = undx }; rc = ioctl(fd, HIDIOCGUCODE, &uref); // Fills in usage code if (rc != 0) { REPORT_USB_IOCTL_ERROR("HIDIOCGUCODE", errno); break; } if (uref.usage_code == ucode) { is_matched = true; break; } } // loop over usages } if (is_matched) { result = malloc(sizeof(struct hiddev_field_info)); memcpy(result, &finfo, sizeof(struct hiddev_field_info)); } bye: if (debug) { printf("(%s) Returning: %p\n", __func__, result); if (result) dbgrpt_hiddev_field_info(result, 1); } return result; } /* Look through all reports of a given type (HID_REPORT_TYPE_FEATURE, etc) to * find one having a field with a given usage code. * * Arguments: * fd file descriptor of open hiddev device * report_type HID_REPORT_TYPE_INPUT, HID_REPORT_TYPE_OUTPUT, or HID_REPORT_TYPE_FEATURE * ucode usage code * match_all_ucodes if true, all usages of the field must match ucode * if false, at least one usage must match ucode * * Returns: record identifying the report and field */ struct hid_field_locator* hiddev_find_report(int fd, __u32 report_type, __u32 ucode, bool match_all_ucodes) { bool debug = false; if (debug) printf("(%s) Starting. report_type=%d, ucode=0x%08x, match_all_ucodes=%s\n", __func__, report_type, ucode, sbool(match_all_ucodes)); struct hid_field_locator * result = NULL; struct hiddev_report_info rinfo = { .report_type = report_type, .report_id = HID_REPORT_ID_FIRST }; int report_id_found = -1; int field_index_found = -1; struct hiddev_field_info * finfo_found = NULL; int reportinfo_rc = 0; //while (reportinfo_rc == 0 && report_id_found == -1) { while (reportinfo_rc == 0 && !finfo_found) { // printf("(%s) Report counter %d, report_id = 0x%08x %s\n", // __func__, rptct, rinfo.report_id, interpret_report_id(rinfo.report_id)); errno = 0; reportinfo_rc = ioctl(fd, HIDIOCGREPORTINFO, &rinfo); if (reportinfo_rc != 0) { // no more reports if (reportinfo_rc != -1) REPORT_USB_IOCTL_ERROR("HIDIOCGREPORTINFO", errno); break; } for (int fndx = 0; fndx < rinfo.num_fields && field_index_found == -1; fndx++) { // finfo_found = is_field_edid(fd, &rinfo, fndx); // *** TEMP *** FORCE FAILURE finfo_found = test_field_ucode(fd, report_type, rinfo.report_id, fndx, ucode, match_all_ucodes); if (finfo_found) { report_id_found = rinfo.report_id; field_index_found = fndx; break; } } rinfo.report_id |= HID_REPORT_ID_NEXT; } // loop over reports // assert( (report_id_found >= 0 && finfo_found ) || // (report_id_found == -1 && !finfo_found ) ); if (finfo_found) { // if (report_id_found >= 0) { result = calloc(1, sizeof(struct hid_field_locator)); // result->rinfo = calloc(1, sizeof(struct hiddev_report_info)); // memcpy(result->rinfo, &rinfo, sizeof(struct hiddev_report_info)); result->finfo = finfo_found; // returned by is_field_edid() or test_field_ucode() result->report_type = rinfo.report_type; result->report_id = report_id_found; result->field_index = field_index_found; // finfo.field_index may have been changed by HIDIOGREPORTINFO } if (debug) { if (result) { printf("(%s) Returning: %p\n", __func__, result); printf("(%s) report_id=%d, field_index=%d\n", __func__, result->report_id, result->field_index); // report_hid_field_locator(result, 1); } else printf("(%s) Returning NULL", __func__); } return result; } /* Finds the report describing the EDID. * * Arguments: * fd file descriptor of open hiddev device * * Returns: pointer to newly allocated struct hid_field_locator representing * the feature report and field within that report that returns * the EDID, * NULL if not found * * It is the responsibility of the caller to free the returned struct. */ struct hid_field_locator * locate_edid_report(int fd) { bool debug = false; struct hid_field_locator* result = NULL; result = hiddev_find_report(fd, HID_REPORT_TYPE_FEATURE, 0x00800002, /*match_all_ucodes=*/true); if (result) { // find_report() should have parm specifying minimum number of usages if (result->finfo->maxusage < 128) { printf("(%s) Located report contains less than 128 usages. Discarding.\n", __func__); free_hid_field_locator(result); result = NULL; } } if (debug) { if (result) { printf("(%s) Returning %p report_id=%d, field_index=%d\n", __func__, result, result->report_id, result->field_index); // report_hid_field_locator(result, 1); } else printf("(%s) Returning NULL", __func__); } return result; } // // Get multibyte value // /* Base function for retrieving a multibyte field value using a * call to HIDIOCGUSAGES. The value to be retrieved is specified * using a struct hiddev_usage_ref_multi. * * Arguments: * fd file descriptor of open hiddev device * uref_multi specifies value to be retrieve, and buffer * in which to return bytes * * Returns: * pointer to Buffer struct containing the value, NULL if error * * It is the responsibility of the caller to free the returned buffer. */ Buffer * get_multibyte_value_by_uref_multi( int fd, struct hiddev_usage_ref_multi * uref_multi ) { bool debug = false; if (debug) { printf("(%s) Starting. fd=%d, uref_multi=%p\n", __func__, fd, uref_multi); dbgrpt_hiddev_usage_ref_multi(uref_multi, 1); } int rc; Buffer * result = NULL; #ifndef NDEBUG __u32 report_type = uref_multi->uref.report_type; assert(report_type == HID_REPORT_TYPE_FEATURE || report_type == HID_REPORT_TYPE_INPUT); // *** CG19 *** #endif rc = ioctl(fd, HIDIOCGUSAGES, uref_multi); // Fills in usage value if (rc != 0) { if (errno == EINVAL) { if (debug) printf("(%s) ioctl(HIDIOCGUSAGES) returned EINVAL\n", __func__); } else REPORT_USB_IOCTL_ERROR("HIDIOCGUSAGES", errno); goto bye; } result = buffer_new(uref_multi->num_values, __func__); for (int ndx=0; ndxnum_values; ndx++) buffer_add(result, uref_multi->values[ndx] & 0xff); bye: if (debug) { printf("Returning: %p\n", result); if (result) { buffer_dump(result); } } return result; } /* Retrieve the bytes of a multibyte field value using a * call to HIDIOCGUSAGES. The field to be retrieved is * specified using a struct hid_field_locator. * * Arguments: * fd file descriptor of open hiddev device * loc pointer to hid_field_locator struct * * Returns: * pointer to Buffer struct containing the value, NULL if error * * It is the responsibility of the caller to free the returned buffer. */ Buffer * hiddev_get_multibyte_report_value_by_hid_field_locator( int fd, struct hid_field_locator * loc) { bool debug = false; if (debug) { printf("(%s) Starting. hid_field_locator=%p\n", __func__, loc); // report_hid_field_locator(loc, 1); } Buffer * result = NULL; struct hiddev_report_info rinfo; rinfo.report_type = loc->report_type; rinfo.report_id = loc->report_id; rinfo.num_fields = 0; // initialize to avoid valgrind warning int rc = ioctl(fd, HIDIOCGREPORT, &rinfo); if (rc != 0) { if (errno == EINVAL) { if (debug) printf("(%s) ioctl(HIDIOCGUSAGES) returned EINVAL\n", __func__); } else REPORT_USB_IOCTL_ERROR("HIDIOCGREPORT", errno); goto bye; } struct hiddev_usage_ref_multi uref_multi; memset(&uref_multi, 0, sizeof(uref_multi)); // initialize all fields to make valgrind happy uref_multi.uref.report_type = loc->report_type; uref_multi.uref.report_id = loc->report_id; uref_multi.uref.field_index = loc->field_index; uref_multi.uref.usage_index = 0; uref_multi.uref.usage_code = 0; uref_multi.num_values = loc->finfo->maxusage; result = get_multibyte_value_by_uref_multi(fd, &uref_multi); bye: if (debug) printf("(%s) Returning: %p\n", __func__, result); return result; } /* Retrieve the bytes of a multibyte field value using a call to HIDIOCGUSAGES. * It is left to hiddev to determine the correct report of the specified report * type to use to get the value of the specified usage code. * * Arguments: * fd file descriptor of open hiddev device * report_type HID_REPORT_TYPE_FEATURE or HID_REPORT_TYPE_INPUT * usage_code usage code to retrieve * num_values number of bytes * * Returns: * pointer to Buffer struct containing the value, NULL if error * * It is the responsibility of the caller to free the returned buffer. */ Buffer * hiddev_get_multibyte_value_by_report_type_and_ucode( int fd, __u32 report_type, __u32 usage_code, __u32 num_values) { bool debug = false; if (debug) printf("(%s) Starting. fd=%d, report_type=%d, usage_code=0x%08x, num_values=%d\n", __func__, fd, report_type, usage_code, num_values); Buffer * result = NULL; assert(report_type == HID_REPORT_TYPE_FEATURE || report_type == HID_REPORT_TYPE_INPUT); struct hiddev_usage_ref_multi uref_multi; memset(&uref_multi, 0, sizeof(uref_multi)); // initialize all fields to make valgrind happy uref_multi.uref.report_type = report_type; uref_multi.uref.report_id = HID_REPORT_ID_UNKNOWN; uref_multi.uref.usage_code = usage_code; uref_multi.num_values = num_values; // needed? yes! result = get_multibyte_value_by_uref_multi(fd, &uref_multi); if (debug) printf("(%s) Returning: %p\n", __func__, result); return result; } /* Retrieve the bytes of a multibyte field value using a call to HIDIOCGUSAGES. * It is left to hiddev to determine the correct report to use to get the value * of the specified usage code. Both Feature and Input reports are tried. * * This function first tries to get a value using a feature report. * If that fails, an input report is tried. * * Arguments: * fd file descriptor of open hiddev device * usage_code usage code to retrieve * num_values number of bytes * * Returns: * pointer to Buffer struct containing the value * * It is the responsibility of the caller to free the returned buffer. */ Buffer * hiddev_get_multibyte_value_by_ucode(int fd,__u32 usage_code, __u32 num_values) { Buffer * result = hiddev_get_multibyte_value_by_report_type_and_ucode( fd, HID_REPORT_TYPE_FEATURE, usage_code, num_values); if (!result) result = hiddev_get_multibyte_value_by_report_type_and_ucode( fd, HID_REPORT_TYPE_INPUT, usage_code, num_values); return result; } /* Retrieves the EDID (128 bytes) from a hiddev device representing a HID * compliant monitor. * * Arguments: * fd file descriptor * * Returns: * pointer to Buffer struct containing the EDID * * It is the responsibility of the caller to free the returned buffer. */ Buffer * hiddev_get_edid(int fd) { bool debug = false; if (debug) printf("(%s) Starting\n", __func__); Buffer * result = NULL; struct hid_field_locator * loc = locate_edid_report(fd); if (loc) { result = hiddev_get_multibyte_report_value_by_hid_field_locator(fd, loc); free_hid_field_locator(loc); } if (debug) printf("(%s) Returning: %p\n", __func__, result); return result; } // // *** Miscellaneous functions *** // /* Returns the name of a hiddev device, as reported by ioctl HIDIOCGNAME. * * Arguments: * fd file descriptor of open hiddev device * * Returns: pointer to newly allocated string, * NULL if ioctl call fails (should never happen) */ char * get_hiddev_name(int fd) { bool debug = false; if (debug) printf("(%s) Starting. fd=%d\n", __func__, fd); const int blen = 256; char buf1[blen]; for (int ndx=0; ndx < blen; ndx++) buf1[ndx] = '\0'; // initialize to avoid valgrind warning // returns length of result, including terminating null int rc = ioctl(fd, HIDIOCGNAME(blen), buf1); // printf("(%s) HIDIOCGNAME returned %d\n", __func__, rc); // hex_dump(buf1,64); char * result = NULL; if (rc >= 0) result = g_strdup(buf1); if (debug) printf("(%s) Returning |%s|\n", __func__, result); return result; } ddcutil-2.2.0/src/usb_util/hidraw_util.c0000644000175000001440000002512714754576332013743 /** @file hidraw_util.c */ // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "util/coredefs.h" #include "util/file_util.h" #include "util/glib_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/udev_util.h" #include "util/udev_usb_util.h" #include "usb_util/base_hid_report_descriptor.h" #include "usb_util/hid_report_descriptor.h" #include "usb_util/usb_hid_common.h" #include "usb_util/hidraw_util.h" // // *** Functions to identify hidraw devices representing monitors *** // /* Filter to find hiddevN files for scandir() */ static int is_hidraw(const struct dirent *ent) { return !strncmp(ent->d_name, "hidraw", strlen("hidraw")); } GPtrArray * get_hidraw_device_names_using_filesys() { const char *hidraw_paths[] = { "/dev/", NULL }; // Dirent_Filter filterfunc = is_hidraw; return get_filenames_by_filter(hidraw_paths, is_hidraw); } // // Utility functions // const char * bus_str(int bus) { switch (bus) { case BUS_USB: return "USB"; break; case BUS_HIL: return "HIL"; break; case BUS_BLUETOOTH: return "Bluetooth"; break; case BUS_VIRTUAL: return "Virtual"; break; default: return "Other"; break; } } // // Probe hidraw devices // void probe_hidraw_device(char * devname, bool show_monitors_only, int depth) { bool debug = false; puts(""); rpt_vstring(depth, "Probing device %s", devname); // printf("(%s) %s\n", __func__, devname); int d1 = depth+1; int d2 = depth+2; int fd; // int i; int res, desc_size = 0; Byte buf[1024] = {0}; // initialize to avoid valgrind warning struct hidraw_report_descriptor rpt_desc; struct hidraw_devinfo info; memset(&rpt_desc, 0x0, sizeof(rpt_desc)); memset(&info, 0x0, sizeof(info)); // memset(buf, 0x0, sizeof(buf)); /* Open the Device with non-blocking reads. In real life, don't use a hard coded path; use libudev instead. */ fd = open(devname, O_RDWR|O_NONBLOCK); // open() returns < 0 for error, > 0 if success, // assert() avoids coverity flagging resource leak assert(fd != 0); if (fd < 0) { rpt_vstring(depth, "Unable to open device %s: %s", devname, strerror(errno)); Usb_Detailed_Device_Summary * devsum = lookup_udev_usb_device_by_devname(devname, true); if (devsum) { // report_usb_detailed_device_summary(devsum, 2); rpt_vstring(d1, "USB bus %s, device %s, vid:pid: %s:%s - %s:%s", devsum->busnum_s, devsum->devnum_s, devsum->vendor_id, devsum->product_id, devsum->vendor_name, devsum->product_name); free_usb_detailed_device_summary(devsum); } goto bye; } /* Get Raw Name */ res = ioctl(fd, HIDIOCGRAWNAME(256), buf); if (res < 0) { perror("HIDIOCGRAWNAME"); goto bye; } rpt_vstring(d1, "Raw Name: %s", buf); /* Get Physical Location */ res = ioctl(fd, HIDIOCGRAWPHYS(256), buf); if (res < 0) { perror("HIDIOCGRAWPHYS"); goto bye; } rpt_vstring(d1, "Raw Phys: %s", buf); /* Get Raw Info */ res = ioctl(fd, HIDIOCGRAWINFO, &info); if (res < 0) { perror("HIDIOCGRAWINFO"); goto bye; } rpt_vstring(d1, "Raw Info:"); rpt_vstring(d2, "bustype: %d (%s)", info.bustype, bus_str(info.bustype)); rpt_vstring(d2, "vendor: 0x%04hx", info.vendor); rpt_vstring(d2, "product: 0x%04hx", info.product); // Get bus and device numbers using udev since hidraw doesn't report it char * simple_devname = strstr(devname, "hidraw"); Udev_Usb_Devinfo * dinfo = get_udev_usb_devinfo("hidraw", simple_devname); if (dinfo) { rpt_vstring(d1, "Busno:Devno as reported by get_udev_usb_devinfo() for %s: %03d:%03d", simple_devname, dinfo->busno, dinfo->devno); free(dinfo); } else rpt_vstring(d1, "Error getting busno:devno using get_udev_usb_devinfo()"); /* Get Report Descriptor Size */ // why is this necessary? buffer in rpt_desc is already HID_MAX_DESCRIPTOR_SIZE? res = ioctl(fd, HIDIOCGRDESCSIZE, &desc_size); if (res < 0) { perror("HIDIOCGRDESCSIZE"); goto bye; } if (debug) rpt_vstring(d1, "Report Descriptor Size: %d", desc_size); // bool is_monitor = false; /* Get Report Descriptor */ rpt_desc.size = desc_size; res = ioctl(fd, HIDIOCGRDESC, &rpt_desc); if (res < 0) { perror("HIDIOCGRDESC"); goto bye; } if (debug) { rpt_vstring(d1, "Report Descriptor:"); // for (i = 0; i < rpt_desc.size; i++) // printf("%hhx ", rpt_desc.value[i]); // puts("\n"); rpt_hex_dump(rpt_desc.value, rpt_desc.size, d2); } Hid_Report_Descriptor_Item * report_item_list = tokenize_hid_report_descriptor(rpt_desc.value, rpt_desc.size) ; // report_hid_report_item_list(report_item_list, d2); bool is_monitor = is_monitor_by_tokenized_hid_report_descriptor(report_item_list); #ifdef OLD Hid_Report_Descriptor_Item * cur_item = report_item_list; // Look at the first Usage Page item, is it USB Monitor? while (cur_item) { if (cur_item->btag == 0x04) { if (cur_item->data == 0x80) is_monitor = true; break; } cur_item = cur_item->next; } #endif rpt_vstring(d1, "%s a USB connected monitor", (is_monitor) ? "Is" : "Not"); if (!is_monitor && show_monitors_only) { is_monitor = force_hid_monitor_by_vid_pid( info.vendor, info.product); if (is_monitor) rpt_vstring(d1, "Device vid/pid matches exception list. Forcing report for device."); } Parsed_Hid_Descriptor * phd = NULL; if (is_monitor || !show_monitors_only) { rpt_vstring(d1,"Tokenized report descriptor:"); report_hid_report_item_list(report_item_list, d2); } if (is_monitor) { puts(""); phd = parse_hid_report_desc(rpt_desc.value, rpt_desc.size); Parsed_Hid_Report * edid_report = find_edid_report_descriptor(phd); if (edid_report) { rpt_title("Report descriptor for EDID:", d1); summarize_parsed_hid_report(edid_report, d2); } else rpt_title("No EDID report descriptor found!!!", d1); puts(""); GPtrArray * feature_reports = get_vcp_code_reports(phd); if (feature_reports && feature_reports->len > 0) { rpt_title("Report descriptors for VCP features:", d1); summarize_vcp_code_report_array(feature_reports, d2); } else rpt_title("No VCP Feature report descriptors found!!!", d1); GPtrArray * reports = select_parsed_hid_report_descriptors(phd, HIDF_REPORT_TYPE_FEATURE); if (reports->len == 0) { puts(""); rpt_title("No HID reports exist of type HIDF_REPORT_TYPE_FEATURE.", d1); } for (int ndx = 0; ndx < reports->len; ndx++) { Parsed_Hid_Report * a_report = g_ptr_array_index(reports, ndx); puts(""); rpt_vstring(d1, "HID Feature report id: %3d 0x%02x", a_report->report_id, a_report->report_id); rpt_vstring(d1, "Parsed report description:"); dbgrpt_parsed_hid_report(a_report, d2); /* Get Feature */ buf[0] = a_report->report_id; /* Report Number */ res = ioctl(fd, HIDIOCGFEATURE(1024), buf); if (res < 0) { perror("HIDIOCGFEATURE"); } else { // printf("ioctl HIDIOCGFEATURE returned: %d\n", res); rpt_vstring(d1,"Report data:"); rpt_vstring(d1, "Per hidraw.h: The first byte of SFEATURE and GFEATURE is the report number"); rpt_hex_dump(buf, res, d2); } } free_parsed_hid_descriptor(phd); // not defined, but need to free phd } free_hid_report_item_list(report_item_list); bye: if (fd > 0) close(fd); } /* Indicates if a hidraw device represents a monitor. * * Arguments: * devname device name, e.g. /dev/hidraw3 * * Returns: true/false * */ bool hidraw_is_monitor_device(char * devname) { bool debug = false; if (debug) printf("(%s) 'Checking device %s\n", __func__, devname); bool is_monitor = false; int fd; int res, desc_size = 0; Byte buf[1024]; // TODO: maximum report size struct hidraw_report_descriptor rpt_desc; // struct hidraw_devinfo info; /* Open the Device with non-blocking reads. In real life, don't use a hard coded path; use libudev instead. */ fd = open(devname, O_RDWR|O_NONBLOCK); if (fd < 0) { perror("Unable to open device"); goto bye; } memset(&rpt_desc, 0x0, sizeof(rpt_desc)); // memset(&info, 0x0, sizeof(info)); memset(buf, 0x0, sizeof(buf)); /* Get Report Descriptor Size */ res = ioctl(fd, HIDIOCGRDESCSIZE, &desc_size); if (res < 0) { perror("HIDIOCGRDESCSIZE"); goto bye; } /* Get Report Descriptor */ rpt_desc.size = desc_size; res = ioctl(fd, HIDIOCGRDESC, &rpt_desc); if (res < 0) { perror("HIDIOCGRDESC"); goto bye; } Hid_Report_Descriptor_Item * report_item_list = tokenize_hid_report_descriptor(rpt_desc.value, rpt_desc.size) ; // report_hid_report_item_list(report_item_list, 2); is_monitor = is_monitor_by_tokenized_hid_report_descriptor(report_item_list); free_hid_report_item_list(report_item_list); bye: if (fd >= 0) // really shouldn't be closing 0..2 stdin..stderr, but coverity complains close(fd); if (debug) printf("(%s) devname=%s, returning %s\n", __func__, devname, sbool(is_monitor)); return is_monitor; } /* Probes hidraw devices. * * Arguments: * show_monitors_only show detailed information only for monitors * depth logical indentation depth * * Returns: nothing */ void probe_hidraw(bool show_monitors_only, int depth) { GPtrArray * hidraw_names = get_hidraw_device_names_using_filesys(); rpt_vstring(depth, "Found %d USB HID devices.", hidraw_names->len); for (int ndx = 0; ndx < hidraw_names->len; ndx++) { char * devname = g_ptr_array_index(hidraw_names, ndx); // printf("(%s) Probing %s...\n", __func__, devname); probe_hidraw_device(devname, true, depth); } g_ptr_array_free(hidraw_names, true); } ddcutil-2.2.0/src/usb_util/libusb_reports.c0000644000175000001440000012361714441414365014457 /** \file libusb_reports.c * * Report libusb data structures * * libusb is not currently used by ddcutil. This code is retained for reference. */ // Copyright (C) 2014-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later // // Portions adapted from lsusb.c (command lsusb) by Thomas Sailer and David Brownell // Adapted from usbplay2 file libusb_util.c #include #include #include #include #include // HID_MAX_DESCRIPTOR_SIZE is here on Mint #include // for HID_MAX_DESCRIPTOR_SIZE #include #include #include #include #include // #include #include "util/data_structures.h" #include "util/string_util.h" #include "util/report_util.h" #include "util/device_id_util.h" #include "usb_util/base_hid_report_descriptor.h" #include "usb_util/hid_report_descriptor.h" #include "usb_util/usb_hid_common.h" #include "usb_util/libusb_reports.h" // // Identifier to name tables // Value_Name class_id_table[] = { {LIBUSB_CLASS_PER_INTERFACE, "LIBUSB_CLASS_PER_INTERFACE"}, VN(LIBUSB_CLASS_AUDIO), // {0xff,NULL}, VN_END }; Value_Name_Title class_code_table[] = { /** In the context of a \ref libusb_device_descriptor "device descriptor", * LIBUSB_CLASS_PER_INSTANCE indicates that each interface specifies its * own class information and all interfaces operate independently. */ VNT( LIBUSB_CLASS_PER_INTERFACE, "Per interface"), // 0 VNT( LIBUSB_CLASS_AUDIO, "Audio"), // 1 VNT( LIBUSB_CLASS_COMM, "Communications"), // 2 VNT( LIBUSB_CLASS_HID, "Human Interface Device"), // 3 VNT( LIBUSB_CLASS_PHYSICAL, "Physical device"), // 5 VNT( LIBUSB_CLASS_PRINTER, "Printer"), // 7 VNT( LIBUSB_CLASS_IMAGE, "Image"), // 6 VNT( LIBUSB_CLASS_MASS_STORAGE, "Mass storage"), // 8 VNT( LIBUSB_CLASS_HUB, "Hub"), // 9 VNT( LIBUSB_CLASS_DATA, "Data"), // 10 VNT( LIBUSB_CLASS_SMART_CARD, "Smart card"), // 0x0b VNT( LIBUSB_CLASS_CONTENT_SECURITY, "Content security"), // 0x0d VNT( LIBUSB_CLASS_VIDEO, "Video"), // 0x0e VNT( LIBUSB_CLASS_PERSONAL_HEALTHCARE, "Personal healthcare"), // 0x0f VNT( LIBUSB_CLASS_DIAGNOSTIC_DEVICE, "Diagnostic device"), // 0xdc VNT( LIBUSB_CLASS_WIRELESS, "Wireless"), // 0xe0 VNT( LIBUSB_CLASS_APPLICATION, "Application"), // 0xfe VNT( LIBUSB_CLASS_VENDOR_SPEC, "Vendor specific"), // 0xff VNT_END }; Value_Name_Title descriptor_type_table[] = { VNT( LIBUSB_DT_DEVICE, "Device"), // 0x01 VNT( LIBUSB_DT_CONFIG, "Configuration"), // 0x02 VNT( LIBUSB_DT_STRING, "String"), // 0x03 VNT( LIBUSB_DT_INTERFACE, "Interface"), // 0x04 VNT( LIBUSB_DT_ENDPOINT, "Endpoint"), // 0x05 VNT( LIBUSB_DT_BOS, "BOS" ), // 0x0f, VNT( LIBUSB_DT_DEVICE_CAPABILITY, "Device Capability"), // 0x10, VNT( LIBUSB_DT_HID, "HID"), // 0x21, VNT( LIBUSB_DT_REPORT, "HID report"), // 0x22, VNT( LIBUSB_DT_PHYSICAL, "Physical"), // 0x23, VNT( LIBUSB_DT_HUB, "Hub"), // 0x29, VNT( LIBUSB_DT_SUPERSPEED_HUB, "SuperSpeed Hub"), // 0x2a, VNT( LIBUSB_DT_SS_ENDPOINT_COMPANION, "SuperSpeed Endpoint Companion"), // 0x30 VNT_END }; #ifdef REF /** \ingroup desc * Endpoint direction. Values for bit 7 of the * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme. */ enum libusb_endpoint_direction { /** In: device-to-host */ LIBUSB_ENDPOINT_IN = 0x80, /** Out: host-to-device */ LIBUSB_ENDPOINT_OUT = 0x00 }; #endif Value_Name_Title endpoint_direction_table[] = { VNT( LIBUSB_ENDPOINT_IN, "IN"), VNT( LIBUSB_ENDPOINT_OUT, "OUT"), VNT_END }; #ifdef REF #define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */ /** \ingroup desc * Endpoint transfer type. Values for bits 0:1 of the * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field. */ enum libusb_transfer_type { /** Control endpoint */ LIBUSB_TRANSFER_TYPE_CONTROL = 0, /** Isochronous endpoint */ LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1, /** Bulk endpoint */ LIBUSB_TRANSFER_TYPE_BULK = 2, /** Interrupt endpoint */ LIBUSB_TRANSFER_TYPE_INTERRUPT = 3, /** Stream endpoint */ LIBUSB_TRANSFER_TYPE_BULK_STREAM = 4, }; #endif // Problem: LIBUSB_TRANFER_TYPE_BULK_STREAM not defined in 1.0.17 #define LIBUSB_TRANSFER_TYPE_BULK_STREAM_LOCAL 4 Value_Name_Title transfer_type_table[] = { VNT(LIBUSB_TRANSFER_TYPE_CONTROL, "Control"), // 0 VNT(LIBUSB_TRANSFER_TYPE_ISOCHRONOUS, "Isochronous"), // 1 VNT(LIBUSB_TRANSFER_TYPE_BULK, "Bulk"), // 2 VNT(LIBUSB_TRANSFER_TYPE_INTERRUPT, "Interrupt"), // 3 VNT(LIBUSB_TRANSFER_TYPE_BULK_STREAM_LOCAL, "Bulk Stream"), // 4 VNT_END }; char * descriptor_title(Byte val) { return vnt_title(descriptor_type_table, val); } char * endpoint_direction_title(Byte val) { return vnt_title(endpoint_direction_table, val); } char * transfer_type_title(Byte val) { return vnt_title(transfer_type_table, val); } char * class_code_title(Byte val) { return vnt_title(class_code_table, val); } // // Misc Utilities // #define LIBUSB_STRING_BUFFER_SIZE 100 char libusb_string_buffer[LIBUSB_STRING_BUFFER_SIZE]; char * lookup_libusb_string(struct libusb_device_handle * dh, int string_id) { int rc = libusb_get_string_descriptor_ascii( dh, string_id, (unsigned char *) libusb_string_buffer, LIBUSB_STRING_BUFFER_SIZE); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_get_string_descriptor_ascii", rc); strcpy(libusb_string_buffer, ""); } else { // 7/2017: assert was triggered by user, why? // replace assert by diagnostic message if (rc != strlen(libusb_string_buffer)) { printf("(%s) rc=%d, LIBUSB_STRING_BUFFER_SIZE=%d, strlen=%zu, value=|%s|\n", __func__, rc, LIBUSB_STRING_BUFFER_SIZE, strlen(libusb_string_buffer), libusb_string_buffer ); } } return libusb_string_buffer; } #ifdef UNUSED // unused, and requires include of wchar.h wchar_t libusb_string_buffer_wide[LIBUSB_STRING_BUFFER_SIZE]; wchar_t * lookup_libusb_string_wide(struct libusb_device_handle * dh, int string_id) { int rc = libusb_get_string_descriptor( dh, string_id, 33, // US English (unsigned char *) libusb_string_buffer_wide, // N. CAST LIBUSB_STRING_BUFFER_SIZE); if (rc < 0) { REPORT_LIBUSB_ERROR("libusb_get_string_descriptor_wide", rc, LIBUSB_CONTINUE); wcscpy(libusb_string_buffer_wide, L""); } else { // printf("(%s) rc=%d, wcslen(libusb_string_buffer_wide)=%d, strlen=%d\n", // __func__, rc, wcslen(libusb_string_buffer_wide), strlen(libusb_string_buffer_wide) ); // assert(rc == wcslen(libusb_string_buffer)); } return (wchar_t *) libusb_string_buffer; } #endif // from lsusb.c /* ---------------------------------------------------------------------- */ /* workaround libusb API goofs: "byte" should never be sign extended; * using "char" is trouble. Likewise, sizes should never be negative. */ static inline int typesafe_control_msg( libusb_device_handle * dev, unsigned char requesttype, unsigned char request, int value, int idx, unsigned char * bytes, unsigned size, int timeout) { int ret = libusb_control_transfer( dev, requesttype, request, value, idx, bytes, size, timeout); if (ret < 0) return -ret; else return ret; } #define usb_control_msg typesafe_control_msg // // Report functions for libusb data structures // void report_libusb_endpoint_descriptor( const struct libusb_endpoint_descriptor * epdesc, libusb_device_handle * dh, // may be null int depth) { int d1 = depth+1; rpt_structure_loc("libusb_endpoint_descriptor", epdesc, depth); rpt_vstring(d1, "%-20s 0x%02x %s", "bDescriptorType:", epdesc->bDescriptorType, descriptor_title(epdesc->bDescriptorType) ); /** bEndpointAddress: The address of the endpoint described by this descriptor. Bits 0:3 are * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction, * see \ref libusb_endpoint_direction. */ unsigned char endpoint_number = epdesc->bEndpointAddress & 0x0f; char * direction_name = (epdesc->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ? "IN" : "OUT"; rpt_vstring(d1, "%-20s 0x%02x Endpoint number: %d Direction: %s", "bEndpointAddress:", epdesc->bEndpointAddress, endpoint_number, direction_name); /** Attributes which apply to the endpoint when it is configured using * the bConfigurationValue. Bits 0:1 determine the transfer type and * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for * isochronous endpoints and correspond to \ref libusb_iso_sync_type. * Bits 4:5 are also only used for isochronous endpoints and correspond to * \ref libusb_iso_usage_type. Bits 6:7 are reserved. */ // uint8_t bmAttributes; Byte transfer_type = epdesc->bmAttributes & 0x03; // Byte isoc_sync_type = epdesc->bmAttributes & 0x0c; // unused // Byte isoc_iso_usage_type = epdesc->bmAttributes & 0x30; // unused rpt_vstring(d1, "%-20s 0x%02x Transfer Type: %s", "bmAttributes:", epdesc->bmAttributes, transfer_type_title(transfer_type) ); /** Maximum packet size this endpoint is capable of sending/receiving. */ // uint16_t wMaxPacketSize; rpt_vstring(d1, "%-20s %u", "wMaxPacketSize:", epdesc->wMaxPacketSize); /** Interval for polling endpoint for data transfers. */ // uint8_t bInterval; rpt_vstring(d1, "%-20s %d %s", "bInterval", epdesc->bInterval, "(data transfer polling interval)" ); // skipping several /** Length of the extra descriptors, in bytes. */ // int extra_length; rpt_vstring(d1, "%-20s %d (length of extra descriptors)", "extra_length:", epdesc->extra_length); } // from lsusb.c /* Read a control message * * Arguments: * dh libusb display handle * bmRequestType * bRequest * wValue * wIndex bInterfaceNumber parm * dbuf pointer to buffer * dbufsz buffer size * WLength number of bytes to try to read * pbytes_read return number of bytes actually read here * * Returns: true if success, false if not */ bool call_read_control_msg( struct libusb_device_handle * dh, uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, // = bInterfaceNumber Byte * dbuf, // data uint16_t dbufsz, uint16_t wLength, // report length int * pbytes_read) { bool debug = false; if (debug) printf("(%s) Starting\n", __func__); assert(dh); assert( dbufsz >= wLength); // const int CTRL_RETRIES = 2; const int CTRL_TIMEOUT = (5*1000); /* milliseconds */ bool ok = false; int bytes_read = 0; uint16_t bInterfaceNumber = wIndex; uint16_t rptlen = wLength; int rc = libusb_claim_interface(dh, bInterfaceNumber); if (rc != 0) { // TODO: replace w proper diagnostic message using libusb functions printf("(%s) libusb_claim_inteface returned %d\n", __func__, rc); goto bye; } int retries = 4; while (bytes_read < rptlen && retries--) { bytes_read = usb_control_msg( dh, bmRequestType, bRequest, wValue, bInterfaceNumber, // = wIndex dbuf, rptlen, // = wLength CTRL_TIMEOUT); } if (bytes_read > 0) { ok = true; } libusb_release_interface(dh, bInterfaceNumber); bye: *pbytes_read = bytes_read; if (debug) printf("(%s) Returning: %s, *pbytes_read=%d\n", __func__, sbool(ok), *pbytes_read); return ok; } /* Get bytes of HID Report Descriptor * * Arguments: * dh * bInterfaceNumber * rptlen * dbuf * dbufsz * * Returns: true if success, false if not */ bool get_raw_report_descriptor( struct libusb_device_handle * dh, uint8_t bInterfaceNumber, uint16_t rptlen, // report length Byte * dbuf, int dbufsz, int * pbytes_read) { bool ok = false; assert(dh); ok = call_read_control_msg( dh, // dev_handle LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_INTERFACE, // bmRequestType LIBUSB_REQUEST_GET_DESCRIPTOR, // bRequest LIBUSB_DT_REPORT << 8 | 0x0, // wValue - the value field for the setup packet bInterfaceNumber, // ?? wIndex - index field for the setup packet ??? dbuf, // data dbufsz, rptlen, // wLength pbytes_read ); if (ok && *pbytes_read < rptlen) { printf(" Warning: incomplete report descriptor\n"); // dump_report_desc(dbuf, *pbytes_read); // old way } return ok; } // TODO: move to more appropriate location // HID Class-Specific Requests values. See section 7.2 of the HID specifications #define HID_GET_REPORT 0x01 #define HID_GET_IDLE 0x02 #define HID_GET_PROTOCOL 0x03 #define HID_SET_REPORT 0x09 #define HID_SET_IDLE 0x0A #define HID_SET_PROTOCOL 0x0B #ifdef ALREADY_DEFINED // defined in hid_report_descriptor.h #define HID_REPORT_TYPE_INPUT 0x01 #define HID_REPORT_TYPE_OUTPUT 0x02 #define HID_REPORT_TYPE_FEATURE 0x03 #endif /* Get bytes of HID Feature Report * * Arguments: * dh libusb device handle * bInterfaceNumber interface number * report_id feature report number * rptlen bytes requested (may be larger than actual report size) * dbuf pointer to buffer * dbufsz buffer size * pbytes_read return number of bytes read here * * Returns: true if success, false if not */ bool get_raw_report( struct libusb_device_handle * dh, uint8_t bInterfaceNumber, uint8_t report_id, uint16_t rptlen, // report length Byte * dbuf, int dbufsz, int * pbytes_read) { bool ok = false; ok = call_read_control_msg( dh, // dev_handle LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, // bmRequestType HID_GET_REPORT, // bRequest HID_REPORT_TYPE_FEATURE << 8 | report_id, // wValue - the value field for the setup packet bInterfaceNumber, // ?? wIndex - index field for the setup packet ??? dbuf, // data dbufsz, rptlen, // wLength pbytes_read ); return ok; } /* Reports struct libusb_interface_descriptor * * Arguments: * inter pointer to libusb_interface_descriptor instance * dh display handle, not required but allows for additional information * depth logical indentation depth * * Returns: nothing */ void report_libusb_interface_descriptor( const struct libusb_interface_descriptor * inter, libusb_device_handle * dh, // may be null int depth) { int d1 = depth+1; rpt_structure_loc("libusb_interface_descriptor", inter, depth); /** Size of this descriptor (in bytes) */ // uint8_t bLength; rpt_vstring(d1, "%-20s %d", "bLength", inter->bLength); /** Descriptor type. Will have value * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE * in this context. */ // uint8_t bDescriptorType; rpt_vstring(d1, "%-20s 0x%02x %s", "bDescriptorType:", inter->bDescriptorType, descriptor_title(inter->bDescriptorType) ); /** Number of this interface */ // uint8_t bInterfaceNumber; rpt_vstring(d1, "%-20s %u", "bInterfaceNumber:", inter->bInterfaceNumber); /** Value used to select this alternate setting for this interface */ // uint8_t bAlternateSetting; rpt_vstring(d1, "%-20s %u", "bAlternateSetting:", inter->bAlternateSetting); /** Number of endpoints used by this interface (excluding the control * endpoint). */ // uint8_t bNumEndpoints; rpt_vstring(d1, "%-20s %u", "bNumEndpoints:", inter->bNumEndpoints); /** USB-IF class code for this interface. See \ref libusb_class_code. */ // uint8_t bInterfaceClass; rpt_vstring(d1, "%-20s %u (0x%02x) %s", "bInterfaceClass:", inter->bInterfaceClass, inter->bInterfaceClass, class_code_title(inter->bInterfaceClass) ); /** USB-IF subclass code for this interface, qualified by the * bInterfaceClass value */ // uint8_t bInterfaceSubClass; rpt_vstring(d1, "%-20s %u (0x%02x) %s", "bInterfaceSubClass:", inter->bInterfaceSubClass, inter->bInterfaceSubClass, ""); /** USB-IF protocol code for this interface, qualified by the * bInterfaceClass and bInterfaceSubClass values */ // uint8_t bInterfaceProtocol; rpt_vstring(d1, "%-20s %u (0x%02x) %s", "bInterfaceProtocol:", inter->bInterfaceProtocol, inter->bInterfaceProtocol, ""); // Index of string descriptor describing this interface: uint8_t iInterface; char * interface_name = ""; if (dh && inter->iInterface > 0) interface_name = lookup_libusb_string(dh, inter->iInterface); rpt_vstring(d1, "%-20s %d \"%s\" ", "iInterface", inter->iInterface, interface_name ); /** Array of endpoint descriptors. This length of this array is determined * by the bNumEndpoints field. */ // const struct libusb_endpoint_descriptor *endpoint; // NB: This is an array of endpoint descriptors, // not an array of pointers to endpoint descriptors // nor a pointer to array of pointers to endpoint descriptors int ndx = 0; for (ndx=0; ndxbNumEndpoints; ndx++) { const struct libusb_endpoint_descriptor *epdesc = &(inter->endpoint[ndx]); report_libusb_endpoint_descriptor(epdesc, dh, d1); } /** Extra descriptors. If libusb encounters unknown interface descriptors, * it will store them here, should you wish to parse them. */ // const unsigned char *extra; /** Length of the extra descriptors, in bytes. */ // int extra_length; rpt_vstring(d1, "%-20s %d (length of extra descriptors)", "extra_length:", inter->extra_length); if (inter->extra_length > 0) { rpt_vstring(d1, "extra at %p: ", inter->extra); rpt_hex_dump(inter->extra, inter->extra_length, d1); if (dh) { if (inter->bInterfaceClass == LIBUSB_CLASS_HID) { // 3 const Byte * cur_extra = inter->extra; int remaining_length = inter->extra_length; while (remaining_length > 0) { HID_Descriptor * cur_hid_desc = (HID_Descriptor *) cur_extra; assert(cur_hid_desc->bLength <= remaining_length); report_hid_descriptor(dh, inter->bInterfaceNumber, cur_hid_desc, d1); cur_extra += cur_hid_desc->bLength; remaining_length -= cur_hid_desc->bLength; } } } } } /* Reports struct libusb_interface * * Arguments: * inter pointer to libusb_interface instance * dh display handle, not required but allows for additional information * depth logical indentation depth * * Returns: nothing * * struct libusb_interface represents a collection of alternate settings for a * particular USB interface. It contains an array of interface descriptors, one * for each alternate settings. */ void report_libusb_interface( const struct libusb_interface * interface, libusb_device_handle * dh, // may be null int depth) { int d1 = depth+1; rpt_structure_loc("libusb_interface", interface, depth); // The number of alternate settings that belong to this interface rpt_vstring(d1, "%-20s %d (number of alternate settings for this interface)", "num_altsetting", interface->num_altsetting); // rpt_int("num_altsetting", NULL, interface->num_altsetting, d1); for (int ndx=0; ndxnum_altsetting; ndx++) { report_libusb_interface_descriptor(&interface->altsetting[ndx], dh, d1); } } /* Reports struct libusb_config_descriptor * * Arguments: * config pointer to libusb_config_descriptor instance * dh display handle, not required but allows for additional information * depth logical indentation depth * * Returns: nothing * * struct libusb_config_descriptor represents the standard USB configuration * descriptor. This descriptor is documented in section 9.6.3 of the USB 3.0 * specification. It contains multiple libusb_interface structs. * * All multiple-byte fields are represented in host-endian format. */ void report_libusb_config_descriptor( const struct libusb_config_descriptor * config, libusb_device_handle * dh, // may be null int depth) { int d1 = depth+1; rpt_structure_loc("libusb_config_descriptor", config, depth); // Size of this descriptor (in bytes): uint8_t bLength; rpt_vstring(d1, "%-20s %d", "bLength:", config->bLength); // Descriptor type. Will have value LIBUSB_DT_CONFIG in this context. rpt_vstring(d1, "%-20s 0x%02x %s", "bDescriptorType:", config->bDescriptorType, // uint8_t bDescriptorType; descriptor_title(config->bDescriptorType) ); /** Total length of data returned for this configuration */ //uint16_t wTotalLength; /** Number of interfaces supported by this configuration */ // uint8_t bNumInterfaces; rpt_int("bNumInterfaces", NULL, config->bNumInterfaces, d1); /** Identifier value for this configuration */ // uint8_t bConfigurationValue; rpt_int("bConfigurationValue", "id for this configuration", config->bConfigurationValue, d1); /** Index of string descriptor describing this configuration */ // uint8_t iConfiguration; rpt_int("iConfiguration", "index of string descriptor", config->iConfiguration, d1); /** Configuration characteristics */ // uint8_t bmAttributes; rpt_uint8_as_hex("bmAttributes", "config characteristics", config->bmAttributes, d1); /** Maximum power consumption of the USB device from this bus in this * configuration when the device is fully opreation. Expressed in units * of 2 mA. */ // uint8_t MaxPower; rpt_int("MaxPower", "units of 2 mA", config->MaxPower, d1); /** Array of interfaces supported by this configuration. The length of * this array is determined by the bNumInterfaces field. */ // const struct libusb_interface *interface; int ndx = 0; for (ndx=0; ndxbNumInterfaces; ndx++) { const struct libusb_interface *inter = &(config->interface[ndx]); report_libusb_interface(inter, dh, d1); } /** Extra descriptors. If libusb encounters unknown configuration * descriptors, it will store them here, should you wish to parse them. */ // const unsigned char *extra; /** Length of the extra descriptors, in bytes. */ // int extra_length; rpt_int("extra_length", "len of extra descriptors", config->extra_length, d1); } /* Reports struct libusb_device_descriptor. * * Arguments: * desc pointer to libusb_device_descriptor instance * dh if non-null, string values are looked up for string descriptor indexes * depth logical indentation depth * * Returns: nothing * * struct libusb_device_descriptor represents the standard USB device descriptor. * This descriptor is documented in section 9.6.1 of the USB 3.0 specification. * * All multiple-byte fields are represented in host-endian format. */ void report_libusb_device_descriptor( const struct libusb_device_descriptor * desc, libusb_device_handle * dh, // may be null int depth) { int d1 = depth+1; rpt_structure_loc("libusb_device_descriptor", desc, depth); // Size of this descriptor (in bytes): uint8_t bLength; rpt_vstring(d1, "%-20s %d", "bLength:", desc->bLength); // Descriptor type. Will have value LIBUSB_DT_DEVICE in this context. rpt_vstring(d1, "%-20s 0x%02x %s", "bDescriptorType:", desc->bDescriptorType, // uint8_t bDescriptorType; descriptor_title(desc->bDescriptorType) ); /** USB specification release number in binary-coded decimal. A value of * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */ // uint16_t bcdUSB; unsigned int bcdHi = desc->bcdUSB >> 8; unsigned int bcdLo = desc->bcdUSB & 0x0f; rpt_vstring(d1,"%-20s 0x%04x (%x.%02x)", "bcdUSB", desc->bcdUSB, bcdHi, bcdLo); /** USB-IF class code for the device. See \ref libusb_class_code. */ rpt_vstring(d1, "%-20s 0x%02x (%u) %s", "bDeviceClass:", desc->bDeviceClass, // uint8_t bDeviceClass; desc->bDeviceClass, class_code_title(desc->bDeviceClass) ); /** USB-IF subclass code for the device, qualified by the bDeviceClass value */ // uint8_t bDeviceSubClass; rpt_vstring(d1, "%-20s 0x%02x (%u)", "bDeviceSubClass:", desc->bDeviceSubClass, desc->bDeviceSubClass); /** USB-IF protocol code for the device, qualified by the bDeviceClass and * bDeviceSubClass values */ // uint8_t bDeviceProtocol; // rpt_int("bDeviceProtocol", NULL, desc->bDeviceProtocol, d1); rpt_vstring(d1, "%-20s 0x%02x (%u)", "bDeviceProtocol:", desc->bDeviceProtocol, desc->bDeviceProtocol); /** Maximum packet size for endpoint 0 */ // uint8_t bMaxPacketSize0; rpt_vstring(d1, "%-20s %u (max size for endpoint 0)", "bMaxPacketSize0:", desc->bMaxPacketSize0); Pci_Usb_Id_Names usb_id_names = devid_get_usb_names( desc->idVendor, desc->idProduct, 0, 2); // USB-IF vendor ID: uint16_t idVendor; rpt_vstring(d1, "%-20s 0x%04x %s", "idVendor:", desc->idVendor, usb_id_names.vendor_name); // USB-IF product ID: uint16_t idProduct; rpt_vstring(d1, "%-20s 0x%04x %s", "idProduct:", desc->idProduct, usb_id_names.device_name); // Device release number in binary-coded decimal: uint16_t bcdDevice; bcdHi = desc->bcdDevice >> 8; bcdLo = desc->bcdDevice & 0x0f; rpt_vstring(d1, "%-20s %2x.%02x (device release number)", "bcdDevice:", bcdHi, bcdLo); // Index of string descriptor describing manufacturer: uint8_t iManufacturer; // rpt_vstring(d1, "%-20s %u (mfg string descriptor index)", "iManufacturer:", desc->iManufacturer); char * mfg_name = ""; // wchar_t * mfg_name_w = L""; if (dh && desc->iManufacturer) { mfg_name = lookup_libusb_string(dh, desc->iManufacturer); // mfg_name_w = lookup_libusb_string_wide(dh, desc->iManufacturer) ; // wprintf(L"Manufacturer (wide) %d -%ls\n", // desc->iManufacturer, // lookup_libusb_string_wide(dh, desc->iManufacturer) ); } rpt_vstring(d1, "%-20s %d %s", "iManufacturer:", desc->iManufacturer, mfg_name); // rpt_vstring(d1, "%-20s %u %S", "iManufacturer:", desc->iManufacturer, mfg_name_w); // Index of string descriptor describing product: uint8_t iProduct; // rpt_int("iProduct", "product string descriptor index", desc->iProduct, d1); char * product_name = ""; if (dh && desc->iProduct) product_name = lookup_libusb_string(dh, desc->iProduct); rpt_vstring(d1, "%-20s %u %s", "iProduct:", desc->iProduct, product_name); //Index of string descriptor containing device serial number: uint8_t iSerialNumber; // rpt_int("iSerialNumber", "index of string desc for serial num", desc->iProduct, d1); char * sn_name = ""; if (dh && desc->iSerialNumber) sn_name = lookup_libusb_string(dh, desc->iSerialNumber); rpt_vstring(d1, "%-20s %u %s", "iSerialNumber:", desc->iSerialNumber, sn_name); // Number of possible configurations: uint8_t bNumConfigurations; rpt_vstring(d1, "%-20s %u (number of possible configurations)", "bNumConfigurations:", desc->bNumConfigurations); } char * format_port_number_path(unsigned char path[], int portct, char * buf, int bufsz) { *buf = 0; int ndx; for (ndx=0; ndx < portct; ndx++) { char *end = buf + strlen(buf); // printf("end=%p\n", end); if (ndx == 0) sprintf(end, "%u", path[ndx]); else sprintf(end, ".%u", path[ndx]); } return buf; } bool is_hub_descriptor(const struct libusb_device_descriptor * desc) { return (desc->bDeviceClass == 9); } #ifdef IN_PROGRESS void report_open_dev( libusb_device * dev, libusb_device_handle * dh, // must not be null bool show_hubs, int depth) { bool debug = false; if (debug) printf("(%s) Starting. dev=%p, dh=%p, show_hubs=%s\n", __func__, dev, dh, sbool(show_hubs)); assert(dev); assert(dh); int d1 = depth+1; int rc; } #endif /* Reports a single libusb device. * */ void report_libusb_device( libusb_device * dev, bool show_hubs, int depth) { bool debug = false; if (debug) printf("(%s) Starting. dev=%p, show_hubs=%s\n", __func__, dev, sbool(show_hubs)); int d1 = depth+1; int rc; rpt_structure_loc("libusb_device", dev, depth); uint8_t busno = libusb_get_bus_number(dev); uint8_t devno = libusb_get_device_address(dev); rpt_vstring(d1, "%-20s: %d (0x%04x)", "Bus number", busno, busno); rpt_vstring(d1, "%-20s: %d (0x%04x)", "Device address", devno, devno); uint8_t portno = libusb_get_port_number(dev); rpt_vstring(d1, "%-20s: %u (%s)", "Port number", portno, "libusb_get_port_number(), number of the port this device is connected to"); /* uint8_t */ unsigned char path[8]; int portct = libusb_get_port_numbers(dev, path, sizeof(path)); char buf[100]; format_port_number_path(path, portct, buf, 100); rpt_vstring(d1, "%-20s: %s (list of all port numbers from root)", "Port numbers", buf); struct libusb_device_descriptor desc; // copies data into struct pointed to by desc, does not allocate: rc = libusb_get_device_descriptor(dev, &desc); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_get_device_descriptor", rc); goto bye; } if ( !show_hubs && is_hub_descriptor(&desc)) { rpt_title("Is hub device, skipping detail", d1); } else { struct libusb_device_handle * dh = NULL; int rc = libusb_open(dev, &dh); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_open", rc); dh = NULL; // belt and suspenders goto bye; } else { if (debug) printf("(%s) Successfully opened\n", __func__); int has_detach_kernel_capability = libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER); if (debug) printf("(%s) %s kernel detach driver capability\n", __func__, (has_detach_kernel_capability) ? "Has" : "Does not have"); if (has_detach_kernel_capability) { rc = libusb_set_auto_detach_kernel_driver(dh, 1); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_set_auto_detach_kernel_driver", rc); libusb_close(dh); goto bye; } } } #ifdef TEMPORARY_TEST if (dh) { // printf("String 0:\n"); // printf("%s\n", lookup_libusb_string(dh, 0)); // INVALID_PARM printf("String 1:\n"); printf("%s\n", lookup_libusb_string(dh, 1)); } #endif report_libusb_device_descriptor(&desc, dh, d1); struct libusb_config_descriptor *config; libusb_get_config_descriptor(dev, 0 /* config_index */, &config); // returns a pointer report_libusb_config_descriptor(config, dh, d1); libusb_free_config_descriptor(config); libusb_close(dh); } bye: printf("\n"); if (debug) printf("(%s) Done\n", __func__); } // Report a list of libusb_devices void report_libusb_devices(libusb_device **devs, bool show_hubs, int depth) { libusb_device *dev; int i = 0; while ((dev = devs[i++]) != NULL) { puts(""); report_libusb_device(dev, show_hubs, depth); } } #ifdef REF typedef struct hid_class_descriptor { uint8_t bDescriptorType; uint16_t wDescriptorLength; } HID_Class_Descriptor; typedef struct hid_descriptor { uint8_t bLength; uint8_t bDescriptorType; uint16_t bcdHID; uint8_t bCountryCode; uint8_t bNumDescriptors; // number of class descriptors, always at least 1, i.e. Report descriptor uint8_t bDescriptorType; // start of first class descriptor uint16_t wDescriptorLength; } HID_Descriptor; #endif static void report_retrieved_report_descriptor_and_probe( libusb_device_handle* dh, Byte * dbuf, int dbufct, int depth) { int d1 = depth+1; int d2 = depth+2; // int d3 = depth+3; Byte buf[1024] = {0}; int bytes_read = 0; rpt_vstring(depth, "Displaying report descriptor in HID external form:"); Hid_Report_Descriptor_Item* item_list = tokenize_hid_report_descriptor(dbuf, dbufct); report_hid_report_item_list(item_list, d1); puts(""); Parsed_Hid_Descriptor* phd = parse_hid_report_desc_from_item_list(item_list); if (phd) { rpt_vstring(depth, "Parsed report descriptor:"); dbgrpt_parsed_hid_descriptor(phd, d1); puts(""); rpt_vstring(d1, "Finding HID report for EDID..."); Parsed_Hid_Report* edid_report_desc = find_edid_report_descriptor(phd); if (!edid_report_desc) { rpt_vstring(d2, "Not found"); } else { // get EDID report dbgrpt_parsed_hid_report(edid_report_desc, d1); rpt_vstring(d1, "Get report data for EDID"); uint16_t rptlen = 258; bytes_read = 0; uint16_t report_id = edid_report_desc->report_id; bool ok = get_raw_report( dh, 0, // interface number TODO report_id, rptlen, buf, 1024, &bytes_read); if (!ok) printf("(%s) Error reading report\n", __func__); else { rpt_vstring(d2, "Read %d bytes for report %d 0x%02x for EDID", bytes_read, report_id, report_id); rpt_hex_dump(buf, bytes_read, d2); } } // VCP Codes puts(""); rpt_vstring(d1, "Finding HID feature reports for VCP features..."); GPtrArray* vcp_code_report_descriptors = get_vcp_code_reports(phd); if (vcp_code_report_descriptors && vcp_code_report_descriptors->len > 0) { for (int ndx = 0; ndx < vcp_code_report_descriptors->len; ndx++) { Vcp_Code_Report* vcr = g_ptr_array_index(vcp_code_report_descriptors, ndx); // puts(""); summarize_vcp_code_report(vcr, d2); rpt_vstring(d2, "Get report data for VCP feature 0x%02x", vcr->vcp_code); uint16_t rptlen = 3; bytes_read = 0; uint16_t report_id = vcr->rpt->report_id; bool ok = get_raw_report( dh, 0, // interface number TODO report_id, rptlen, buf, 1024, &bytes_read); if (!ok) printf("(%s) Error reading report\n", __func__); else { rpt_vstring(d2, "Read %d bytes for report %d 0x%02x for vcp feature 0x%02x", bytes_read, report_id, report_id, vcr->vcp_code); rpt_hex_dump(buf, bytes_read, d2); } puts(""); } } else { rpt_vstring(d2, "Not found"); puts(""); } free_parsed_hid_descriptor(phd); } free_hid_report_item_list(item_list); } /* Reports a HID_Descriptor * * Arguments: * dh libusb device handle * bInterfaceNumber interface number * desc pointer to HID_Descriptor to report * depth logical indentation depth * * Returns: * nothing */ void report_hid_descriptor( libusb_device_handle * dh, uint8_t bInterfaceNumber, HID_Descriptor * desc, int depth) { bool debug = false; if (debug) printf("(%s) Starting. dh=%p, bInterfaceNumber=%d, desc=%p\n", __func__, dh, bInterfaceNumber, desc); int d1 = depth+1; rpt_structure_loc("HID_Descriptor", desc, depth); rpt_vstring(d1, "%-20s %u", "bLength", desc->bLength); rpt_vstring(d1, "%-20s %u %s", "bDescriptorType", desc->bDescriptorType, descriptor_title(desc->bDescriptorType)); rpt_vstring(d1, "%-20s %2x.%02x (0x%04x)", "bcdHID", desc->bcdHID>>8, desc->bcdHID & 0x0f, desc->bcdHID); rpt_vstring(d1, "%-20s %u", "bCountryCode", desc->bCountryCode); rpt_vstring(d1, "%-20s %u", "bNumDescriptors", desc->bNumDescriptors); rpt_vstring(d1, "first bDescriptorType is at %p", &desc->bClassDescriptorType); int ndx = 0; for (;ndx < desc->bNumDescriptors; ndx++) { assert(sizeof(HID_Class_Descriptor) == 3); int offset = ndx * sizeof(HID_Class_Descriptor); HID_Class_Descriptor * cur = (HID_Class_Descriptor *) (&desc->bClassDescriptorType + offset); rpt_vstring(d1, "cur = %p", cur); rpt_vstring(d1, "%-20s %u %s", "bDescriptorType", cur->bDescriptorType, descriptor_title(cur->bDescriptorType)); uint16_t descriptor_len = cur->wDescriptorLength; // assumes we're on little endian system // uint16_t rpt_len = buf[7+3*i] | (buf[8+3*i] << rpt_vstring(d1, "%-20s %u", "wDescriptorLength", descriptor_len); switch(cur->bDescriptorType) { case LIBUSB_DT_REPORT: { rpt_vstring(d1, "Reading report descriptor of type LIBUSB_DT_REPORT from device..."); Byte dbuf[HID_MAX_DESCRIPTOR_SIZE]; if (dh == NULL) { printf("(%s) device handle is NULL, Cannot get report descriptor\n", __func__); } else { int bytes_read = 0; bool ok = get_raw_report_descriptor( dh, bInterfaceNumber, descriptor_len, // report length dbuf, sizeof(dbuf), &bytes_read); if (!ok) printf("(%s) get_raw_report_descriptor() returned %s\n", __func__, sbool(ok)); if (ok) { puts(""); rpt_hex_dump(dbuf, bytes_read, d1); puts(""); report_retrieved_report_descriptor_and_probe(dh, dbuf, bytes_read, d1); } } break; } case LIBUSB_DT_STRING: printf("(%s) Unimplemented: String report descriptor\n", __func__); break; default: printf("(%s) Descriptor. Type= 0x%02x\n", __func__, cur->bDescriptorType); break; } } if (debug) printf("(%s) Done.\n", __func__); } // // Module initialization // void init_libusb_reports() { devid_ensure_initialized(); } ddcutil-2.2.0/src/usb_util/libusb_util.c0000644000175000001440000005556714572333721013747 /** @file libusb_util.c */ // Copyright (C) 2016-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "util/device_id_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "usb_util/hid_report_descriptor.h" #include "usb_util/libusb_reports.h" #include "usb_util/usb_hid_common.h" #include "usb_util/libusb_util.h" // Note on function naming: // Since libusb.h uses "libusb_" as a prefix to function and struct names, it // would be confusing for this file to use the same convention. // // Utility functions // // copied and modified from make_path() in libusb/hid.c in hidapi char *make_path(int bus_number, int device_address, int interface_number) { char str[64]; snprintf(str, sizeof(str), "%04x:%04x:%02x", bus_number, device_address, interface_number); str[sizeof(str)-1] = '\0'; return g_strdup(str); } char *make_path_from_libusb_device(libusb_device *dev, int interface_number) { return make_path(libusb_get_bus_number(dev), libusb_get_device_address(dev), interface_number); } // // Possible_Monitor_Device reporting and lifecycle // struct possible_monitor_device * new_possible_monitor_device() { struct possible_monitor_device * cur = calloc(1, sizeof(struct possible_monitor_device)); return cur; } #ifdef UNTESTED void free_possible_monitor_device(struct possible_monitor_device * mondev) { if (mondev) { if (mondev->manufacturer_name) free(mondev->manufacturer_name); if (mondev->product_name) free(mondev->product_name); if (mondev->serial_number) free(mondev->serial_number); // n. do not free libusb_device // if (mondev->libusb_device) // libusb_unref_device(mondev->libusb_device); // ??? free(mondev); } } void free_possible_monitor_device_list(struct possible_monitor_device * head) { struct possible_monitor_device * cur = head; while (cur) { struct possible_monitor_device * next = cur->next; free_possible_monitor_device(cur); cur = next; } } #endif void report_possible_monitor_device(struct possible_monitor_device * mondev, int depth) { int d1 = depth+1; rpt_structure_loc("possible_monitor_device", mondev, depth); rpt_vstring(d1, "%-20s %p", "libusb_device", mondev->libusb_device); rpt_vstring(d1, "%-20s %d", "bus", mondev->bus); rpt_vstring(d1, "%-20s %d", "device_address", mondev->device_address); rpt_vstring(d1, "%-20s 0x%04x", "vid", mondev->vid); rpt_vstring(d1, "%-20s 0x%04x", "pid", mondev->pid); rpt_vstring(d1, "%-20s %d", "interface", mondev->interface); rpt_vstring(d1, "%-20s %d", "alt_setting", mondev->alt_setting); rpt_vstring(d1, "%-20s %s", "manufacturer_name", mondev->manufacturer_name); rpt_vstring(d1, "%-20s %s", "product_name", mondev->product_name); rpt_vstring(d1, "%-20s %s", "serial_number_ascii", mondev->serial_number); // rpt_vstring(d1, "%-20s %S", "serial_number_wide", mondev->serial_number_wide); rpt_vstring(d1, "%-20s %p", "next_sibling", mondev->next); } void report_possible_monitors(struct possible_monitor_device * mondev_head, int depth) { rpt_title("Possible monitor devices:", depth); if (!mondev_head) { rpt_title("None", depth+1); } else { struct possible_monitor_device * cur = mondev_head; while(cur) { report_possible_monitor_device(cur, depth+1); cur = cur->next; } } } typedef struct descriptor_path { unsigned short busno; unsigned short devno; struct libusb_device_descriptor * desc; struct libusb_device * dev; struct libusb_config_descriptor * config; struct libusb_interface * interface; struct libusb_interface_descriptor * inter; } Descriptor_Path; void report_descriptor_path(Descriptor_Path * pdpath, int depth) { int d1 = depth+1; rpt_structure_loc("Descriptor_Path", pdpath, depth); rpt_vstring(d1, "%-20s %d", "busno:", pdpath->busno); rpt_vstring(d1, "%-20s %d", "devno:", pdpath->devno); rpt_vstring(d1, "%-20s %p", "desc:", pdpath->desc); rpt_vstring(d1, "%-20s %p", "dev:", pdpath->dev); rpt_vstring(d1, "%-20s %p", "config:", pdpath->config); rpt_vstring(d1, "%-20s %p", "interface:", pdpath->interface); rpt_vstring(d1, "%-20s %p", "inter:", pdpath->inter); } // // Identify HID interfaces that that are not keyboard or mouse // /* Tests if the specified libusb_interface_descriptor possibly represents a * USB connected monitor. * * Arguments: * config pointer to instance to test * dpath structure path to this instance, used for messages * * Returns: true/false */ static bool possible_monitor_interface_descriptor( const struct libusb_interface_descriptor * inter, Descriptor_Path dpath) { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); // #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Wdiscarded-qualifiers" // This pragma is undefined on older versions of gcc, results in warnings // when building for older OS releases on OBS. So just use a cast instead. dpath.inter = (struct libusb_interface_descriptor *) inter; // #pragma GCC diagnostic pop bool result = false; if (inter->bInterfaceClass == LIBUSB_CLASS_HID) { if (debug) { rpt_vstring(0, "bInterfaceClass: 0x%02x (%d)", inter->bInterfaceClass, inter->bInterfaceClass); rpt_vstring(0, "bInterfaceSubClass: 0x%02x (%d)", inter->bInterfaceSubClass, inter->bInterfaceSubClass); rpt_int("bInterfaceProtocol", NULL, inter->bInterfaceProtocol, 0); } if (inter->bInterfaceProtocol != 1 && inter->bInterfaceProtocol != 2) result = true; } if (debug) printf("(%s) Returning %s\n", __func__, sbool(result)); return result; } /* Tests if the specified libusb_interface possibly represents a * USB connected monitor. * * Arguments: * config pointer to instance to test * dpath structure path to this instance, used for messages * * Returns: true/false */ static bool possible_monitor_interface( const struct libusb_interface * interface, Descriptor_Path dpath) { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); // pragma doesn't work on older versions of GCC, so use cast // #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Wdiscarded-qualifiers" dpath.interface = (struct libusb_interface *) interface; // #pragma GCC diagnostic pop bool result = false; int ndx; for (ndx=0; ndxnum_altsetting; ndx++) { const struct libusb_interface_descriptor * idesc = &interface->altsetting[ndx]; // report_interface_descriptor(idesc, d1); result |= possible_monitor_interface_descriptor(idesc, dpath); } if (debug) printf("(%s) Returning: %s\n", __func__, sbool(result)); return result; } /* Tests if the specified libusb_config_descriptor possibly represents a * USB connected monitor. * * Arguments: * config pointer to instance to test * dpath structure path to this instance, used for messages * * Returns: true/false */ static bool possible_monitor_config_descriptor( const struct libusb_config_descriptor * config, Descriptor_Path dpath) { bool result = false; // #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Wdiscarded-qualifiers" dpath.config = (struct libusb_config_descriptor *) config; // #pragma GCC diagnostic pop int ndx = 0; if (config->bNumInterfaces > 1) { // report_descriptor_path(&dpath, 0); uint16_t vid = dpath.desc->idVendor; uint16_t pid = dpath.desc->idProduct; Pci_Usb_Id_Names names; names = devid_get_usb_names( vid, pid, 0, 2); printf("(%s) Examining only interface 0 for device %d:%d, vid=0x%04x, pid=0x%04x %s %s\n", __func__, dpath.busno, dpath.devno, vid, pid, names.vendor_name, names.device_name); } // HACK: look at only interface 0 // for (ndx=0; ndxbNumInterfaces; ndx++) { const struct libusb_interface *inter = &(config->interface[ndx]); result |= possible_monitor_interface(inter, dpath); // } // if (result) // printf("(%s) Returning: %d\n", __func__, result); return result; } /* Tests if the specified libusb_device instance possibly represents a * USB connected monitor. * * Arguments: * config pointer to instance to test * dpath structure path to this instance, used for messages * * Returns: true/false */ bool possible_monitor_dev(libusb_device * dev, bool check_forced_monitor, Descriptor_Path dpath) { bool debug = false; if (debug) printf("(%s) Starting. dev=%p\n", __func__, dev); bool result = false; struct libusb_config_descriptor *config; libusb_get_config_descriptor(dev, 0, &config); struct libusb_device_descriptor desc; // copies data into struct pointed to by desc, does not allocate: int rc = libusb_get_device_descriptor(dev, &desc); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_get_device_descriptor", rc); goto bye; } dpath.desc = &desc; dpath.dev = dev; result = possible_monitor_config_descriptor(config, dpath); libusb_free_config_descriptor(config); if (!result && check_forced_monitor) { struct libusb_device_descriptor desc; int rc = libusb_get_device_descriptor(dev, &desc); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_device_descriptor", rc); goto bye; } // gushort vid = desc.idVendor; // gushort pid = desc.idProduct; if (debug) printf("(%s) Callling force_hid_monitor_by_vid_pid(0x%04x, 0x%04x)\n", __func__, desc.idVendor, desc.idProduct ); result = force_hid_monitor_by_vid_pid(desc.idVendor, desc.idProduct); } bye: if (debug) printf("(%s) Returning: %s\n" , __func__, sbool(result)); return result; } // *** NOT CURRENTLY USED *** // check_forced_monitor not implemented // apparently can get by without collected information in struct possible_monitor_device struct possible_monitor_device * alt_possible_monitor_dev( libusb_device * dev, bool check_forced_monitor) // NOT CURRENTLY USED! { bool debug = false; if (debug) printf("(%s) Starting. dev=%p, check_forced_monitor=%s\n", __func__, dev, sbool(check_forced_monitor)); struct possible_monitor_device * new_node = NULL; // report_dev(dev, NULL, false /* show hubs */, 0); int bus = libusb_get_bus_number(dev); int device_address = libusb_get_device_address(dev); gushort vid = 0; gushort pid = 0; struct libusb_device_descriptor desc; int rc = libusb_get_device_descriptor(dev, &desc); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_device_descriptor", rc); goto bye; } vid = desc.idVendor; pid = desc.idProduct; struct libusb_config_descriptor * config; rc = libusb_get_config_descriptor(dev, 0, &config); // returns a pointer if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_config_descriptor", rc); goto bye; } // Logitech receiver has subclass 0 on interface 2, // try ignoring all interfaces other than 0 int inter_no = 0; // for (inter_no=0; inter_nobNumInterfaces; inter_no++) { { const struct libusb_interface *inter = &(config->interface[inter_no]); int altset_no; for (altset_no=0; altset_nonum_altsetting; altset_no++) { const struct libusb_interface_descriptor * idesc = &inter->altsetting[altset_no]; if (idesc->bInterfaceClass == LIBUSB_CLASS_HID) { rpt_vstring(0, "bInterfaceClass: 0x%02x (%d)", idesc->bInterfaceClass, idesc->bInterfaceClass); rpt_vstring(0, "bInterfaceSubClass: 0x%02x (%d)", idesc->bInterfaceSubClass, idesc->bInterfaceSubClass); rpt_int("bInterfaceProtocol", NULL, idesc->bInterfaceProtocol, 0); if (idesc->bInterfaceProtocol != 1 && idesc->bInterfaceProtocol != 2) { // TO ADDRESS: WHAT IF MULTIPLE altsettings? what if they conflict? libusb_ref_device(dev); // if (debug) // report_dev(dev, NULL, false, 0); struct libusb_device_handle * dh = NULL; rc = libusb_open(dev, &dh); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_open", rc); dh = NULL; // belt and suspenders } else { printf("(%s) Successfully opened\n", __func__); rc = libusb_set_auto_detach_kernel_driver(dh, 1); if (rc < 0) REPORT_LIBUSB_ERROR_NOEXIT("libusb_set_auto_detach_kernel_driver", rc); if (new_node) { printf("(%s) Found additional possible monitor device on altset_no %d. Ignoring.\n", __func__, altset_no); } else { new_node = new_possible_monitor_device(); new_node->libusb_device = dev; new_node->bus = bus; new_node->device_address = device_address; new_node->alt_setting = altset_no; new_node->interface = inter_no; new_node->vid = vid; new_node->pid = pid; if (debug) { printf("Manufacturer: %d - %s\n", desc.iManufacturer, lookup_libusb_string(dh, desc.iManufacturer) ); printf("Product: %d - %s\n", desc.iProduct, lookup_libusb_string(dh, desc.iProduct) ); printf("Serial number: %d - %s\n", desc.iSerialNumber, lookup_libusb_string(dh, desc.iSerialNumber) ); } new_node->manufacturer_name = g_strdup(lookup_libusb_string(dh, desc.iManufacturer)); new_node->product_name = g_strdup(lookup_libusb_string(dh, desc.iProduct)); new_node->serial_number = g_strdup(lookup_libusb_string(dh, desc.iSerialNumber)); // new_node->serial_number_wide = wcsdup(lookup_libusb_string_wide(dh, desc.iSerialNumber)); // printf("(%s) serial_number_wide = |%S|\n", __func__, new_node->serial_number_wide); // report_device_descriptor(&desc, NULL, d1); // report_open_libusb_device(dh, 1); } libusb_close(dh); } } } } } libusb_free_config_descriptor(config); bye: if (debug) printf("(%s) Returning %p\n", __func__, new_node); return new_node; } /** Examines a null terminated list of pointers to struct libusb_device * * Returns a linked list of struct possible_monitor_device that represents * possible monitors */ // *** NOT CURRENTLY USED *** struct possible_monitor_device * get_possible_monitors( libusb_device **devs // null terminated list ) { bool debug = false; if (debug) printf("(%s) Starting\n", __func__); Possible_Monitor_Device * last_device = new_possible_monitor_device(); Possible_Monitor_Device * head_device = last_device; libusb_device *dev; int i = 0; while ((dev = devs[i++]) != NULL) { Possible_Monitor_Device * possible_monitor = alt_possible_monitor_dev(dev, /* check_forced_monitor= */ true); if (possible_monitor) { last_device->next = possible_monitor; last_device = possible_monitor; } } struct possible_monitor_device * true_head; true_head = head_device->next; free(head_device); if (debug) printf("(%s) Returning: %p\n", __func__, true_head); return true_head; } /* Filters a null terminated list of pointers to struct libusb_device to * those representing possible USB connected monitors. * * Arguments: * devs null terminated list * * Returns: filtered list (newly allocated) * * It is the responsibility of the caller to free the returned list. */ libusb_device ** filter_possible_monitor_devs( libusb_device **devs) { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); libusb_device *dev; int devct = 0; while ( devs[devct++] ) {} libusb_device ** result = calloc(devct+1, sizeof(libusb_device *)); int foundndx = 0; int i = 0; while ((dev = devs[i++]) != NULL) { unsigned short busno = libusb_get_bus_number(dev); unsigned short devno = libusb_get_device_address(dev); Descriptor_Path dpath; memset(&dpath, 0, sizeof(Descriptor_Path)); dpath.busno = busno; dpath.devno = devno; struct libusb_device_descriptor desc; // copies data into struct pointed to by desc, does not allocate: int rc = libusb_get_device_descriptor(dev, &desc); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_get_device_descriptor", rc); break; } dpath.desc = &desc; if (debug) printf("(%s) Examining device. bus=0x%04x, device=0x%04x\n", __func__, busno, devno); bool possible = possible_monitor_dev(dev, /*check_forced_monitor=*/ true, dpath); if (possible) { uint16_t vid = dpath.desc->idVendor; uint16_t pid = dpath.desc->idProduct; Pci_Usb_Id_Names names; names = devid_get_usb_names( vid, pid, 0, 2); printf("Found potential HID device %d:%d, vid=0x%04x, pid=0x%04x %s %s\n", dpath.busno, dpath.devno, vid, pid, names.vendor_name, (names.device_name) ? names.device_name : "(unrecognized pid)"); result[foundndx++] = dev; } } if (debug) printf("(%s) Returing: %p\n", __func__, result); return result; } /* Probe USB HID devices using libusb facilities. * * Arguments: * possible_monitors_only if true, only show detail for possible monitors * depth logical indentation depth * * Returns: nothing */ void probe_libusb(bool possible_monitors_only, int depth) { bool debug = false; if (debug) printf("(%s) Starting\n", __func__); bool ok = devid_ensure_initialized(); if (!ok) { printf("(%s) devid_ensure_initialized() failed. Terminating probe_libusb()\n", __func__); return; } libusb_device ** devs; int rc; ssize_t cnt; // number of devices in list rc = libusb_init(NULL); // initialize a library session, use default context if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_init", rc); goto bye; } #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000106) libusb_set_option(NULL /* default context */, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); #else libusb_set_debug(NULL /*default context*/, LIBUSB_LOG_LEVEL_INFO); #endif cnt = libusb_get_device_list(NULL /* default context */, &devs); if (cnt < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_get_device_list", (int) cnt); } else { libusb_device ** devs_to_show = devs; libusb_device ** filtered_devs_to_show = NULL; if (possible_monitors_only) { devs_to_show = filter_possible_monitor_devs(devs); filtered_devs_to_show = devs_to_show; // note newly allocated memory } report_libusb_devices(devs_to_show, false, // show_hubs depth); if (filtered_devs_to_show) free(filtered_devs_to_show); libusb_free_device_list(devs, 1 /* unref the devices in the list */); } libusb_exit(NULL); bye: if (debug) printf("(%s) Done\n", __func__); } bool libusb_is_monitor_by_path(gushort busno, gushort devno, gushort intfno) { bool debug = false; printf("(%s) Starting. busno=%d 0x%04x, devno=%d 0x%04x, intfno=%d 0x%02x\n", __func__, busno, busno, devno, devno, intfno, intfno); bool result = false; if (intfno == 0) { // monitors never have more than 1 interface bool ok = devid_ensure_initialized(); if (!ok) { printf("(%s) devid_ensure_initialized() failed. Terminating probe_libusb()\n", __func__); goto bye; } libusb_device **devs; int rc; ssize_t cnt; // number of devices in list rc = libusb_init(NULL); // initialize a library session, use default context if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_init", rc); goto bye; } #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000106) libusb_set_option(NULL /* default context */, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); #else libusb_set_debug(NULL /*default context*/, LIBUSB_LOG_LEVEL_INFO); #endif cnt = libusb_get_device_list(NULL /* default context */, &devs); if (cnt < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_get_device_list", (int) cnt); } else { libusb_device *dev; int i = 0; while ((dev = devs[i++]) != NULL) { // unsigned short busno = libusb_get_bus_number(dev); // unsigned short devno = libusb_get_device_address(dev); if (busno == libusb_get_bus_number(dev) && devno == libusb_get_device_address(dev)) { printf ("(%s) Found busno=%d, devno=%d\n", __func__, busno, devno); Descriptor_Path dpath; memset(&dpath, 0, sizeof(Descriptor_Path)); dpath.busno = busno; dpath.devno = devno; struct libusb_device_descriptor desc; // copies data into struct pointed to by desc, does not allocate: int rc = libusb_get_device_descriptor(dev, &desc); if (rc < 0) { REPORT_LIBUSB_ERROR_NOEXIT("libusb_get_device_descriptor", rc); break; } dpath.desc = &desc; if (debug) printf("(%s) Examining device. bus=0x%04x, device=0x%04x\n", __func__, busno, devno); result = possible_monitor_dev(dev, /*check_forced_monitor=*/ true, dpath); break; } } libusb_free_device_list(devs, 1 /* unref the devices in the list */); } libusb_exit(NULL); } bye: if (debug) printf("(%s) Done. Returning %s\n", __func__, sbool(result)); return result; } ddcutil-2.2.0/src/usb_util/base_hid_report_descriptor.c0000644000175000001440000003205014754576332017010 /** base_hid_report_descriptor.c * * Functions to perform basic parsing of the HID Report Descriptor and * display the contents of the Report Descriptor in the format used * in HID documentation. */ // Copyright (C) 2016-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include "util/device_id_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "usb_util/usb_hid_common.h" #include "usb_util/base_hid_report_descriptor.h" typedef struct ptr_pair{ void * p1; void * p2; } Ptr_Pair; Ptr_Pair item_flag_names_r(uint16_t flags, char * b1, int b1_size, char * b2, int b2_size) { assert(b1_size >= 80); assert(b2_size >= 80); snprintf(b1, b1_size, "%s %s %s %s %s", flags & 0x01 ? "Constant" : "Data", flags & 0x02 ? "Variable" : "Array", flags & 0x04 ? "Relative" : "Absolute", flags & 0x08 ? "Wrap" : "No_Wrap", flags & 0x10 ? "Non_Linear" : "Linear" ); snprintf(b2, b2_size, "%s %s %s %s", flags & 0x20 ? "No_Preferred_State" : "Preferred_State", flags & 0x40 ? "Null_State" : "No_Null_Position", flags & 0x80 ? "Volatile" : "Non_Volatile", flags & 0x100 ? "Buffered Bytes" : "Bitfield" ); Ptr_Pair result = {b1,b2}; return result; } Ptr_Pair item_flag_names(uint16_t flags) { static char b1[80]; static char b2[80]; return item_flag_names_r(flags, b1, 80, b2, 80); } #ifdef OLD static void dump_unit(unsigned int data, unsigned int len) { char *systems[5] = { "None", "SI Linear", "SI Rotation", "English Linear", "English Rotation" }; char *units[5][8] = { { "None", "None", "None", "None", "None", "None", "None", "None" }, { "None", "Centimeter", "Gram", "Seconds", "Kelvin", "Ampere", "Candela", "None" }, { "None", "Radians", "Gram", "Seconds", "Kelvin", "Ampere", "Candela", "None" }, { "None", "Inch", "Slug", "Seconds", "Fahrenheit", "Ampere", "Candela", "None" }, { "None", "Degrees", "Slug", "Seconds", "Fahrenheit", "Ampere", "Candela", "None" }, }; unsigned int i; unsigned int sys; int earlier_unit = 0; /* First nibble tells us which system we're in. */ sys = data & 0xf; data >>= 4; if (sys > 4) { if (sys == 0xf) printf("System: Vendor defined, Unit: (unknown)\n"); else printf("System: Reserved, Unit: (unknown)\n"); return; } else { printf("System: %s, Unit: ", systems[sys]); } for (i = 1 ; i < len * 2 ; i++) { char nibble = data & 0xf; data >>= 4; if (nibble != 0) { if (earlier_unit++ > 0) printf("*"); printf("%s", units[sys][i]); if (nibble != 1) { /* This is a _signed_ nibble(!) */ int val = nibble & 0x7; if (nibble & 0x08) val = -((0x7 & ~val) + 1); printf("^%d", val); } } } if (earlier_unit == 0) printf("(None)"); printf("\n"); } #endif static char * unit_name_r(unsigned int data, unsigned int len, char * buf, int bufsz) { assert(bufsz >= 80); char *systems[5] = { "None", "SI Linear", "SI Rotation", "English Linear", "English Rotation" }; char *units[5][8] = { { "None", "None", "None", "None", "None", "None", "None", "None" }, { "None", "Centimeter", "Gram", "Seconds", "Kelvin", "Ampere", "Candela", "None" }, { "None", "Radians", "Gram", "Seconds", "Kelvin", "Ampere", "Candela", "None" }, { "None", "Inch", "Slug", "Seconds", "Fahrenheit", "Ampere", "Candela", "None" }, { "None", "Degrees", "Slug", "Seconds", "Fahrenheit", "Ampere", "Candela", "None" }, }; unsigned int i; unsigned int sys; int earlier_unit = 0; /* First nibble tells us which system we're in. */ sys = data & 0xf; data >>= 4; if (sys > 4) { if (sys == 0xf) strcpy(buf, "System: Vendor defined, Unit: (unknown)"); else strcpy(buf, "System: Reserved, Unit: (unknown)"); } else { sprintf(buf, "System: %s, Unit: ", systems[sys]); for (i = 1 ; i < len * 2 ; i++) { char nibble = data & 0xf; data >>= 4; if (nibble != 0) { if (earlier_unit++ > 0) strcat(buf, "*"); sprintf(buf+strlen(buf), "%s", units[sys][i]); if (nibble != 1) { /* This is a _signed_ nibble(!) */ int val = nibble & 0x7; if (nibble & 0x08) val = -((0x7 & ~val) + 1); sprintf(buf+strlen(buf), "^%d", val); } } } } if (earlier_unit == 0) strcat(buf, "(None)"); return buf; } static char * unit_name(unsigned int data, unsigned int len) { static char buf[80]; return unit_name_r(data, len, buf, 80); } /** Debugging function. */ void report_raw_hid_report_item(Hid_Report_Descriptor_Item * item, int depth) { int d1 = depth+1; rpt_structure_loc("Hid_Report_Item", item, depth); rpt_vstring(d1, "%-20s: 0x%02x", "btype", item->btype); rpt_vstring(d1, "%-20s: 0x%02x", "btag", item->btag); // rpt_vstring(d1, "%-20s: %d", "bsize", item->bsize); // rpt_vstring(d1, "%-20s: %d", "bsize_orig", item->bsize_orig); rpt_vstring(d1, "%-20s: %d", "bsize_bytect", item->bsize_bytect); rpt_vstring(d1, "%-20s: 0x%08x", "data", item->data); } void free_hid_report_item_list(Hid_Report_Descriptor_Item * head) { while (head) { Hid_Report_Descriptor_Item * next = head->next; free(head); head = next; } } /* Converts the bytes of a HID Report Descriptor to a linked list of * Hid_Report_Items. * * Arguments: * b address of bytes * l number of bytes * * Returns: linked list of Hid_Report_Items */ // need better name Hid_Report_Descriptor_Item * tokenize_hid_report_descriptor(Byte * b, int l) { bool debug = false; if (debug) printf("(%s) Starting. b=%p, l=%d\n", __func__, b, l); Hid_Report_Descriptor_Item * root = NULL; Hid_Report_Descriptor_Item * prev = NULL; Hid_Report_Descriptor_Item * cur = NULL; int i, j; // if (debug) // printf("(%s) Report Descriptor: (length is %d)\n", __func__, l); for (i = 0; i < l; ) { cur = calloc(1, sizeof(Hid_Report_Descriptor_Item)); Byte b0 = b[i] & 0x03; // first 2 bits are size indicator, 0, 1, 2, or 3 cur->bsize_bytect = (b0 == 3) ? 4 : b0; // actual number of bytes cur->btype = (b[i] & (0x03 << 2))>>2; // next 2 bits are type, shift to range 0..3 cur->btag = b[i] & ~0x03; // mask out size bits to get tag memcpy(cur->raw_bytes, b+i, 1+cur->bsize_bytect); // WRONG: printf("(%s) raw_bytes: 0x%0*x\n", __func__, (1+cur->bsize_bytect)*2, cur->raw_bytes); if (cur->bsize_bytect > 0) { cur->data = 0; for (j = 0; j < cur->bsize_bytect; j++) { cur->data += (b[i+1+j] << (8*j)); } } // alt: int kk = i+1; switch(cur->bsize_bytect) { case 4: cur->data_alt.u32 = b[kk+3]<< 24 | b[kk+2] << 16 | b[kk+1] << 8 | b[kk]; assert (cur->data_alt.u32 == cur->data); break; case 2: cur->data_alt.u16 = b[kk+1] << 8 | b[kk]; // printf("(%s) data_alt.u16 = 0x%04x, cur->data = 0x%08x\n", // __func__, cur->data_alt.u16, cur->data); assert (cur->data_alt.u16 == cur->data); break; case 1: cur->data_alt.u8 = b[kk]; assert (cur->data_alt.u8 == cur->data); break; default: assert(cur->bsize_bytect == 0); } if (!root) { root = cur; prev = cur; } else { prev->next = cur; prev = cur; } i += 1 + cur->bsize_bytect; } if (debug) printf("(%s) Returning: %p\n", __func__, root); return root; } typedef struct hid_report_item_globals { uint16_t usage_page; struct hid_report_item_globals * prev; } Hid_Report_Item_Globals; /* Reports a single Hid_Report_Item * * Arguments: * item pointer to Hid_Report_Item to report * globals current globals state * depth logical indentation depth */ void report_hid_report_item( Hid_Report_Descriptor_Item * item, Hid_Report_Item_Globals * globals, int depth) { // int d1 = depth+1; int d_indent = depth+5; // TODO: handle push/pop of globals char *types[4] = { "Main", "Global", "Local", "reserved" }; char databuf[80]; if (item->bsize_bytect == 0) strcpy(databuf, "none"); else snprintf(databuf, 80, "0x%0*x", item->bsize_bytect*2, item->data); char rawbuf[16]; rawbuf[0] = '\0'; // possibly switch this on and off char workbuf[9]; // 2 chars/byte + 1 for terminating null hexstring2( item->raw_bytes+1, // bytes to convert item->bsize_bytect, // number of bytes NULL, // no separator string false, // uppercase, workbuf, // buffer in which to return hex string sizeof(workbuf) ); // buffer size snprintf(rawbuf, 16, "%02x %-8s ", item->raw_bytes[0], workbuf); rpt_vstring(depth, "%sItem(%-6s): %s, data=[ %s ]", rawbuf, types[item->btype], devid_hid_descriptor_item_type(item->btag), // replacement for names_reporttag() databuf); switch (item->btag) { case 0x04: /* Usage Page */ #ifdef HACK_FOR_HP_LP2480ZX switch(item->data) { // belongs elsewhere case 0xffa0: printf("Fixup: data = 0xffa0 -> 0x80\n"); item->data = 0x80; break; case 0xffa1: item->data = 0x81; break; } #endif rpt_vstring(d_indent, "%s", devid_usage_code_page_name(item->data)); // names_huts(data)); globals->usage_page = item->data; break; case 0x08: /* Usage */ case 0x18: /* Usage Minimum */ case 0x28: /* Usage Maximum */ { // char * name = names_hutus((hut<<16) + item->data); char * name = devid_usage_code_id_name(globals->usage_page,item->data); if (!name) { name = "Unrecognized usage"; } rpt_vstring(d_indent, "%s", name); } break; case 0x54: /* Unit Exponent */ rpt_vstring(d_indent, "Unit Exponent: %i", (signed char)item->data); break; case 0x64: /* Unit */ rpt_vstring(d_indent, "%s", unit_name(item->data, item->bsize_bytect)); break; case 0xa0: /* Collection */ rpt_vstring(d_indent, "%s", collection_type_name(item->data)); break; case 0x80: /* Input */ case 0x90: /* Output */ case 0xb0: /* Feature */ { // interpret the bits into 2 lines of text Ptr_Pair flag_names = item_flag_names(item->data); rpt_vstring(d_indent, "%s", (char *) flag_names.p1); rpt_vstring(d_indent, "%s", (char *) flag_names.p2); break; } } } /* Given a Hid Report Descriptor, represented as a linked list of * Hid_Report_Items, display the descriptor in a form similar to that * used in HID documentation, with annotation. * * Arguments: * head first item in list * depth logical indentation depth * * Returns: nothing */ void report_hid_report_item_list(Hid_Report_Descriptor_Item * head, int depth) { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); Hid_Report_Item_Globals globals; // will contain current globals as list is walked memset(&globals, 0, sizeof(Hid_Report_Item_Globals)); while (head) { report_hid_report_item(head, &globals, depth); head = head->next; } } /* Indicates if a tokenized HID Report Descriptor, represented as a linked * list of Hid_Report_Descriptor_Items, represents a USB connected monitor. * * Arguments: * report_item_list list head * * Returns: true/false * * Per section 5.5 of Usb Monitor Control Class Specification Rev 1.0: * "In order to identify a HID class device as a monitor, the device's * HID Report Descriptor must contain a top-level collection with a usage * of Monitor Control from the USB Monitor Usage Page." * * i.e. Usage page = 0x80 USB monitor * Usage id = 0x01 Monitor Control */ bool is_monitor_by_tokenized_hid_report_descriptor(Hid_Report_Descriptor_Item * report_item_list) { bool is_monitor = false; Hid_Report_Descriptor_Item * cur_item = report_item_list; // We cheat on the spec. Just look at the first Usage Page item, is it USB Monitor? while (cur_item) { if (cur_item->btag == 0x04) { if (cur_item->data == 0x80) { is_monitor = true; } break; } } return is_monitor; } ddcutil-2.2.0/src/usb_util/hid_report_descriptor.c0000644000175000001440000012737714754576332016037 /** @file hid_report_descriptor.c */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include "util/coredefs.h" #include "util/device_id_util.h" #include "util/report_util.h" #include "usb_util/base_hid_report_descriptor.h" #include "usb_util/usb_hid_common.h" #include "usb_util/hid_report_descriptor.h" // // Lookup tables // static const char* report_type_name_table[] = { "invalid", "Input", "Output", "Feature" }; /* Returns a string representation of a report type id * * Arguments: report_type * * Returns: string representation of id */ const char * hid_report_type_name(Byte report_type) { if (report_type < HID_REPORT_TYPE_MIN || report_type > HID_REPORT_TYPE_MAX) report_type = 0; return report_type_name_table[report_type]; } /* Create a string representation of Main Item flags bitfield. * The representation is returned in a buffer provided, which * must be at least 150 bytes in size. * * Arguments: * data flags * buffer where to save formatted response * bufsz buffer size * * Returns: buffer */ char * interpret_item_flags_r(uint16_t data, char * buffer, int bufsz) { assert(buffer && bufsz > 150); snprintf(buffer, bufsz, "%s %s %s %s %s %s %s %s %s", data & 0x01 ? "Constant" : "Data", data & 0x02 ? "Variable" : "Array", data & 0x04 ? "Relative" : "Absolute", data & 0x08 ? "Wrap" : "No_Wrap", data & 0x10 ? "Non_Linear" : "Linear", data & 0x20 ? "No_Preferred_State" : "Preferred_State", data & 0x40 ? "Null_State" : "No_Null_Position", data & 0x80 ? "Volatile" : "Non_Volatile", data & 0x100 ? "Buffered Bytes" : "Bitfield"); return buffer; } // // Free functions for Parsed_Hid_Descriptor and its contained structs // void free_parsed_hid_field(Parsed_Hid_Field * phf) { if (phf) { if (phf->extended_usages) g_array_free(phf->extended_usages, true); free(phf); } } #ifdef UNUSED // wrap free_parsed_hid_field() in signature of GDestroyNotify() void free_parsed_hid_field_func(gpointer data) { free_parsed_hid_field((Parsed_Hid_Field *) data); } #endif void free_parsed_hid_report(Parsed_Hid_Report * phr) { if (phr) { if (phr->hid_fields) { g_ptr_array_set_free_func(phr->hid_fields, (GDestroyNotify) free_parsed_hid_field); g_ptr_array_free(phr->hid_fields, true); } free(phr); } } // wrap free_parsed_hid_report() in signature of GDestroyNotify() void free_parsed_hid_report_func(gpointer data) { free_parsed_hid_report((Parsed_Hid_Report *) data); } #ifdef UNUSED void free_parsed_hid_collection_func(gpointer data); // forward ref #endif void free_parsed_hid_collection(Parsed_Hid_Collection * phc) { if (phc) { if (phc->reports) { g_ptr_array_set_free_func(phc->reports,(GDestroyNotify) free_parsed_hid_field); g_ptr_array_free(phc->reports, true); } if (phc->child_collections) { g_ptr_array_set_free_func(phc->child_collections, (GDestroyNotify) free_parsed_hid_collection); g_ptr_array_free(phc->child_collections, true); } free(phc); } } #ifdef UNUSED // wrap free_parsed_hid_collection() in signature of GDestroyNotify() void free_parsed_hid_collection_func(gpointer data) { free_parsed_hid_collection((Parsed_Hid_Collection *) data); } #endif void free_parsed_hid_descriptor(Parsed_Hid_Descriptor * phd) { if (phd) { if (phd->root_collection) { free_parsed_hid_collection(phd->root_collection); } free(phd); } } // // Functions to report Parsed_Hid_Descriptor and its contained structs // void report_hid_field(Parsed_Hid_Field * hf, int depth) { int d1 = depth+1; // rpt_structure_loc("Hid_Field", hf, depth); rpt_title("Field: ", depth); char buf[200]; rpt_vstring(d1, "%-20s: 0x%04x %s", "Usage page", hf->usage_page, devid_usage_code_page_name(hf->usage_page)); // deprecated // rpt_vstring(d1, "%-20s: 0x%04x %s", "Usage id", // hf->usage_id, // devid_usage_code_id_name(hf->usage_page, hf->usage_id)); char * ucode_name = NULL; #ifdef OLD if (hf->extended_usage) { ucode_name = devid_usage_code_name_by_extended_id(hf->extended_usage); if (!ucode_name) ucode_name = "(Unrecognized usage code)"; } else ucode_name = "WARNING: No usage specified for field"; rpt_vstring(d1, "%-20s: 0x%08x %s", "Extended Usage", hf->extended_usage, ucode_name); #endif if (!hf->extended_usages && !hf->min_extended_usage && !hf->max_extended_usage) { rpt_vstring(d1, "WARNING: No usage specified for field"); } else { if (hf->extended_usages) { for (int ndx = 0; ndx < hf->extended_usages->len; ndx++) { uint32_t extusage = g_array_index(hf->extended_usages, uint32_t, ndx); ucode_name = devid_usage_code_name_by_extended_id(extusage); if (!ucode_name) ucode_name = "(Unrecognized usage code)"; if (ndx == 0) rpt_vstring(d1, "%-20s: 0x%08x %s", "Extended Usage", extusage, ucode_name); else rpt_vstring(d1, "%-20s 0x%08x %s", "", extusage, ucode_name); } } if (hf->min_extended_usage) { ucode_name = devid_usage_code_name_by_extended_id(hf->min_extended_usage); if (!ucode_name) ucode_name = "(Unrecognized usage code)"; rpt_vstring(d1, "%-20s: 0x%08x %s", "Minimum Extended Usage", hf->min_extended_usage, ucode_name); } if (hf->max_extended_usage) { ucode_name = devid_usage_code_name_by_extended_id(hf->max_extended_usage); if (!ucode_name) ucode_name = "(Unrecognized usage code)"; rpt_vstring(d1, "%-20s: 0x%08x %s", "Maximum Extended Usage", hf->max_extended_usage, ucode_name); } if ( ( hf->min_extended_usage && !hf->max_extended_usage) || (!hf->min_extended_usage && hf->max_extended_usage) ) rpt_vstring(d1, "Min and max extended usage must occur together"); } rpt_vstring(d1, "%-20s: 0x%04x %s", "Item flags", hf->item_flags, interpret_item_flags_r(hf->item_flags, buf, 200) ); rpt_vstring(d1, "%-20s: 0x%04x %d", "Logical minimum", hf->logical_minimum, hf->logical_minimum); rpt_vstring(d1, "%-20s: 0x%04x %d", "Logical maximum", hf->logical_maximum, hf->logical_maximum); rpt_vstring(d1, "%-20s: 0x%04x %d", "Physical minimum", hf->physical_minimum, hf->physical_minimum); rpt_vstring(d1, "%-20s: 0x%04x %d", "Physical maximum", hf->physical_maximum, hf->physical_maximum); rpt_vstring(d1, "%-20s: %d", "Report size", hf->report_size); rpt_vstring(d1, "%-20s: %d", "Report count", hf->report_count); rpt_vstring(d1, "%-20s: 0x%04x %d", "Unit_exponent", hf->unit_exponent, hf->unit_exponent); rpt_vstring(d1, "%-20s: 0x%04x %d", "Unit", hf->unit, hf->unit); } /* Report a single report in a parsed HID report descriptor * * Arguments: * pdesc pointer to Hid_Report instance * depth logical indentation depth * * Returns: nothing */ void dbgrpt_parsed_hid_report(Parsed_Hid_Report * hr, int depth) { int d1 = depth+1; // int d2 = depth+2; // rpt_structure_loc("Hid_Report", hr,depth); rpt_vstring(depth, "%-20s:%*s 0x%02x %d", "Report id", rpt_get_indent(1), "", hr->report_id, hr->report_id); rpt_vstring(d1, "%-20s: 0x%02x %s", "Report type", hr->report_type, hid_report_type_name(hr->report_type) ); if (hr->hid_fields && hr->hid_fields->len > 0) { // rpt_title("Fields: (alt) ", d1); for (int ndx=0; ndxhid_fields->len; ndx++) { report_hid_field( g_ptr_array_index(hr->hid_fields, ndx), d1); } } else rpt_vstring(d1, "%-20s: none", "Fields"); } /* Output a brief summary of a Parsed_Hid_Report indicating its report id and type * * Arguments: * pdesc pointer to Hid_Report instance * depth logical indentation depth * * Returns: nothing */ void summarize_parsed_hid_report(Parsed_Hid_Report * hr, int depth) { // int d1 = depth+1; // rpt_vstring(depth, "%-20s:%*s 0x%02x %d", "Report id", rpt_indent(1), "", hr->report_id, hr->report_id); // rpt_vstring(d1, "%-20s: 0x%02x %s", "Report type", // hr->report_type, hid_report_type_name(hr->report_type) ); rpt_vstring(depth, "report id: 0x%02x (%3d), report type: 0x%02x (%s)", hr->report_id, hr->report_id, hr->report_type, hid_report_type_name(hr->report_type) ); } void report_hid_collection(Parsed_Hid_Collection * col, int depth) { bool show_dummy_root = false; int d1 = depth+1; if (!col->is_root_collection || show_dummy_root) rpt_structure_loc("Hid_Collection", col, depth); if (col->is_root_collection) { if (show_dummy_root) rpt_title("Dummy root collection", d1); } else { rpt_vstring(d1, "%-20s: x%02x %s", "Collection type", col->collection_type, collection_type_name(col->collection_type)); rpt_vstring(d1, "%-20s: x%02x %s", "Usage page", col->usage_page, devid_usage_code_page_name(col->usage_page)); // deprecated: // rpt_vstring(d1, "%-20s: x%02x %s", "Usage id", // col->usage_id, devid_usage_code_id_name(col->usage_page, col->usage_id)); rpt_vstring(d1, "%-20s: 0x%08x %s", "Extended Usage", col->extended_usage, devid_usage_code_name_by_extended_id(col->extended_usage)); } if (col->child_collections && col->child_collections->len > 0) { int child_depth = d1; if (!col->is_root_collection || show_dummy_root) rpt_title("Contained collections: ", d1); else child_depth = depth; for (int ndx = 0; ndx < col->child_collections->len; ndx++) { Parsed_Hid_Collection * a_child = g_ptr_array_index(col->child_collections, ndx); report_hid_collection(a_child, child_depth); } } if (col->reports && col->reports->len > 0) { if (col->is_root_collection) printf("(%s) ERROR: Dummy root collection contains reports\n", __func__); rpt_title("Reports:", d1); for (int ndx = 0; ndx < col->reports->len; ndx++) dbgrpt_parsed_hid_report(g_ptr_array_index(col->reports, ndx), d1); } else rpt_vstring(d1, "%-20s: None", "Reports"); } /* Report a parsed HID descriptor. * * Arguments: * pdesc pointer to Parsed_Hid_Descriptor * depth logical indentation depth * * Returns: nothing */ void dbgrpt_parsed_hid_descriptor(Parsed_Hid_Descriptor * pdesc, int depth) { int d1 = depth + 1; rpt_structure_loc("Parsed_Hid_Descriptor", pdesc, depth); report_hid_collection(pdesc->root_collection, d1); } static void accumulate_report_descriptors_for_collection( Parsed_Hid_Collection * col, Byte report_type_flags, GPtrArray * accumulator) { if (col->child_collections && col->child_collections->len > 0) { for (int ndx = 0; ndx < col->child_collections->len; ndx++) { Parsed_Hid_Collection * a_child = g_ptr_array_index(col->child_collections, ndx); accumulate_report_descriptors_for_collection(a_child, report_type_flags, accumulator); } } if (col->reports && col->reports->len > 0) { for (int ndx = 0; ndx < col->reports->len; ndx++) { Parsed_Hid_Report * rpt = g_ptr_array_index(col->reports, ndx); if ( (rpt->report_type == HID_REPORT_TYPE_INPUT && (report_type_flags & HIDF_REPORT_TYPE_INPUT )) || (rpt->report_type == HID_REPORT_TYPE_OUTPUT && (report_type_flags & HIDF_REPORT_TYPE_OUTPUT )) || (rpt->report_type == HID_REPORT_TYPE_FEATURE && (report_type_flags & HIDF_REPORT_TYPE_FEATURE)) ) { g_ptr_array_add(accumulator, rpt); } } } } /* Extracts the report descriptors of the specified report type or types and * returns them as an array of pointers to the reports. * * Arguments: * phd pointer to parsed HID descriptor * report_type_flags report types to select, as array of flag bits * * Returns: array of pointers to Hid_Report */ GPtrArray * select_parsed_hid_report_descriptors(Parsed_Hid_Descriptor * phd, Byte report_type_flags) { GPtrArray * selected_reports = g_ptr_array_new(); accumulate_report_descriptors_for_collection( phd->root_collection, report_type_flags, selected_reports); return selected_reports; } // // Data structures and functions For building Parsed_Hid_Descriptor // // struct cur_report_globals; typedef struct cur_report_globals { uint16_t usage_page; int16_t logical_minimum; int16_t logical_maximum; bool physical_minimum_defined; // for future use properly implementing physical min/max algorithm per USB spec bool physical_maximum_defined; int16_t physical_minimum; int16_t physical_maximum; uint16_t unit_exponent; uint16_t unit; uint16_t report_size; uint16_t report_id; uint16_t report_count; // number of data fields for the item struct cur_report_globals * prev; } Cur_Report_Globals; typedef struct cur_report_locals { // if bSize = 3, usages are 4 byte extended usages // int usage_bsize; // actually just 0..4 int usage_bsize_bytect; // 0, 1, 2, or 4 GArray * usages; uint32_t usage_minimum; uint32_t usage_maximum; GArray * designator_indexes; uint16_t designator_minimum; uint16_t designator_maximum; GArray * string_indexes; uint16_t string_maximum; uint16_t string_minimum; } Cur_Report_Locals; void free_cur_report_locals(Cur_Report_Locals * locals) { if (locals) { if (locals->usages) g_array_free(locals->usages, true); if (locals->string_indexes) g_array_free(locals->string_indexes, true); if (locals->designator_indexes) g_array_free(locals->designator_indexes, true); free(locals); } } Parsed_Hid_Report * find_hid_report(Parsed_Hid_Collection * col, Byte report_type, uint16_t report_id) { Parsed_Hid_Report * result = NULL; if (col->reports->len) { for (int ndx=0; ndx < col->reports->len && !result; ndx++) { Parsed_Hid_Report * cur = g_ptr_array_index(col->reports, ndx); if (cur->report_type == report_type && cur->report_id == report_id) result = cur; } } return result; } Parsed_Hid_Report * find_hid_report_or_new(Parsed_Hid_Collection * hc, Byte report_type, uint16_t report_id) { bool debug = false; if (debug) printf("(%s) report_type=%d, report_id=%d\n", __func__, report_type, report_id); assert(hc); Parsed_Hid_Report * result = find_hid_report(hc, report_type, report_id); if (!result) { if (!hc->reports) { hc->reports = g_ptr_array_new(); } result = calloc(1, sizeof(Parsed_Hid_Report)); result->report_id = report_id; result->report_type = report_type; g_ptr_array_add(hc->reports, result); } return result; } void add_report_field(Parsed_Hid_Report * hr, Parsed_Hid_Field * hf) { assert(hr && hf); if (!hr->hid_fields) hr->hid_fields = g_ptr_array_new(); g_ptr_array_add(hr->hid_fields, hf); } void add_hid_collection_child(Parsed_Hid_Collection * parent, Parsed_Hid_Collection * new_child) { if (!parent->child_collections) parent->child_collections = g_ptr_array_new(); g_ptr_array_add(parent->child_collections, new_child); } /* From the Device Class Definition for Human Interface Devices: Interpretation of Usage, Usage Minimum orUsage Maximum items vary as a function of the item's bSize field. If the bSize field = 3 then the item is interpreted as a 32 bit unsigned value where the high order 16 bits defines the Usage Page and the low order 16 bits defines the Usage ID. 32 bit usage items that define both the Usage Page and Usage ID are often referred to as "Extended" Usages. If the bSize field = 1 or 2 then the Usage is interpreted as an unsigned value that selects a Usage ID on the currently defined Usage Page. When the parser encounters a main item it concatenates the last declared Usage Page with a Usage to form a complete usage value. Extended usages can be used to override the currently defined Usage Page for individual usages. */ /* Creates an extended usage value from a usage page and usage value. * If the usage value size (usage_bsize) is 4 bytes, then it is already * and extended value and is returned. If it is 1 or 2 bytes, then it * represents a simple usage id and is combined with the usage page to * create an extended value. * * If usage_bsize is not in the range 1..4, then the extended value is * created heuristically. If the high order bytes of usage are non-zero, * the usage is assumed to be an extended usage and returned. If the high * order bytes of usage are 0, it is treated as a simple usage id and is * combined with with usage_page to create the extended usage value. * * Arguments: * usage_page * usage * usage_bsize 3 or 4 indicates a 4 byte value * * Returns: extended usage value */ uint32_t extended_usage(uint16_t usage_page, uint32_t usage, int usage_bsize) { bool debug = false; uint32_t result = 0; if (usage_bsize == 3 || usage_bsize == 4) // allow it to be indicator (3) or actual number of bytes result = usage; else if (usage_bsize == 1 || usage_bsize == 2) { // assert( (usage & 0xffff0000) == 0); if ( (usage & 0xffff0000) != 0) { printf("(%s) usage_bsize=%d but usage = 0x%08x. As fixup, ignoring high order bytes\n", __func__, usage_bsize, usage); result = usage_page << 16 | (usage &0x00ff); printf("(%s) usage_page = 0x%04x, returning: 0x%08x\n", __func__, usage_page, result); } else result = usage_page <<16 | usage; } else if (usage & 0xff00) result = usage; else result = usage_page << 16 | usage; if (debug) { printf("(%s) usage_page=0x%04x, usage=0x%08x, usage_bsize=%d, returning 0x%08x\n", __func__, usage_page, usage, usage_bsize, result); } return result; } /* The data value in the report descriptor can be 1, 2, or 4 bytes. * In tokenized form, it is stored as a 4 byte unsigned integer. * This function looks at the high order bit of the original value * to determine if the value is negative. * * Arguments: * data data value, possibly expanded to 4 bytes * bytect number of bytes in original value * * Returns: signed value */ static int32_t maybe_signed_data(uint32_t data, int bytect) { bool debug = false; if (debug) printf("(%s) bytect = %d, data = 0x%0*x\n", __func__, bytect, 2*bytect, data); int32_t result = 0; assert(bytect == 0 || bytect == 1 || bytect==2 || bytect==4); if (bytect > 0) { unsigned int sign_bitno = (bytect * 8) - 1; uint32_t sign_mask = (uint32_t) 1 << sign_bitno; // cast to avoid clang warning // printf(" sign_bitno = %d, sign_mask=0x%08x\n", sign_bitno, sign_mask); if (data & sign_mask) result = -data; else result = data; } if (debug) printf("(%s) Returning: %d\n", __func__, result); return result; } /* Fully interpret a sequence of Hid_Report_Items * * Arguments: * head pointer to linked list of Hid_Report_Items * * Returns: parsed report descriptor */ // TODO: Should this function return NULL in case of invalid data (e.g. more end than start collections)? Parsed_Hid_Descriptor * parse_hid_report_desc_from_item_list(Hid_Report_Descriptor_Item * items_head) { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); char *types[4] = { "Main", "Global", "Local", "reserved" }; Cur_Report_Globals * cur_globals = calloc(1, sizeof(struct cur_report_globals)); Cur_Report_Locals * cur_locals = calloc(1, sizeof(struct cur_report_locals)); Parsed_Hid_Collection * cur_collection = NULL; Parsed_Hid_Descriptor * parsed_descriptor = calloc(1, sizeof(Parsed_Hid_Descriptor)); parsed_descriptor->root_collection = calloc(1,sizeof(Parsed_Hid_Collection)); parsed_descriptor->root_collection->is_root_collection = true; parsed_descriptor->valid_descriptor = true; // set false if invalid, should never occur #define COLLECTION_STACK_SIZE 10 Parsed_Hid_Collection * collection_stack[COLLECTION_STACK_SIZE]; collection_stack[0] = parsed_descriptor->root_collection; int collection_stack_cur = 0; Hid_Report_Descriptor_Item * item = items_head; while(item) { if (debug) { char datastr[20]; snprintf(datastr, 20, "[0x%0*x] %d", item->bsize_bytect*2, item->data, item->data); printf("(%s) Item(%-6s): %s, data=%s\n", __func__, types[item->btype], devid_hid_descriptor_item_type(item->btag), datastr); } switch (item->btype) { // Main item tags case 0: // Main item switch(item->btag) { case 0xa0: // Collection { cur_collection = calloc(1, sizeof(Parsed_Hid_Collection)); cur_collection->collection_type = item->data; cur_collection->usage_page = cur_globals->usage_page; uint32_t cur_usage = 0; if (cur_locals->usages && cur_locals->usages->len > 0) { cur_usage = g_array_index(cur_locals->usages, uint32_t, 0); // cur_collection->usage_id = cur_usage; // deprecated } else { printf("(%s) No usage id has been set for collection\n", __func__); } if (cur_usage) { cur_collection->extended_usage = extended_usage( cur_globals->usage_page, cur_usage, cur_locals->usage_bsize_bytect); // or 0 to use heuristic } else { // what to do if there was no usage value? // makes no sense to combine it with usage page printf("(%s) Collection has no usage value\n", __func__); } cur_collection->reports = g_ptr_array_new(); // add this collection as a child of the parent collection add_hid_collection_child(collection_stack[collection_stack_cur], cur_collection); assert(collection_stack_cur < COLLECTION_STACK_SIZE-1); collection_stack[++collection_stack_cur] = cur_collection; break; } case 0x80: /* Input */ case 0x90: /* Output */ case 0xb0: /* Feature */ { Parsed_Hid_Field * hf = calloc(1, sizeof(Parsed_Hid_Field)); Byte report_type; if (item->btag == 0x80) report_type = HID_REPORT_TYPE_INPUT; else if (item->btag == 0x90) report_type = HID_REPORT_TYPE_OUTPUT; else report_type = HID_REPORT_TYPE_FEATURE; hf->item_flags = item->data; uint16_t report_id = cur_globals->report_id; Parsed_Hid_Report * hr = find_hid_report_or_new( cur_collection, report_type, report_id); // add this item/field to current report add_report_field(hr, hf); #ifdef OLD int field_index = hr->hid_fields->len - 1; // field number within report // if multiple usages, does this apply to fields within report or // occurrences within field ??? // WRONG! if (cur_locals->usages && cur_locals->usages->len > 0) { int usagect = cur_locals->usages->len; int usagendx = (field_index < usagect) ? field_index : usagect-1; uint32_t this_usage = g_array_index(cur_locals->usages, uint32_t, usagendx); hf->extended_usage = extended_usage(cur_globals->usage_page, this_usage, cur_locals->usage_bsize_bytect); // or 0 to use heuristic if (debug) { printf("(%s) item 0x%02x, usagect=%d, usagendx=%d, this_usage=0x%04x\n", __func__, item->btag, usagect, usagendx, this_usage); } } else { // message unnecessary here, warning will be issued by report_parsed_hid_report() if (debug) { printf("(%s) Tag 0x%02x, Report id: %d 0x%02x: No usage values in cur_locals\n", __func__, item->btag, report_id, report_id); } } #endif if ( ( cur_locals->usage_minimum && !cur_locals->usage_maximum) || (!cur_locals->usage_minimum && cur_locals->usage_maximum) ) { printf("(%s) Either both or neither usage_minimum or usage_maximum must be specified\n", __func__); parsed_descriptor->valid_descriptor = false; } if (cur_locals->usage_minimum) hf->min_extended_usage = extended_usage(cur_globals->usage_page, cur_locals->usage_minimum, 0); if (cur_locals->usage_maximum) hf->max_extended_usage = extended_usage(cur_globals->usage_page, cur_locals->usage_maximum, 0); if (cur_locals->usages && cur_locals->usages->len > 0) { hf->extended_usages = g_array_new(true, true, sizeof(uint32_t)); for (int ndx = 0; ndx < cur_locals->usages->len; ndx++) { uint32_t ausage = g_array_index(cur_locals->usages, uint32_t, ndx); uint32_t extusage = extended_usage(cur_globals->usage_page, ausage, 0); g_array_append_val(hf->extended_usages, extusage ); } } hf->usage_page = cur_globals->usage_page; hf->report_size = cur_globals->report_size; hf->report_count = cur_globals->report_count; hf->unit_exponent = cur_globals->unit_exponent; hf->unit = cur_globals->unit; hf->logical_minimum = cur_globals->logical_minimum; hf->logical_maximum = cur_globals->logical_maximum; /* From the HID Device Class Definition spec section 6.2.2.7: Until Physical Minimum and Physical Maximum are declared in a report descriptor they are assumed by the HID parser to be equal to Logical Minimum and Logical Maximum, respectively. After declaring them to so that they can applied to a (Input, Output or Feature) main item they continue to effect all subsequent main items. If both the Physical Minimum and Physical Maximum extents are equal to 0 then they will revert to their default interpretation. */ #ifdef WRONG // see section 6.2.2.7 for correct algorithm hf->physical_minimum = (cur_globals->physical_minimum) ? cur_globals->physical_minimum : cur_globals->logical_minimum; hf->physical_maximum = (cur_globals->physical_maximum) ? cur_globals->physical_maximum : cur_globals->logical_maximum; #endif hf->physical_minimum = cur_globals->physical_minimum; hf->physical_maximum = cur_globals->physical_maximum; #define UNHANDLED(F) \ if (cur_locals->F) \ printf("%s) Tag 0x%02x, Unimplemented: %s\n", __func__, item->btag, #F); UNHANDLED(designator_indexes) UNHANDLED(designator_minimum) UNHANDLED(designator_maximum) UNHANDLED(string_indexes) UNHANDLED(string_minimum) UNHANDLED(string_maximum) #undef UNHANDLED break; } case 0xc0: // End Collection if (collection_stack_cur == 0) { printf("(%s) End Collection item without corresponding Collection\n", __func__); // Need to do anything more to recover? } else collection_stack_cur--; break; default: break; } // switch(btag) free_cur_report_locals(cur_locals); cur_locals = calloc(1, sizeof(struct cur_report_locals)); break; // Global item tags case 1: // Global item switch (item->btag) { case 0x04: /* Usage Page */ cur_globals->usage_page = item->data; break; case 0x14: // Logical Minimum cur_globals->logical_minimum = maybe_signed_data(item->data, item->bsize_bytect); break; case 0x24: cur_globals->logical_maximum = maybe_signed_data(item->data, item->bsize_bytect); break; case 0x34: cur_globals->physical_minimum = maybe_signed_data(item->data, item->bsize_bytect); break; case 0x44: cur_globals->physical_maximum = maybe_signed_data(item->data, item->bsize_bytect);; break; case 0x54: // Unit Exponent cur_globals->unit_exponent = item->data; // Global break; case 0x64: // Unit cur_globals->unit = item->data; // ?? // Global break; case 0x74: cur_globals->report_size = item->data; break; case 0x84: cur_globals->report_id = item->data; break; case 0x94: cur_globals->report_count = item->data; break; case 0xa4: // Push { Cur_Report_Globals* old_globals = cur_globals; cur_globals = calloc(1, sizeof(Cur_Report_Globals)); cur_globals->prev = old_globals; break; } case 0xb4: // Pop if (!cur_globals->prev) { printf("(%s) Invalid item Pop without previous Push\n", __func__); } else { Cur_Report_Globals * popped_globals = cur_globals; cur_globals = cur_globals->prev; free(popped_globals); } break; default: printf("(%s) Invalid global item tag: 0x%02x\n", __func__, item->btag); } // switch(btag) break; // Local item tags case 2: // Local item switch(item->btag) { case 0x08: // Usage { if (debug) printf("(%s) tag 0x08 (Usage), bsize_bytect=%d, value=0x%08x %d\n", __func__, item->bsize_bytect, item->data, item->data); if (cur_locals->usages == NULL) cur_locals->usages = g_array_new( /* null terminated */ false, /* init to 0 */ true, /* field size */ sizeof(uint32_t) ); g_array_append_val(cur_locals->usages, item->data); if (cur_locals->usages->len > 1) { if (debug) printf("(%s) After append, cur_locals->usages->len = %d\n", __func__, cur_locals->usages->len); } if (cur_locals->usages->len == 1) cur_locals->usage_bsize_bytect = item->bsize_bytect; else { if (item->bsize_bytect != cur_locals->usage_bsize_bytect && cur_locals->usage_bsize_bytect != 0) // avoid redundant messages { printf("(%s) Warning: Multiple usages for fields have different size values\n", __func__); printf(" Switching to heurisitic interpretation of usage\n"); cur_locals->usage_bsize_bytect = 0; } } break; } case 0x18: // Usage minimum cur_locals->usage_minimum = item->data; break; case 0x28: cur_locals->usage_maximum = item->data; break; case 0x38: // designator index // TODO: same as 0x08 Usage printf("(%s) Local item value 0x38 (Designator Index) unimplemented\n", __func__); break; case 0x48: cur_locals->designator_minimum = item->data; break; case 0x58: cur_locals->designator_maximum = item->data; break; case 0x78: // string index // TODO: same as 0x08 Usage printf("(%s) Local item value 0x78 (String Index) unimplemented\n", __func__); break; case 0x88: cur_locals->string_minimum = item->data; break; case 0x98: cur_locals->string_maximum = item->data; break; case 0xa8: // delimiter - defines beginning or end of set of local items // what to do? printf("(%s) Local item Delimiter unimplemented\n", __func__); break; default: printf("(%s) Invalid local item tag: 0x%02x\n", __func__, item->btag); } break; default: printf("(%s) Invalid item type: 0x%04x\n", __func__, item->btype); } item = item->next; } free_cur_report_locals(cur_locals); // Free the globals stack, in case there's anything on it Cur_Report_Globals * prev_globals = NULL; while (cur_globals) { prev_globals = cur_globals->prev; free(cur_globals); cur_globals = prev_globals; } return parsed_descriptor; } /* Parse and interpret the bytes of a HID report descriptor. * * Arguments: * b address of first byte * desclen number of bytes * * Returns: parsed report descriptor */ Parsed_Hid_Descriptor * parse_hid_report_desc(Byte * b, int desclen) { bool debug = false; if (debug) printf("(%s) Starting. b=%p, desclen=%d\n", __func__, b, desclen); Hid_Report_Descriptor_Item * item_list = tokenize_hid_report_descriptor(b, desclen) ; Parsed_Hid_Descriptor * result = parse_hid_report_desc_from_item_list(item_list); free_hid_report_item_list(item_list); return result; } // // Functions that extract information from a Parsed_Hid_Descriptor // /* Indicates if a parsed HID Report Descriptor represents a USB connected monitor. * * Arguments: * phd pointer parsed HID Report Descriptor * * Returns: true/false * * Per section 5.5 of USB Monitor Control Class Specification Rev 1.0: * "In order to identify a HID class device as a monitor, the device's * HID Report Descriptor must contain a top-level collection with a usage * of Monitor Control from the USB Monitor Usage Page." * * i.e. Usage page = 0x80 USB monitor * Usage id = 0x01 Monitor Control */ bool is_monitor_by_parsed_hid_report_descriptor(Parsed_Hid_Descriptor * phd) { bool is_monitor = false; Parsed_Hid_Collection * root_collection = phd->root_collection; for (int ndx = 0; ndx < root_collection->child_collections->len; ndx++) { Parsed_Hid_Collection * col = g_ptr_array_index(root_collection->child_collections, ndx); if (col->extended_usage == (0x0080 << 16 | 0x0001) ) { is_monitor = true; break; } } return is_monitor; } uint16_t get_vcp_code_from_parsed_hid_report(Parsed_Hid_Report * rpt) { uint16_t vcp_code = 0; if (rpt->report_type == HID_REPORT_TYPE_FEATURE && rpt->hid_fields && rpt->hid_fields->len == 1) { Parsed_Hid_Field * f = g_ptr_array_index(rpt->hid_fields, 0); // n. ignoring possibility of report count > 1, multiple usages if (f->usage_page == 0x80) { // vcp_code = f->extended_usage & 0xffff; vcp_code = g_array_index(f->extended_usages, uint32_t, 0) & 0xffff; assert( (vcp_code & 0xff00) == 0); } } return vcp_code; } void dbgrpt_vcp_code_report(Vcp_Code_Report * vcr, int depth) { int d1 = depth+1; rpt_structure_loc("Vcp_Code_Report", vcr, depth); rpt_vstring(d1, "%-20s %d 0x%02x", "vcp_code", vcr->vcp_code, vcr->vcp_code); rpt_vstring(d1, "%-20s %p", "rpt", vcr->rpt); dbgrpt_parsed_hid_report(vcr->rpt, d1); } void dbgrpt_vcp_code_report_array(GPtrArray * vcr_array, int depth) { rpt_vstring(depth, "Vcp_Code_Report array at %p contains %d entries:", vcr_array, vcr_array->len); int d1 = depth+1; for (int ndx=0; ndx < vcr_array->len; ndx++) { dbgrpt_vcp_code_report( g_ptr_array_index(vcr_array, ndx), d1); } } void summarize_vcp_code_report(Vcp_Code_Report * vcr, int depth) { // int d1 = depth+1; // rpt_vstring(depth, "%-20s %d 0x%02x", "vcp_code", vcr->vcp_code, vcr->vcp_code); // rpt_vstring(d1, "%-20s %d 0x%02x", "report_id", vcr->rpt->report_id, vcr->rpt->report_id); rpt_vstring(depth, "vcp code: 0x%02x (%3d), report id: 0x%02x (%3d), report type: 0x%02x (%s)", vcr->vcp_code, vcr->vcp_code, vcr->rpt->report_id, vcr->rpt->report_id, vcr->rpt->report_type, hid_report_type_name(vcr->rpt->report_type)); } void summarize_vcp_code_report_array(GPtrArray * vcr_array, int depth) { // rpt_vstring(depth, "VCP code reports:"); // int d1 = depth+1; for (int ndx=0; ndx < vcr_array->len; ndx++) { summarize_vcp_code_report( g_ptr_array_index(vcr_array, ndx), depth); } } /* Per the spec, e.g. USB Monitor Control Class Spec section 5.5, there can be * multiple top application collections, one of which must be a monitor application. * In practice, we've only seen a single top level application collection, but for * generality this function selects the monitor application from a parsed HID descriptor. */ // May be null in case where device was forced to be a monitor for // testing purposes based on its vid/pid Parsed_Hid_Collection * get_monitor_application_collection(Parsed_Hid_Descriptor * phd) { bool debug = false; if (debug) printf("(%s) Starting. phd=%p\n", __func__, phd); Parsed_Hid_Collection * result = NULL; Parsed_Hid_Collection * root_collection = phd->root_collection; for (int ndx = 0; ndx < root_collection->child_collections->len; ndx++) { Parsed_Hid_Collection * col = g_ptr_array_index(root_collection->child_collections, ndx); if (debug) printf("(%s) extended_usage = 0x%08x\n", __func__, col->extended_usage); if (col->extended_usage == (0x0080 << 16 | 0x0001) ) { result = col; break; } } if (debug) printf("(%s) Returning: %p\n", __func__, result); return result; } static int compare_vcp_code_report(gconstpointer first, gconstpointer second) { int result = 0; const Vcp_Code_Report * a = first; const Vcp_Code_Report * b = second; if (a->vcp_code < b->vcp_code) result = -1; else if (a->vcp_code > b->vcp_code) result = 1; return result; } /* Gets table of VCP codes and the reports that implement them. * * Arguments: phd pointer to parsed HID descriptor * * Returns: array of Vco_Code_Report */ GPtrArray * get_vcp_code_reports(Parsed_Hid_Descriptor * phd) { bool debug = false; if (debug) printf("(%s) Starting. phd=%p\n", __func__, phd); // May be null in case where device was forced to be a monitor for // testing purposds based on its vid/pid Parsed_Hid_Collection * col = get_monitor_application_collection(phd); GPtrArray * vcp_reports = g_ptr_array_new(); // Simplifying assumptions: // report has only one field if (col && col->reports) { for (int ndx = 0; ndx < col->reports->len; ndx++) { Parsed_Hid_Report * rpt = g_ptr_array_index(col->reports, ndx); if (rpt->report_type == HID_REPORT_TYPE_FEATURE) { if (rpt->hid_fields && rpt->hid_fields->len == 1) { Parsed_Hid_Field * f = g_ptr_array_index(rpt->hid_fields, 0); if (debug) report_hid_field(f, 5); if (f->usage_page == 0x0082 && f->report_size == 8 ) { // Have seen cases where usage ID == 0, e.g. Apple Cinema Display report xe7 // ignore such // Byte vcp_feature_code = f->extended_usage & 0xff; // TO DO: Handle case of min_usage/max_usage if (f->extended_usages) { Byte vcp_feature_code = g_array_index(f->extended_usages, uint32_t, 0) & 0xffff; if (vcp_feature_code) { Vcp_Code_Report * code_rpt = calloc(1, sizeof(Vcp_Code_Report)); code_rpt->vcp_code = vcp_feature_code; code_rpt->rpt = rpt; g_ptr_array_add(vcp_reports, code_rpt); } else { if (debug) printf("(%s) Ignoring report with usage_id = 0\n", __func__); } } } } } } } // sort array by vcp code g_ptr_array_sort(vcp_reports, compare_vcp_code_report); if (debug) { printf("(%s) Returning array of %d reports at %p\n", __func__, vcp_reports->len, vcp_reports); dbgrpt_vcp_code_report_array(vcp_reports, 1); } return vcp_reports; } /* Gets Parsed_Hid_Report for the EDID * * Arguments: phd pointer to parsed HID descriptor * * Returns: Parsed_Hid_Report for EDID */ Parsed_Hid_Report * find_edid_report_descriptor(Parsed_Hid_Descriptor * phd) { bool debug = false; if (debug) printf("(%s) Starting. phd=%p\n", __func__, phd); Parsed_Hid_Collection * col = get_monitor_application_collection(phd); Parsed_Hid_Report * edid_report = NULL; if (col && col->reports) { for (int ndx = 0; ndx < col->reports->len; ndx++) { Parsed_Hid_Report * rpt = g_ptr_array_index(col->reports, ndx); if (rpt->report_type == HID_REPORT_TYPE_FEATURE) { if (rpt->hid_fields && rpt->hid_fields->len == 1) { Parsed_Hid_Field * f = g_ptr_array_index(rpt->hid_fields, 0); if (f->extended_usages && f->extended_usages->len == 1) { uint32_t extusage = g_array_index(f->extended_usages, uint32_t, 0); if (extusage == ((0x0080 << 16) | 0x0002) && (f->item_flags & HID_FIELD_BUFFERED_BYTE) && f->report_size == 8 && f->report_count >= 128 ) { edid_report = rpt; break; } } } } } } return edid_report; } ddcutil-2.2.0/src/usb_util/hidraw_util.h0000664000175000001440000000210014754576332013734 /* hidraw_util.h * * * * Copyright (C) 2016 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef HIDRAW_UTIL_H_ #define HIDRAW_UTIL_H_ void probe_hidraw(bool show_monitors_only, int depth); bool hidraw_is_monitor_device(char * devname); #endif /* _HIDRAW_UTIL_H_ */ ddcutil-2.2.0/src/usb_util/base_hid_report_descriptor.h0000664000175000001440000000415514754576332017024 /* base_hid_report_descriptor.h * * Functions to perform basic parsing of the HID Report Descriptor and * display the contents of the Report Descriptor in the format used * in HID documentation. * * * Copyright (C) 2016 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef BASE_HID_REPORT_DESCRIPTOR_H_ #define BASE_HID_REPORT_DESCRIPTOR_H_ #include #include "util/coredefs.h" typedef struct hid_report_item { struct hid_report_item * next; Byte raw_bytes[5]; Byte btype; // 0=Main, 1=Global, 2=Local, prefix bits 2-3 Byte btag; Byte bsize_bytect; // number of bytes, as opposed to indicator, i.e 4 means 4 bytes uint32_t data; // alternative, as done in struct hid_item in kernel header file hid.h: union { uint8_t u8; int8_t s8; uint16_t u16; int8_t s16; uint32_t u32; int32_t s32; uint8_t *longdata; } data_alt; } Hid_Report_Descriptor_Item; void report_hid_report_item_list(Hid_Report_Descriptor_Item * head, int depth); void free_hid_report_item_list(Hid_Report_Descriptor_Item * head); Hid_Report_Descriptor_Item * tokenize_hid_report_descriptor(Byte * b, int l) ; bool is_monitor_by_tokenized_hid_report_descriptor(Hid_Report_Descriptor_Item * report_item_list); #endif /* BASE_HID_REPORT_DESCRIPTOR_H_ */ ddcutil-2.2.0/src/usb_util/libusb_reports.h0000664000175000001440000001440014754576332014465 /* libusb_reports.h * * libusb is not currently used by ddcutil. This code is retained for reference. * * * Copyright (C) 2016-2018 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ // Adapted from usbplay2 file libusb_util.h #ifndef LIBUSB_REPORTS_H_ #define LIBUSB_REPORTS_H_ #include // need pkgconfig? #include // #include #include "util/coredefs.h" #define LIBUSB_EXIT true #define LIBUSB_CONTINUE false #define REPORT_LIBUSB_ERROR(_funcname, _errno, _exit_on_error) \ do { \ fprintf(stderr, "(%s) " _funcname " returned %d (%s): %s\n", \ __func__, \ _errno, \ libusb_error_name(_errno), \ libusb_strerror(_errno) \ ); \ if (_exit_on_error) \ exit(1); \ } while(0); #define REPORT_LIBUSB_ERROR_NOEXIT(_funcname, _errno) \ do { \ fprintf(stderr, "(%s) " _funcname " returned %d (%s): %s\n", \ __func__, \ _errno, \ libusb_error_name(_errno), \ libusb_strerror(_errno) \ ); \ } while(0); #define CHECK_LIBUSB_RC(_funcname, _rc, _exit_on_error) \ do { \ if (_rc < 0) { \ fprintf(stderr, "(%s) " _funcname " returned %d (%s): %s\n", \ __func__, \ _rc, \ libusb_error_name(_rc), \ libusb_strerror(_rc) \ ); \ if (_exit_on_error) \ exit(1); \ } \ } while(0); // Initialization void init_libusb_reports(); // initialize lookup tables // Lookup descriptive names of constants char * descriptor_title(Byte val); char * endpoint_direction_title(Byte val); char * transfer_type_title(Byte val); char * class_code_title(Byte val); // Misc utilities char * lookup_libusb_string( struct libusb_device_handle * dh, int string_id); #ifdef UNUSED wchar_t * lookup_libusb_string_wide(struct libusb_device_handle * dh, int string_id); #endif // Report functions for libusb data structures void report_libusb_endpoint_descriptor( const struct libusb_endpoint_descriptor * epdesc, libusb_device_handle * dh, // may be null int depth); void report_libusb_interface_descriptor( const struct libusb_interface_descriptor * inter, libusb_device_handle * dh, // may be null int depth); void report_libusb_interface( const struct libusb_interface * interface, libusb_device_handle * dh, // may be null int depth) ; void report_libusb_config_descriptor( const struct libusb_config_descriptor * config, libusb_device_handle * dh, // may be null int depth); void report_libusb_device_descriptor( const struct libusb_device_descriptor * desc, libusb_device_handle * dh, // may be null int depth); void report_libusb_device( libusb_device * dev, bool show_hubs, int depth); void report_libusb_devices( libusb_device ** devs, bool show_hubs, int depth); #ifdef OLD bool get_raw_report_descriptor_old( struct libusb_device_handle * dh, uint8_t bInterfaceNumber, uint16_t rptlen, // report length Byte * dbuf, int dbufsz, int * pbytes_read); #endif bool get_raw_report_descriptor( struct libusb_device_handle * dh, uint8_t bInterfaceNumber, uint16_t rptlen, // report length Byte * dbuf, int dbufsz, int * pbytes_read); bool get_raw_report( struct libusb_device_handle * dh, uint8_t bInterfaceNumber, uint8_t report_id, uint16_t rptlen, // report length Byte * dbuf, int dbufsz, int * pbytes_read); bool is_hub_descriptor(const struct libusb_device_descriptor * desc); // really belongs elsewhere typedef struct __attribute__((__packed__)) hid_class_descriptor { uint8_t bDescriptorType; uint16_t wDescriptorLength; } HID_Class_Descriptor; typedef struct __attribute__((__packed__)) hid_descriptor { uint8_t bLength; uint8_t bDescriptorType; uint16_t bcdHID; uint8_t bCountryCode; uint8_t bNumDescriptors; // number of class descriptors, always at least 1, i.e. Report descriptor uint8_t bClassDescriptorType; // start of first class descriptor uint16_t wClassDescriptorLength; } HID_Descriptor; void report_hid_descriptor( libusb_device_handle * dh, uint8_t bInterfaceNumber, HID_Descriptor * desc, int depth); #endif /* LIBUSB_REPORTS_H_ */ ddcutil-2.2.0/src/usb_util/hid_report_descriptor.h0000644000175000001440000001264014754576332016026 /** @file hid_report_descriptor.h */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef HID_REPORT_DESCRIPTOR_H_ #define HID_REPORT_DESCRIPTOR_H_ #include #include "util/coredefs.h" #include "usb_util/base_hid_report_descriptor.h" #ifndef HID_FIELD_CONSTANT // Bits of item flags, as defined in hiddev.h // Define them here if hiddev.h was not already included #define HID_FIELD_CONSTANT 0x001 #define HID_FIELD_VARIABLE 0x002 #define HID_FIELD_RELATIVE 0x004 #define HID_FIELD_WRAP 0x008 #define HID_FIELD_NONLINEAR 0x010 #define HID_FIELD_NO_PREFERRED 0x020 #define HID_FIELD_NULL_STATE 0x040 #define HID_FIELD_VOLATILE 0x080 #define HID_FIELD_BUFFERED_BYTE 0x100 #endif // values identical to those for HID_REPORT_TYPE_* in hiddev.h: #define HID_REPORT_TYPE_INPUT 1 #define HID_REPORT_TYPE_OUTPUT 2 #define HID_REPORT_TYPE_FEATURE 3 #define HID_REPORT_TYPE_MIN 1 #define HID_REPORT_TYPE_MAX 3 /* From the Device Class Definition for Human Interface Devices: Interpretation of Usage, Usage Minimum orUsage Maximum items vary as a function of the item's bSize field. If the bSize field = 3 then the item is interpreted as a 32 bit unsigned value where the high order 16 bits defines the Usage Page and the low order 16 bits defines the Usage ID. 32 bit usage items that define both the Usage Page and Usage ID are often referred to as "Extended" Usages. If the bSize field = 1 or 2 then the Usage is interpreted as an unsigned value that selects a Usage ID on the currently defined Usage Page. When the parser encounters a main item it concatenates the last declared Usage Page with a Usage to form a complete usage value. Extended usages can be used to override the currently defined Usage Page for individual usages. */ typedef struct parsed_hid_field { uint16_t item_flags; uint16_t usage_page; #ifdef OLD uint32_t extended_usage; // hi 16 bits usage_page, lo 16 bits usage_id #endif GArray * extended_usages; // new way, array of uint_32t, hi 16 bits usage page, lo 16 bits usage id uint32_t min_extended_usage; uint32_t max_extended_usage; /* The meaning of logical min/max vs physical/min max is the opposite of what one might expect. Logical refers to the values returned by the device. Physical refers to the "real world" bounds. Per section 6.2.2.7 of the HID Device Class Definition v 1.11: While Logical Minimum and Logical Maximum (extents) bound the values returned by a device, Physical Minimum and Physical Maximum give meaning to those bounds by allowing the report value to be offset and scaled. For example, a thermometer might have logical extents of 0 and 999 but physical extents of 32 and 212 degrees. */ int16_t logical_minimum; int16_t logical_maximum; int16_t physical_minimum; int16_t physical_maximum; uint16_t report_size; uint16_t report_count; uint16_t unit_exponent; uint16_t unit; } Parsed_Hid_Field; typedef struct parsed_hid_report { uint16_t report_id; Byte report_type; GPtrArray * hid_fields; // array of pointers to Parsed_Hid_Field } Parsed_Hid_Report; typedef struct parsed_hid_collection { uint16_t usage_page; uint32_t extended_usage; Byte collection_type; bool is_root_collection; GPtrArray * reports; // array of pointers to Parsed_Hid_Report GPtrArray * child_collections; // array of pointers to Parsed_Hid_Collection } Parsed_Hid_Collection; typedef struct parsed_hid_descriptor { bool valid_descriptor; Parsed_Hid_Collection * root_collection; } Parsed_Hid_Descriptor; void free_parsed_hid_descriptor(Parsed_Hid_Descriptor * phd); Parsed_Hid_Descriptor * parse_hid_report_desc_from_item_list(Hid_Report_Descriptor_Item * items_head); Parsed_Hid_Descriptor * parse_hid_report_desc(Byte * b, int desclen); void dbgrpt_parsed_hid_report(Parsed_Hid_Report * hr, int depth); void summarize_parsed_hid_report(Parsed_Hid_Report * hr, int depth); void dbgrpt_parsed_hid_descriptor(Parsed_Hid_Descriptor * pdesc, int depth); bool is_monitor_by_parsed_hid_report_descriptor(Parsed_Hid_Descriptor * phd); // TODO: use same bit values as item type? will that work? // TODO: poor names typedef enum hid_report_type_enum { HIDF_REPORT_TYPE_NONE = 0x00, HIDF_REPORT_TYPE_INPUT = 0x02, // == 1 << HID_REPORT_TYPE_INPUT HIDF_REPORT_TYPE_OUTPUT = 0x04, // == 1 << HID_REPORT_TYPE_OUTPUT HIDF_REPORT_TYPE_FEATURE = 0x08, // == 1 << HID_REPORT_TYPE_FEATURE HIDF_REPORT_TYPE_ANY = 0xff } Hid_Report_Type_Enum; GPtrArray * select_parsed_hid_report_descriptors(Parsed_Hid_Descriptor * phd, Byte report_type_flags); typedef struct vcp_code_report { uint8_t vcp_code; Parsed_Hid_Report * rpt; } Vcp_Code_Report; void dbgrpt_vcp_code_report(Vcp_Code_Report * vcr, int depth); void dbgrpt_vcp_code_report_array(GPtrArray * vcr_array, int depth); void summarize_vcp_code_report(Vcp_Code_Report * vcr, int depth); void summarize_vcp_code_report_array(GPtrArray * vcr_array, int depth); GPtrArray * get_vcp_code_reports(Parsed_Hid_Descriptor * phd); Parsed_Hid_Report * find_edid_report_descriptor(Parsed_Hid_Descriptor * phd); #endif /* HID_REPORT_DESCRIPTOR_H_ */ ddcutil-2.2.0/src/usb_util/hiddev_reports.h0000644000175000001440000000156514754576332014456 /** @file hiddev_reports.h */ // Copyright (C) 2016-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef HIDDEV_REPORTS_H_ #define HIDDEV_REPORTS_H_ #include #include void init_hiddev_reports(); void dbgrpt_hiddev_devinfo(struct hiddev_devinfo * devinfo, bool lookup_names, int depth); void dbgrpt_hiddev_device_by_fd(int fd, int depth); void dbgrpt_hiddev_usage_ref(struct hiddev_usage_ref * uref, int depth); void dbgrpt_hiddev_usage_ref_multi(struct hiddev_usage_ref_multi * uref_multi, int depth); void dbgrpt_hiddev_report_info(struct hiddev_report_info * rinfo, int depth); void dbgrpt_hiddev_field_info(struct hiddev_field_info * finfo, int depth); char * hiddev_interpret_report_id(__u32 report_id); char * hiddev_interpret_usage_code(int usage_code ); #endif /* UTIL_HIDDEV_REPORTS_H_ */ ddcutil-2.2.0/src/usb_util/hiddev_util.h0000644000175000001440000000572214754576332013734 /** @file hiddev_util.h */ // Copyright (C) 2016-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef HIDDEV_UTIL_H_ #define HIDDEV_UTIL_H_ #include #include // so callers will have definition of strerror() used in REPORT_IOCTL_ERROR macro: #include #include "util/data_structures.h" #include "util/debug_util.h" #include "util/edid.h" // The define is used within directory usb_util. // The more general REPORT_USB_ERROR is defined in base/core.h, so is unavailable // at the util level. #define REPORT_USB_IOCTL_ERROR(_ioctl_name, _errno) \ do { \ printf("(%s) ioctl(%s) failed. errno=%d: %s\n", \ __func__, \ _ioctl_name, \ _errno, \ strerror(_errno) \ ); \ printf("(%s) Backtrace:\n", __func__); \ show_backtrace(2); \ } while(0) #define HID_REPORT_TYPE_INPUT_FG (1 << HID_REPORT_TYPE_INPUT) #define HID_REPORT_TYPE_OUTPUT_FG (1 << HID_REPORT_TYPE_OUTPUT) #define HID_REPORT_TYPE_FEATURE_FG (1 << HID_REPORT_TYPE_FEATURE) // Identifies a field within a report // n. names of structs in hiddev.h begin with "hiddev_", so using that prefix // for the following struct would be confusing struct hid_field_locator { struct hiddev_field_info * finfo; // simplify by eliminating? __u32 report_type; __u32 report_id; __u32 field_index; }; void free_hid_field_locator(struct hid_field_locator * location); void report_hid_field_locator(struct hid_field_locator * ploc, int depth); // n. hiddev.h contains declarations of structs, but not functions, so // prefixing the following functions with "hiddev_" does not lead to confusion struct hid_field_locator* hiddev_find_report(int fd, __u32 report_type, __u32 ucode, bool match_all_ucodes); Buffer * hiddev_get_multibyte_report_value_by_hid_field_locator(int fd, struct hid_field_locator * loc); Buffer * hiddev_get_edid(int fd); Buffer * hiddev_get_multibyte_value_by_report_type_and_ucode(int fd, __u32 report_type, __u32 usage_code, __u32 num_values); Buffer * hiddev_get_multibyte_value_by_ucode(int fd, __u32 usage_code, __u32 num_values); const char * hiddev_report_type_name(__u32 report_type); bool force_hiddev_monitor(int fd); bool is_hiddev_monitor(int fd); GPtrArray * get_hiddev_device_names_using_udev(); GPtrArray * get_hiddev_device_names_using_filesys(); GPtrArray * get_hiddev_device_names(); char * get_hiddev_name(int fd); bool hiddev_is_field_edid(int fd, struct hiddev_report_info * rinfo, int field_index); __u32 hiddev_get_identical_ucode(int fd, struct hiddev_field_info * finfo, __u32 actual_field_index); Buffer * hiddev_collect_single_byte_usage_values( int fd, struct hiddev_field_info * finfo, __u32 field_index); #endif /* HIDDEV_UTIL_H_ */ ddcutil-2.2.0/src/usb_util/usb_hid_common.h0000644000175000001440000000111714754576332014413 /** @file usb_hid_common.h * * Functions that are common to the wrappers for multiple USB HID * packages such as libusb, hiddev */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef USB_HID_COMMON_H_ #define USB_HID_COMMON_H_ /** \cond */ #include #include /** \endcond */ const char * collection_type_name(uint8_t collection_type); bool force_hid_monitor_by_vid_pid(int16_t vid, int16_t pid); bool deny_hid_monitor_by_vid_pid(int16_t vid, int16_t pid); #endif /* USB_HID_COMMON_H_ */ ddcutil-2.2.0/src/usb_util/libusb_util.h0000644000175000001440000000312014754576332013737 /** @file libusb_util.h */ // Copyright (C) 2014-2019 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef LIBUSB_UTIL_H_ #define LIBUSB_UTIL_H_ #include #include // #include #include "usb_util/libusb_reports.h" char *make_path(int bus_number, int device_address, int interface_number); char *make_path_from_libusb_device(libusb_device *dev, int interface_number); // bool possible_monitor_dev(libusb_device * dev, bool check_forced_monitor); // singly linked list of possible monitors typedef struct possible_monitor_device { libusb_device * libusb_device; int bus; int device_address; int alt_setting; int interface; gushort vid; gushort pid; char * manufacturer_name; char * product_name; // conversion is annoying, just retrieve both ascii and wchar version of the serial number // wchar_t * serial_number_wide; char * serial_number; // retrieved as ASCII, note some usages expect wchar struct possible_monitor_device * next; } Possible_Monitor_Device; struct possible_monitor_device * get_possible_monitors(); void report_possible_monitors(struct possible_monitor_device * mondev_head, int depth); #ifdef UNTESTED void free_possible_monitor_device_list(struct possible_monitor_device * head); #endif void probe_libusb(bool possible_monitors_only,int depth); bool libusb_is_monitor_by_path(gushort busno, gushort devno, gushort intfno); #endif /* LIBUSB_UTIL_H_ */ ddcutil-2.2.0/src/util/0000775000175000001440000000000014754576332010466 5ddcutil-2.2.0/src/util/Makefile.am0000644000175000001440000000446714754153540012443 # src/util/Makefile.am AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand clean-local: @echo "(src/util/Makefile) clean-local" mostlyclean-local: @echo "(src/util/Makefile) mostlyclean-local" distclean-local: @echo "(src/util/Makefile) distclean-local" # Intermediate Libraries noinst_LTLIBRARIES = libutil.la libutil_la_SOURCES = \ data_structures.c \ ddcutil_config_file.c \ debug_util.c \ backtrace.c \ edid.c \ error_info.c \ file_util.c \ file_util_base.c \ glib_util.c \ glib_string_util.c \ i2c_util.c \ linux_util.c \ msg_util.c \ multi_level_map.c \ pnp_ids.c \ regex_util.c \ report_util.c \ simple_ini_file.c \ string_util.c \ sysfs_util.c \ subprocess_util.c \ timestamp.c \ traced_function_stack.c \ utilrpt.c \ xdg_util.c if !ENABLE_TARGETBSD_COND libutil_la_SOURCES += \ sysfs_filter_functions.c \ sysfs_i2c_util.c endif if ENABLE_USB_COND libutil_la_SOURCES += \ device_id_util.c else if ENABLE_ENVCMDS_COND libutil_la_SOURCES += \ device_id_util.c endif endif if ENABLE_UDEV_COND libutil_la_SOURCES += \ udev_i2c_util.c \ udev_usb_util.c \ udev_util.c endif if ENABLE_FAILSIM_COND libutil_la_SOURCES += failsim.c endif if USE_LIBDRM_COND libutil_la_SOURCES += \ libdrm_util.c \ drm_common.c endif if USE_X11_COND libutil_la_SOURCES += x11_util.c endif # if ENABLE_YAML_COND # libutil_la_SOURCES += libyaml_dbgutil.c # endif # Rename to "all-local" for development all-local-disabled: @echo "" @echo "(src/util/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" ddcutil-2.2.0/src/util/Makefile.in0000664000175000001440000007410514754576155012465 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # src/util/Makefile.am VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @ENABLE_TARGETBSD_COND_FALSE@am__append_1 = \ @ENABLE_TARGETBSD_COND_FALSE@sysfs_filter_functions.c \ @ENABLE_TARGETBSD_COND_FALSE@sysfs_i2c_util.c @ENABLE_USB_COND_TRUE@am__append_2 = \ @ENABLE_USB_COND_TRUE@device_id_util.c @ENABLE_ENVCMDS_COND_TRUE@@ENABLE_USB_COND_FALSE@am__append_3 = \ @ENABLE_ENVCMDS_COND_TRUE@@ENABLE_USB_COND_FALSE@device_id_util.c @ENABLE_UDEV_COND_TRUE@am__append_4 = \ @ENABLE_UDEV_COND_TRUE@udev_i2c_util.c \ @ENABLE_UDEV_COND_TRUE@udev_usb_util.c \ @ENABLE_UDEV_COND_TRUE@udev_util.c @ENABLE_FAILSIM_COND_TRUE@am__append_5 = failsim.c @USE_LIBDRM_COND_TRUE@am__append_6 = \ @USE_LIBDRM_COND_TRUE@libdrm_util.c \ @USE_LIBDRM_COND_TRUE@drm_common.c @USE_X11_COND_TRUE@am__append_7 = x11_util.c subdir = src/util ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libutil_la_LIBADD = am__libutil_la_SOURCES_DIST = data_structures.c ddcutil_config_file.c \ debug_util.c backtrace.c edid.c error_info.c file_util.c \ file_util_base.c glib_util.c glib_string_util.c i2c_util.c \ linux_util.c msg_util.c multi_level_map.c pnp_ids.c \ regex_util.c report_util.c simple_ini_file.c string_util.c \ sysfs_util.c subprocess_util.c timestamp.c \ traced_function_stack.c utilrpt.c xdg_util.c \ sysfs_filter_functions.c sysfs_i2c_util.c device_id_util.c \ udev_i2c_util.c udev_usb_util.c udev_util.c failsim.c \ libdrm_util.c drm_common.c x11_util.c @ENABLE_TARGETBSD_COND_FALSE@am__objects_1 = \ @ENABLE_TARGETBSD_COND_FALSE@ sysfs_filter_functions.lo \ @ENABLE_TARGETBSD_COND_FALSE@ sysfs_i2c_util.lo @ENABLE_USB_COND_TRUE@am__objects_2 = device_id_util.lo @ENABLE_ENVCMDS_COND_TRUE@@ENABLE_USB_COND_FALSE@am__objects_3 = device_id_util.lo @ENABLE_UDEV_COND_TRUE@am__objects_4 = udev_i2c_util.lo \ @ENABLE_UDEV_COND_TRUE@ udev_usb_util.lo udev_util.lo @ENABLE_FAILSIM_COND_TRUE@am__objects_5 = failsim.lo @USE_LIBDRM_COND_TRUE@am__objects_6 = libdrm_util.lo drm_common.lo @USE_X11_COND_TRUE@am__objects_7 = x11_util.lo am_libutil_la_OBJECTS = data_structures.lo ddcutil_config_file.lo \ debug_util.lo backtrace.lo edid.lo error_info.lo file_util.lo \ file_util_base.lo glib_util.lo glib_string_util.lo i2c_util.lo \ linux_util.lo msg_util.lo multi_level_map.lo pnp_ids.lo \ regex_util.lo report_util.lo simple_ini_file.lo string_util.lo \ sysfs_util.lo subprocess_util.lo timestamp.lo \ traced_function_stack.lo utilrpt.lo xdg_util.lo \ $(am__objects_1) $(am__objects_2) $(am__objects_3) \ $(am__objects_4) $(am__objects_5) $(am__objects_6) \ $(am__objects_7) libutil_la_OBJECTS = $(am_libutil_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/backtrace.Plo \ ./$(DEPDIR)/data_structures.Plo \ ./$(DEPDIR)/ddcutil_config_file.Plo ./$(DEPDIR)/debug_util.Plo \ ./$(DEPDIR)/device_id_util.Plo ./$(DEPDIR)/drm_common.Plo \ ./$(DEPDIR)/edid.Plo ./$(DEPDIR)/error_info.Plo \ ./$(DEPDIR)/failsim.Plo ./$(DEPDIR)/file_util.Plo \ ./$(DEPDIR)/file_util_base.Plo \ ./$(DEPDIR)/glib_string_util.Plo ./$(DEPDIR)/glib_util.Plo \ ./$(DEPDIR)/i2c_util.Plo ./$(DEPDIR)/libdrm_util.Plo \ ./$(DEPDIR)/linux_util.Plo ./$(DEPDIR)/msg_util.Plo \ ./$(DEPDIR)/multi_level_map.Plo ./$(DEPDIR)/pnp_ids.Plo \ ./$(DEPDIR)/regex_util.Plo ./$(DEPDIR)/report_util.Plo \ ./$(DEPDIR)/simple_ini_file.Plo ./$(DEPDIR)/string_util.Plo \ ./$(DEPDIR)/subprocess_util.Plo \ ./$(DEPDIR)/sysfs_filter_functions.Plo \ ./$(DEPDIR)/sysfs_i2c_util.Plo ./$(DEPDIR)/sysfs_util.Plo \ ./$(DEPDIR)/timestamp.Plo \ ./$(DEPDIR)/traced_function_stack.Plo \ ./$(DEPDIR)/udev_i2c_util.Plo ./$(DEPDIR)/udev_usb_util.Plo \ ./$(DEPDIR)/udev_util.Plo ./$(DEPDIR)/utilrpt.Plo \ ./$(DEPDIR)/x11_util.Plo ./$(DEPDIR)/xdg_util.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libutil_la_SOURCES) DIST_SOURCES = $(am__libutil_la_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(LIBDRM_CFLAGS) \ $(GLIB_CFLAGS) AM_CFLAGS = $(AM_CFLAGS_STD) CLEANFILES = \ *expand # Intermediate Libraries noinst_LTLIBRARIES = libutil.la libutil_la_SOURCES = data_structures.c ddcutil_config_file.c \ debug_util.c backtrace.c edid.c error_info.c file_util.c \ file_util_base.c glib_util.c glib_string_util.c i2c_util.c \ linux_util.c msg_util.c multi_level_map.c pnp_ids.c \ regex_util.c report_util.c simple_ini_file.c string_util.c \ sysfs_util.c subprocess_util.c timestamp.c \ traced_function_stack.c utilrpt.c xdg_util.c $(am__append_1) \ $(am__append_2) $(am__append_3) $(am__append_4) \ $(am__append_5) $(am__append_6) $(am__append_7) all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/util/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/util/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libutil.la: $(libutil_la_OBJECTS) $(libutil_la_DEPENDENCIES) $(EXTRA_libutil_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libutil_la_OBJECTS) $(libutil_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/backtrace.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/data_structures.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ddcutil_config_file.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/debug_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/device_id_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/drm_common.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/edid.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error_info.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/failsim.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/file_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/file_util_base.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/glib_string_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/glib_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2c_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libdrm_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/linux_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/msg_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/multi_level_map.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pnp_ids.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/report_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/simple_ini_file.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/string_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/subprocess_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_filter_functions.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_i2c_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sysfs_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/timestamp.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/traced_function_stack.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/udev_i2c_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/udev_usb_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/udev_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/utilrpt.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/x11_util.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xdg_util.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/backtrace.Plo -rm -f ./$(DEPDIR)/data_structures.Plo -rm -f ./$(DEPDIR)/ddcutil_config_file.Plo -rm -f ./$(DEPDIR)/debug_util.Plo -rm -f ./$(DEPDIR)/device_id_util.Plo -rm -f ./$(DEPDIR)/drm_common.Plo -rm -f ./$(DEPDIR)/edid.Plo -rm -f ./$(DEPDIR)/error_info.Plo -rm -f ./$(DEPDIR)/failsim.Plo -rm -f ./$(DEPDIR)/file_util.Plo -rm -f ./$(DEPDIR)/file_util_base.Plo -rm -f ./$(DEPDIR)/glib_string_util.Plo -rm -f ./$(DEPDIR)/glib_util.Plo -rm -f ./$(DEPDIR)/i2c_util.Plo -rm -f ./$(DEPDIR)/libdrm_util.Plo -rm -f ./$(DEPDIR)/linux_util.Plo -rm -f ./$(DEPDIR)/msg_util.Plo -rm -f ./$(DEPDIR)/multi_level_map.Plo -rm -f ./$(DEPDIR)/pnp_ids.Plo -rm -f ./$(DEPDIR)/regex_util.Plo -rm -f ./$(DEPDIR)/report_util.Plo -rm -f ./$(DEPDIR)/simple_ini_file.Plo -rm -f ./$(DEPDIR)/string_util.Plo -rm -f ./$(DEPDIR)/subprocess_util.Plo -rm -f ./$(DEPDIR)/sysfs_filter_functions.Plo -rm -f ./$(DEPDIR)/sysfs_i2c_util.Plo -rm -f ./$(DEPDIR)/sysfs_util.Plo -rm -f ./$(DEPDIR)/timestamp.Plo -rm -f ./$(DEPDIR)/traced_function_stack.Plo -rm -f ./$(DEPDIR)/udev_i2c_util.Plo -rm -f ./$(DEPDIR)/udev_usb_util.Plo -rm -f ./$(DEPDIR)/udev_util.Plo -rm -f ./$(DEPDIR)/utilrpt.Plo -rm -f ./$(DEPDIR)/x11_util.Plo -rm -f ./$(DEPDIR)/xdg_util.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-local distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/backtrace.Plo -rm -f ./$(DEPDIR)/data_structures.Plo -rm -f ./$(DEPDIR)/ddcutil_config_file.Plo -rm -f ./$(DEPDIR)/debug_util.Plo -rm -f ./$(DEPDIR)/device_id_util.Plo -rm -f ./$(DEPDIR)/drm_common.Plo -rm -f ./$(DEPDIR)/edid.Plo -rm -f ./$(DEPDIR)/error_info.Plo -rm -f ./$(DEPDIR)/failsim.Plo -rm -f ./$(DEPDIR)/file_util.Plo -rm -f ./$(DEPDIR)/file_util_base.Plo -rm -f ./$(DEPDIR)/glib_string_util.Plo -rm -f ./$(DEPDIR)/glib_util.Plo -rm -f ./$(DEPDIR)/i2c_util.Plo -rm -f ./$(DEPDIR)/libdrm_util.Plo -rm -f ./$(DEPDIR)/linux_util.Plo -rm -f ./$(DEPDIR)/msg_util.Plo -rm -f ./$(DEPDIR)/multi_level_map.Plo -rm -f ./$(DEPDIR)/pnp_ids.Plo -rm -f ./$(DEPDIR)/regex_util.Plo -rm -f ./$(DEPDIR)/report_util.Plo -rm -f ./$(DEPDIR)/simple_ini_file.Plo -rm -f ./$(DEPDIR)/string_util.Plo -rm -f ./$(DEPDIR)/subprocess_util.Plo -rm -f ./$(DEPDIR)/sysfs_filter_functions.Plo -rm -f ./$(DEPDIR)/sysfs_i2c_util.Plo -rm -f ./$(DEPDIR)/sysfs_util.Plo -rm -f ./$(DEPDIR)/timestamp.Plo -rm -f ./$(DEPDIR)/traced_function_stack.Plo -rm -f ./$(DEPDIR)/udev_i2c_util.Plo -rm -f ./$(DEPDIR)/udev_usb_util.Plo -rm -f ./$(DEPDIR)/udev_util.Plo -rm -f ./$(DEPDIR)/utilrpt.Plo -rm -f ./$(DEPDIR)/x11_util.Plo -rm -f ./$(DEPDIR)/xdg_util.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-local distclean-tags distdir dvi dvi-am html html-am \ info info-am install install-am install-data install-data-am \ install-dvi install-dvi-am install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf pdf-am ps ps-am tags \ tags-am uninstall uninstall-am .PRECIOUS: Makefile clean-local: @echo "(src/util/Makefile) clean-local" mostlyclean-local: @echo "(src/util/Makefile) mostlyclean-local" distclean-local: @echo "(src/util/Makefile) distclean-local" # if ENABLE_YAML_COND # libutil_la_SOURCES += libyaml_dbgutil.c # endif # Rename to "all-local" for development all-local-disabled: @echo "" @echo "(src/util/Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/util/data_structures.c0000644000175000001440000016120714754153540013763 /** @file data_structures.c General purpose data structures */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include // C standard library #include #include // for MIN, MAX /** \endcond */ #include "debug_util.h" #include "report_util.h" #include "string_util.h" #include "data_structures.h" // // Buffer with length management // bool trace_buffer_malloc_free = false; bool trace_buffer = false; // controls buffer tracing bool trace_buffer_resize = false; /** Allocates a **Buffer** instance * * @param size maximum number of bytes that buffer can hold * @param trace_msg optional trace message * * @return pointer to newly allocated instance */ Buffer * buffer_new(int size, const char * trace_msg) { int hacked_size = size+16; // try allocating extra space see if free failures go away - overruns? // printf("(%s) sizeof(Buffer)=%ld, size=%d\n", __func__, sizeof(Buffer), size); // sizeof(Buffer) == 16 Buffer * buffer = (Buffer *) malloc(sizeof(Buffer)); memcpy(buffer->marker, BUFFER_MARKER, 4); buffer->bytes = (Byte *) calloc(1, hacked_size); // hack buffer->buffer_size = size; buffer->len = 0; buffer->size_increment = 0; if (trace_buffer_malloc_free) printf("(%s) Allocated buffer. buffer=%p, buffer->bytes=%p, &buffer->bytes=%p, %s\n", __func__, (void*)buffer, buffer->bytes, (void*)&(buffer->bytes), trace_msg); return buffer; } /** Sets a size increment for the buffer, allowing it to be dynamically * resized if necessary. * * @param buf pointer to Buffer instance * @param size_increment if resizing is necessary, the buffer size will be * increased by this amount */ void buffer_set_size_increment(Buffer * buf, uint16_t size_increment) { buf->size_increment = size_increment; } /** Allocates a **Buffer** instance and sets an initial value * * @param bytes pointer to initial value * @param bytect length of initial value, the buffer size is * also set to this value * @param trace_msg optional trace message * * @return pointer to newly allocated instance * * @remark * Setting the buffer size to the initial value does not allow for * expansion, unless buffer_set_size_increment() is called */ Buffer * buffer_new_with_value(Byte * bytes, int bytect, const char * trace_msg) { Buffer* buf = buffer_new(bytect, trace_msg); buffer_put(buf, bytes, bytect); return buf; } /** Copies a Buffer. * * @param srcbuf instance to copy * @param trace_msg optional trace message * * @return newly allocated copy * * @remark * - The contents of the newly allocated Buffer is identical to * the original, but the maximum length and size increment are * not. Is this an issue? * - Not currently used. (3/2017) */ Buffer * buffer_dup(Buffer * srcbuf, const char * trace_msg) { return buffer_new_with_value(srcbuf->bytes, srcbuf->len, trace_msg); } /** Frees a Buffer instance. All memory associated with the Buffer is released. * * @param buffer pointer to Buffer instance, must be valid * @param trace_msg optional trace message */ void buffer_free(Buffer * buffer, const char * trace_msg) { if (trace_buffer_malloc_free) printf("(%s) Starting. buffer = %p\n", __func__, (void*) buffer); // ASSERT_WITH_BACKTRACE(buffe#ifdef TEMPr); // ASSERT_WITH_BACKTRACE(memcmp(buffer->marker, BUFFER_MARKER, 4) == 0); if (buffer->bytes) { if (trace_buffer_malloc_free) printf("(%s) Freeing buffer->bytes = %p, &buffer->bytes=%p\n", __func__, buffer->bytes, (void*)&(buffer->bytes)); free(buffer->bytes); } if (trace_buffer_malloc_free) printf("(%s) Freeing buffer = %p, %s\n", __func__, (void*)buffer, trace_msg); buffer->marker[3] = 'x'; free(buffer); if (trace_buffer_malloc_free) printf("(%s) Done\n", __func__); } /** Returns the length of the data in the Buffer. * * @param buffer pointer to Buffer instance * @return number of bytes in Buffer */ int buffer_length(Buffer * buffer) { return buffer->len; } /** Adjusts the number of bytes in a Buffer. * * @param buffer pointer to buffer instance * @param bytect new length of buffer contents, must be less that * the maximum size of the buffer */ void buffer_set_length(Buffer * buffer, int bytect) { if (trace_buffer) printf("(%s) bytect=%d, buffer_size=%d\n", __func__, bytect, buffer->buffer_size); assert (bytect <= buffer->buffer_size); buffer->len = bytect; } /** Sets the value stored in a Buffer to a range of bytes. * The buffer length is updated. * * @param buffer pointer to Buffer instance * @param bytes pointer to bytes to store in buffer * @param bytect number of bytes to store */ void buffer_put(Buffer * buffer, Byte * bytes, int bytect) { if (trace_buffer) { printf("(%s) buffer->bytes = %p, bytes=%p, bytect=%d\n", __func__, buffer->bytes, bytes, bytect); printf("(%s) cur len = %d, storing |%.*s|, bytect=%d\n", __func__, buffer->len, bytect, bytes, bytect); } assert (bytect <= buffer->buffer_size); memcpy(buffer->bytes, bytes, bytect); buffer->len = buffer->len + bytect; // printf("(%s) Returning. cur len = %d\n", __func__, buffer->len); } /** Stores a single byte at a specified offset in the buffer. * The buffer length is not updated. * * @param buf pointer to Buffer instance * @param offset offset in buffer at which to store byte * @param byte byte value to be stored * * @remark * A dangerous function. Use with care. */ void buffer_set_byte(Buffer * buf, int offset, Byte byte) { if (trace_buffer) printf("(%s) Storing 0x%02x at offset %d\n", __func__, byte, offset); assert(offset >= 0 && offset < buf->buffer_size); buf->bytes[offset] = byte; } /** Sets a range of bytes in a Buffer. * The logical length of the buffer is not updated. * * @param buf pointer to Buffer instance * @param offset offset in buffer at which to store byte * @param bytes pointer to bytes to store * @param bytect number of bytes to store */ void buffer_set_bytes(Buffer * buf, int offset, Byte * bytes, int bytect) { if (trace_buffer) printf("(%s) Storing %d bytes at offset %d (buf->bytes+offset=%p), buffer_size=%d, bytes=%p, bytes+bytect=%p\n", __func__, bytect, offset, buf->bytes+offset, buf->buffer_size, bytes, bytes+bytect); assert(offset >= 0 && (offset + bytect) <= buf->buffer_size); memcpy(buf->bytes+offset, bytes, bytect); } /** Appends a sequence of bytes to the current contents of a Buffer. * The buffer length is updated. * * @param buffer pointer to the Buffer object * @param bytes pointer to the bytes to be appended * @param bytect number of bytes to append */ void buffer_append(Buffer * buffer, Byte * bytes, int bytect) { // printf("(%s) Starting. buffer=%p\n", __func__, buffer); assert( memcmp(buffer->marker, BUFFER_MARKER, 4) == 0); if (trace_buffer) { printf("(%s) cur len = %d, appending |%.*s|, bytect=%d\n", __func__, buffer->len, bytect, bytes, bytect); printf("(%s) buffer->bytes + buffer->len = %p, bytes=%p, bytect=%d\n", __func__, buffer->bytes+buffer->len, bytes, bytect); } // buffer->len + 2 + bytect .. why the + 2? int required_size = buffer->len + 2 + bytect; if (required_size > buffer->buffer_size && buffer->size_increment > 0) { int new_size = MAX(required_size, buffer->buffer_size + buffer->size_increment); if (trace_buffer_resize) printf("(%s) Resizing. old size = %d, new size = %d\n", __func__, buffer->buffer_size, new_size); buffer_extend(buffer, new_size - buffer->buffer_size); } assert(buffer->len + 2 + bytect <= buffer->buffer_size); memcpy(buffer->bytes + buffer->len, bytes, bytect); buffer->len = buffer->len + bytect; // printf("(%s) Returning. cur len = %d\n", __func__, buffer->len); } /** Appends a string to the current string in the buffer. * * @param buffer pointer to Buffer * @param str string to append * * @remark * If the buffer is not empty, checks by assert that * the last character stored is '\0'; */ void buffer_strcat(Buffer * buffer, char * str) { assert( memcmp(buffer->marker, BUFFER_MARKER, 4) == 0); if (buffer->len == 0) { buffer_append(buffer, (Byte *) str, strlen(str)+1); } else { assert(buffer->bytes[buffer->len - 1] == '\0'); buffer_set_length(buffer, buffer->len - 1); // truncate trailing \0 buffer_append(buffer, (Byte *) str, strlen(str) + 1); } } /** Appends a single byte to the current value in the buffer. * The buffer length is updated. * * @param buffer pointer to Buffer instance * @param byte value to append * * @todo Increase buffer size if necessary and size_increment > 0 */ void buffer_add(Buffer * buffer, Byte byte) { assert( memcmp(buffer->marker, BUFFER_MARKER, 4) == 0); assert(buffer->len + 1 <= buffer->buffer_size); buffer->bytes[buffer->len++] = byte; } /** Tests whether 2 Buffer instances have the same * contents. * * @param buf1 pointer to first Buffer * @param buf2 pointer to second Buffer * @return true if contents are identical, false if not * * @remark * - If both buf1==NULL and buf2==NULL, the result is true */ bool buffer_eq(Buffer* buf1, Buffer* buf2) { bool result = false; if (!buf1 && !buf2) result = true; else if (buf1 && buf2 && buf1->len == buf2->len && memcmp(buf1->bytes, buf2->bytes, buf1->len) == 0 ) result = true; return result; } /** Increases the size of a Buffer * * @param buf pointer to Buffer instance * @param addl_size number of additional bytes */ void buffer_extend(Buffer* buf, int addl_size) { int new_size = buf->buffer_size + addl_size; buf->bytes = realloc(buf->bytes, new_size); buf->buffer_size = new_size; } /** Displays all fields of the Buffer. * This is a debugging function. * * @param buffer pointer to Buffer instance * * @remark * Output is written to stdout. */ void buffer_dump(Buffer * buffer) { printf("Buffer at %p, bytes addr=%p, len=%d, max_size=%d\n", (void*)buffer, buffer->bytes, buffer->len, buffer->buffer_size); // printf(" bytes end addr=%p\n", buffer->bytes+buffer->buffer_size); if (buffer->bytes) hex_dump(buffer->bytes, buffer->len); } /** Displays all fields of the Buffer using rpt_* functions. * This is a debugging function. * * @param buffer pointer to Buffer instance * @param depth logical indentation depth * * @remark * Output is written to stdout. */ void buffer_rpt(Buffer * buffer, int depth) { rpt_vstring(depth, "Buffer at %p, bytes addr=%p, len=%d, max_size=%d", (void*)buffer, buffer->bytes, buffer->len, buffer->buffer_size); if (buffer->bytes) rpt_hex_dump(buffer->bytes, buffer->len, depth); } // // Circular_String_Buffer // /** Allocates a new #Circular_String_Buffer * * @param size buffer size (number of entries) * @return pointer to newly allocated #Circular_String_Buffer */ Circular_String_Buffer * csb_new(int size) { Circular_String_Buffer * csb = calloc(1, sizeof(Circular_String_Buffer)); csb->lines = calloc(size, sizeof(char*)); csb->size = size; csb->ct = 0; return csb; } /** Appends a string to a #Circular_String_Buffer. * * @param csb pointer to #Circular_String_Buffer * @param line string to append * @param copy if true, a copy of the string is appended to the buffer * if false, the string itself is appended */ void csb_add(Circular_String_Buffer * csb, char * line, bool copy) { int nextpos = csb->ct % csb->size; // printf("(%s) Adding at ct %d, pos %d, line |%s|\n", __func__, csb->ct, nextpos, line); if (csb->lines[nextpos] && copy) free(csb->lines[nextpos]); csb->lines[nextpos] = (copy) ? g_strdup(line) : line; csb->ct++; } /** Frees a #Circular_String_Buffer * * @param csb pointer to #Circular_String_Buffer * @param free_strings free the strings pointed to by the #Cirular_String_Buffer */ void csb_free(Circular_String_Buffer * csb, bool free_strings) { if (free_strings) { int first = 0; if (csb->ct > csb->size) first = csb->ct % csb->size; // printf("(%s) first=%d\n", __func__, first); for (int ndx = 0; ndx < csb->ct; ndx++) { int pos = (first + ndx) % csb->size; char * s = csb->lines[pos]; // printf("(%s) line %d, |%s|\n", __func__, ndx, s); free(s); } csb->ct = 0; } free(csb->lines); free(csb); } /** All the strings in a #Circular_String_Buffer are moved to a newly * allocated GPtrArray. The count of lines in the now empty #Circular_String_Buffer * is set to 0. * * @param csb pointer to #Circular_String_Buffer to convert * @return newly allocated #GPtrArray */ GPtrArray * csb_to_g_ptr_array(Circular_String_Buffer * csb) { // printf("(%s) csb->size=%d, csb->ct=%d\n", __func__, csb->size, csb->ct); GPtrArray * pa = g_ptr_array_sized_new(csb->ct); int first = 0; if (csb->ct > csb->size) first = csb->ct % csb->size; // printf("(%s) first=%d\n", __func__, first); for (int ndx = 0; ndx < csb->ct; ndx++) { int pos = (first + ndx) % csb->size; char * s = csb->lines[pos]; // printf("(%s) line %d, |%s|\n", __func__, ndx, s); g_ptr_array_add(pa, s); } csb->ct = 0; return pa; } #ifdef OLD // // Circular Integer Buffer // typedef struct { int * values; int size; int ct; } Circular_Integer_Buffer; /** Allocates a new #Circular_Integer_Buffer * * @param size buffer size (number of entries) * @return newly allocated #Circular_Integer_Buffer */ Circular_Integer_Buffer * cib_new(int size) { Circular_Integer_Buffer * cib = calloc(1, sizeof(Circular_Integer_Buffer)); cib->values = calloc(size, sizeof(int)); cib->size = size; cib->ct = 0; return cib; } void cib_free(Circular_Integer_Buffer * cib) { free(cib->values); free(cib); } /** Appends an integer to a #Circular_Integer_Buffer. * * @param cib #Circular_Integer_Buffer * @param value value to append */ void cib_add(Circular_Integer_Buffer * cib, int value) { int nextpos = cib->ct % cib->size; // printf("(%s) Adding at ct %d, pos %d, value %d\n", __func__, cib->ct, nextpos, value); cib->values[nextpos] = value; cib->ct++; } void cib_get_latest(Circular_Integer_Buffer * cib, int ct, int latest_values[]) { assert(ct <= cib->ct); int ctr = 0; while(ctr < ct) {int_min int ndx = (ctr > 0) ? (ctr-1) % cib->size : cib->size - 1; latest_values[ctr] = cib->values[ ndx ]; } } #endif // // Identifier id to name and description lookup // /** Returns the name of an entry in a Value_Name_Title table. * * @param table pointer to table * @param val value to lookup * * @return name of value, NULL if not found */ char * vnt_name(Value_Name_Title* table, uint32_t val) { // printf("(%s) val=%d\n", __func__, val); // debug_vnt_table(table); char * result = NULL; Value_Name_Title * cur = table; for (; cur->name; cur++) { if (val == cur->value) { result = cur->name; break; } } return result; } /** Returns the title (description field) of an entry in a Value_Name_Title table. * * @param table pointer to table * @param val value to lookup * * @return title of value, NULL if not found */ char * vnt_title(Value_Name_Title* table, uint32_t val) { // printf("(%s) val=%d\n", __func__, val); // debug_vnt_table(table); char * result = NULL; Value_Name_Title * cur = table; for (; cur->name; cur++) { if (val == cur->value) { result = cur->title; break; } } return result; } /** Searches a Value_Name_Title_Table for a specified name or title, * and returns its id value. * * @param table a Value_Name_Title table * @param s string to search for * @param use_title if false, search name field\n * if true, search title field * @param ignore_case if true, search is case-insensitive * @param default_id value to return if not found * * @result value id */ int32_t vnt_find_id( Value_Name_Title_Table table, const char * s, bool use_title, // if false, search by symbolic name, if true, search by title bool ignore_case, int32_t default_id) { assert(s); int32_t result = default_id; Value_Name_Title * cur = table; for (; cur->name; cur++) { char * comparand = (use_title) ? cur->title : cur->name; if (comparand) { int comprc = (ignore_case) ? strcasecmp(s, comparand) : strcmp( s, comparand); if (comprc == 0) { result = cur->value; break; } } } return result; } /** Interprets an integer whose bits represent named flags. * * @param flags_val value to interpret * @param bitname_table pointer to Value_Name table * @param use_title if **true**, use the **title** field of the table,\n * if **false**, use the **name** field of the table * @param sepstr if non-NULL, separator string to insert between values * * @return newly allocated character string * * @remark * - It is the responsibility of the caller to free the returned string * - If a referenced **title** field is NULL, "missing" is used as the value */ char * vnt_interpret_flags( uint32_t flags_val, Value_Name_Title_Table bitname_table, bool use_title, char * sepstr) { bool debug = false; if (debug) printf("(%s) Starting. flags_val=0x%08x, bitname_table=%p, use_title=%s, sepstr=|%s|\n", __func__, flags_val, (void*)bitname_table, sbool(use_title), sepstr); GString * sbuf = g_string_sized_new(200); bool first = true; Value_Name_Title * cur_entry = bitname_table; while (cur_entry->name) { if (debug) printf("(%s) cur_entry=%p, Comparing flags_val=0x%08x vs cur_entry->value = 0x%08x\n", __func__, (void*)cur_entry, flags_val, cur_entry->value); if (!flags_val && cur_entry->value == flags_val) { // special value for no bit set char * sval = (use_title) ? cur_entry->title : cur_entry->name; if (!sval) sval = "missing"; g_string_append(sbuf, sval); break; } if (flags_val & cur_entry->value) { if (first) first = false; else { if (sepstr) { g_string_append(sbuf, sepstr); } } char * sval = (use_title) ? cur_entry->title : cur_entry->name; if (!sval) { sval = "missing"; } g_string_append(sbuf, sval); } cur_entry++; } char * result = g_strdup(sbuf->str); g_string_free(sbuf, true); if (debug) printf("(%s) Done. Returning: |%s|\n", __func__, result); return result; } /** Interprets a flags value as a printable string. The returned string is * valid until the next call of this function in the current thread. * * @param flags_val value to interpret * @param bitname_table pointer to Value_Name_Title table * @param use_title if **true**, use the **title** field of the table,\n * if **false**, use the **name** field of the table * @param sepstr if non-NULL, separator string to insert between values * * @return interpreted value */ char * vnt_interpret_flags_t( uint32_t flags_val, Value_Name_Title_Table bitname_table, bool use_title, char * sepstr) { static GPrivate x_key = G_PRIVATE_INIT(g_free); static GPrivate x_len_key = G_PRIVATE_INIT(g_free); char * buftemp = vnt_interpret_flags(flags_val, bitname_table, use_title, sepstr); char * buf = get_thread_dynamic_buffer(&x_key, &x_len_key, strlen(buftemp)+1); strcpy(buf, buftemp); free(buftemp); return buf; } /** Shows the contents of a **Value_Name_Title table. * Output is written to stdout. * * @param table pointer to table */ void vnt_debug_table(Value_Name_Title * table) { printf("Value_Name_Title table:\n"); Value_Name_Title * cur = table; for (; cur->name; cur++) { printf(" %2d %-30s %s\n", cur->value, cur->name, cur->title); } } // bva - Byte Value Array // // An opaque structure containing an array of bytes that // can grow dynamically. Note that the same byte can // appear multiple times. /** Creates a new **Byte_Value_Array** instance. * @return newly allocated **Byte_Value_Array**. */ Byte_Value_Array bva_create() { GByteArray * ga = g_byte_array_new(); return (Byte_Value_Array) ga; } /** Creates a new **Byte_Value_Array** instance, * containing the values from an existing instance * that satisfy the filter function. * * @param bva **Byte_Value_Array** instance * @param filter_func function that takes a byte value as an argument, * returning true if the value should be included * in the output **Byte_Value_Array** * @return new **Byte_Value_Array** */ Byte_Value_Array bva_filter(Byte_Value_Array bva, IFilter filter_func) { GByteArray * src = (GByteArray*) bva; GByteArray * result = g_byte_array_new(); for (guint ndx=0; ndx < src->len; ndx++) { guint8 v = src->data[ndx]; // Byte v1 = v; if (filter_func(v)) bva_append(result,v); } return (Byte_Value_Array) result; } /** Returns the number of entries in a **Byte_Value_Array**. * * @param bva **Byte_Value_Array** instance * @return number of entries */ int bva_length(Byte_Value_Array bva) { GByteArray* ga = (GByteArray*) bva; return ga->len; } /** Adds a value to a **Byte_Value_Array**. * * @param bva **Byte_Value_Array** instance * @param item value to add */ void bva_append(Byte_Value_Array bva, Byte item) { GByteArray* ga = (GByteArray*) bva; #ifdef NDEBUG g_byte_array_append(ga, &item, 1); #else GByteArray * ga2 = g_byte_array_append(ga, &item, 1); assert(ga2 == ga); #endif } /** Gets a value by its index from a **Byte_Value_Array**. * * @param bva **Byte_Value_Array** instance * @param ndx index of entry * @return value * * **ndx** must be a valid value. * The only check is by assert(). */ Byte bva_get(Byte_Value_Array bva, guint ndx) { GByteArray* ga = (GByteArray*) bva; assert(ndx < ga->len); guint8 v = ga->data[ndx]; Byte v1 = v; return v1; } /** Checks if a **Byte_Value_Array** contains a value. * * @param bva **Byte_Value_Array** instance * @param item value to check for * @return true/false */ bool bva_contains(Byte_Value_Array bva, Byte item) { GByteArray* ga = (GByteArray*) bva; guint ndx; bool result = false; // printf("(%s) item=0x%02x, ga->len=%d\n", __func__, item, ga->len); for (ndx=0; ndx < ga->len; ndx++) { guint8 v = ga->data[ndx]; // Byte v1 = v; if (v == item) { result = true; break; } } // printf("(%s) returning %d\n", __func__, result); return result; } // Comparison function used by gba_sort() static int bva_comp_func(const void * val1, const void * val2) { const guint8 * v1 = val1; const guint8 * v2 = val2; int result = 0; if (*v1 < *v2) result = -1; else if (*v1 > *v2) result = 1; // printf("(%s) *v1=%u, *v2=%u, returning: %d\n", __func__, *v1, *v2, result); return result; } /** Sorts a **Byte_Value_Array** in ascending order * * @param bva **Byte_Value_Array** instance */ void bva_sort(Byte_Value_Array bva) { // printf("(%s) Starting", __func__); GByteArray* ga = (GByteArray*) bva; qsort(ga->data, ga->len, 1, bva_comp_func); // printf("(%s) Done", __func__); } /** Compare 2 sorted #Byte_Value_Array instances for equality. * If the same value occurs multiple times in one array, it * must occur the same number of times in the other. * * @param bva1 pointer to first instance * @param bva2 pointer to second instance * \retval true arrays are identical * \retval false arrays not identical * * @remark * If bva1 or bva2 is null, it is considered to contain 0 values. */ bool bva_sorted_eq(Byte_Value_Array bva1, Byte_Value_Array bva2) { int len1 = (bva1) ? bva_length(bva1) : 0; int len2 = (bva2) ? bva_length(bva2) : 0; bool result = true; if (len1 != len2) { result = false; } else if ( (len1+len2) > 0 ) { for (int ndx = 0; ndx < bva_length(bva1); ndx++) { if (bva_get(bva1,ndx) != bva_get(bva2,ndx)) result = false; } } return result; } /** Returns the bytes from a **Byte_Value_Array**. * * @param bva **Byte_Value_Array** instance * @return pointer to bytes within * * @remark * The length of the bytes returned must be obtained from **bva_length()**. * Alternatively, consider returning a **Buffer**. * @remark * Caller should not free the returned pointer. */ Byte * bva_bytes(Byte_Value_Array bva) { GByteArray* ga = (GByteArray*) bva; // Byte * result = calloc(ga->len, sizeof(guint8)); // memcpy(result, ga->data, ga->len); Byte * result = ga->data; return result; } /** Returns a string representation of the data in a **Byte_Value_Array. * * @param bva **Byte_Value_Array** instance * @param as_hex if true, use 2 character hex representation, * if false, use 1-3 character integer representation * @param sep separator string between values, if NULL then none * @return string representation of data, caller must free */ char * bva_as_string(Byte_Value_Array bva, bool as_hex, char * sep) { assert(bva); GByteArray* ga = (GByteArray*) bva; if (!sep) sep = ""; int len = ga->len; Byte * bytes = ga->data; int sepsz = strlen(sep); int alloc_sz = len * (3+sepsz) + 1; // slightly large, but simpler to compute char * buf = calloc(1, alloc_sz); for (int ndx = 0; ndx < len; ndx++) { char * cursep = (ndx > 0) ? sep : ""; if (as_hex) snprintf(buf + strlen(buf), alloc_sz-strlen(buf), "%s%02x", cursep, bytes[ndx]); else snprintf(buf + strlen(buf), alloc_sz-strlen(buf), "%s%d", cursep, bytes[ndx]); } return buf; } /** Destroy a **Byte_Value_Array**. * * @param bva **Byte_Value_Array** instance */ void bva_free(Byte_Value_Array bva) { GByteArray* ga = (GByteArray*) bva; g_byte_array_free(ga,TRUE); } /** Debugging function to report the contents of a **Byte_Value_Array**. * * @param bva **Byte_Value_Array** instance * @param title if non-null, line to print at start of report */ void bva_report(Byte_Value_Array bva, char * title) { if (title) printf("%s\n", title); int ct = bva_length(bva); int ndx = 0; for (; ndx < ct; ndx++) { Byte hval = bva_get(bva, ndx); printf(" %02X\n", hval); } } #ifdef TESTS // Tests and sample code int egmain(int argc, char** argv) { GList* list1 = NULL; list1 = g_list_append(list1, "Hello world!"); // generates warning: // printf("The first item is '%s'\n", g_list_first(list1)->data); g_list_free(list1);bbf_to_string GSList* list = NULL; printf("The list is now %d items long\n", g_slist_length(list)); list = g_slist_append(list, "first"); list = g_slist_append(list, "second"); printf("The list is now %d items long\n", g_slist_length(list)); g_slist_free(list); return 0; } void test_value_array() { Byte_Value_Array bva = bva_create(); bva_append(bva, 0x01); bva_append(bva, 0x02); int ndx = 0; int ct = bva_length(bva); for (;ndx < ct; ndx++) { Byte val = bva_get(bva, ndx); printf("Value[%d] = 0x%02x\n", ndx, val); } bva_free(bva); } #endif // // Bit_Set_256 - A data structure containing 256 flags // const Bit_Set_256 EMPTY_BIT_SET_256 = {{0}}; /** Sets a flag in a #Bit_Set_256. * * The flag is set in the returned value. * Parm **flags** is NOT modified in place. * * @param flags existing #Bit_Set_256 value * @param flagno flag number to set (0 based) * @return updated set */ Bit_Set_256 bs256_insert( Bit_Set_256 bitset, Byte bitno) { bool debug = false; Bit_Set_256 result = bitset; int bytendx = bitno >> 3; int shiftct = bitno & 0x07; Byte flagbit = 0x01 << shiftct; if (debug) { printf("(%s) bitno=0x%02x, bytendx=%d, shiftct=%d, flagbit=0x%02x\n", __func__, bitno, bytendx, shiftct, flagbit); } result.bytes[bytendx] |= flagbit; if (debug) { char * bs1 = g_strdup(bs256_to_string_t(bitset, "","")); char * bs2 = g_strdup(bs256_to_string_t(result, "","")); printf("(%s) old bitstring=%s, value %d, returning: %s\n", __func__, bs1, bitno, bs2); free(bs1); free(bs2); } return result; } /** Clears a flag in a #Bit_Set_256. * * The flag is cleared in the returned value. * Parm **flags** is NOT modified in place. * * @param flags existing #Bit_Set_256 value * @param flagno flag number to set (0 based) * @return updated set */ Bit_Set_256 bs256_remove( Bit_Set_256 bitset, Byte bitno) { bool debug = false; Bit_Set_256 result = bitset; int bytendx = bitno >> 3; int shiftct = bitno & 0x07; Byte flagbit = 0x01 << shiftct; if (debug) { printf("(%s) bitno=0x%02x, bytendx=%d, shiftct=%d, flagbit=0x%02x\n", __func__, bitno, bytendx, shiftct, flagbit); } result.bytes[bytendx] &= ~flagbit; return result; } /** Tests if a bit is set in a #Bit_Set_256. * * @param bitset #Bit_Set_256 to check * @param bitno bit number to test (0 based) * @return true/false */ bool bs256_contains( Bit_Set_256 bitset, Byte bitno) { bool debug = false; int flagndx = bitno >> 3; int shiftct = bitno & 0x07; Byte flagbit = 0x01 << shiftct; // printf("(%s) bitno=0x%02x, flagndx=%d, shiftct=%d, flagbit=0x%02x\n", // __func__, bitno, flagndx, shiftct, flagbit); bool result = bitset.bytes[flagndx] & flagbit; if (debug) { printf("(%s) bitset:\n ",__func__); for (int ndx = 0; ndx < 32; ndx++) { printf("%02x", bitset.bytes[ndx]); } printf("\n"); printf("(%s) bit %d, returning: %d\n", __func__, bitno, result); } return result; } /** Returns the bit number of the first bit set. * @param bitset #Bit_Set_256 to check * @return number of first bit that is set (0 based), * -1 if no bits set */ int bs256_first_bit_set( Bit_Set_256 bitset) { int result = -1; for (int ndx = 0; ndx < 256; ndx++) { if (bs256_contains(bitset, ndx)) { result = ndx; break; } } return result; } bool bs256_eq( Bit_Set_256 set1, Bit_Set_256 set2) { return memcmp(&set1, &set2, 32) == 0; } Bit_Set_256 bs256_or( Bit_Set_256 set1, Bit_Set_256 set2) { Bit_Set_256 result; for (int ndx = 0; ndx < 32; ndx++) { result.bytes[ndx] = set1.bytes[ndx] | set2.bytes[ndx]; } return result; } Bit_Set_256 bs256_and( Bit_Set_256 set1, Bit_Set_256 set2) { Bit_Set_256 result; for (int ndx = 0; ndx < 32; ndx++) { result.bytes[ndx] = set1.bytes[ndx] & set2.bytes[ndx]; } return result; } Bit_Set_256 bs256_and_not( Bit_Set_256 set1, Bit_Set_256 set2) { // DBGMSG("Starting. vcplist1=%p, vcplist2=%p", vcplist1, vcplist2); Bit_Set_256 result; for (int ndx = 0; ndx < 32; ndx++) { result.bytes[ndx] = set1.bytes[ndx] & ~set2.bytes[ndx]; } // char * s = ddca_bs256_string(&result, "0x",", "); // DBGMSG("Returning: %s", s); // free(s); return result; } #define BS256_REPR_BUF_SZ (3*32+1) /** Represents a #Bit_Set_256 value as a sequence of 32 hex values. * * @param bbset value to represent * @param buf buffer in which to return value * @param bufsz buffer size, must be at least #BB256_REPR_BUF_SZ */ void bs256_repr(Bit_Set_256 bbset, char * buf, int bufsz) { assert(bufsz >= BS256_REPR_BUF_SZ); g_snprintf(buf, bufsz, "%02x %02x %02x %02x %02x %02x %02x %02x " "%02x %02x %02x %02x %02x %02x %02x %02x " "%02x %02x %02x %02x %02x %02x %02x %02x " "%02x %02x %02x %02x %02x %02x %02x %02x", bbset.bytes[ 0], bbset.bytes[ 1], bbset.bytes[ 2], bbset.bytes[ 3], bbset.bytes[ 4], bbset.bytes[ 5], bbset.bytes[ 6], bbset.bytes[ 7], bbset.bytes[ 8], bbset.bytes[ 9], bbset.bytes[10], bbset.bytes[11], bbset.bytes[12], bbset.bytes[13], bbset.bytes[14], bbset.bytes[15], bbset.bytes[16], bbset.bytes[17], bbset.bytes[18], bbset.bytes[19], bbset.bytes[20], bbset.bytes[21], bbset.bytes[22], bbset.bytes[23], bbset.bytes[24], bbset.bytes[25], bbset.bytes[26], bbset.bytes[27], bbset.bytes[28], bbset.bytes[29], bbset.bytes[30], bbset.bytes[31] ); } /** Returns the number of bits set in a #Bit_Set_256 instance. * * @param bbset value to examine * @return number of bits set */ int bs256_count( Bit_Set_256 bbset) { bool debug = false; int result = 0; int flagndx; int bitndx; for (flagndx=0; flagndx < 32; flagndx++) { for (bitndx = 0; bitndx < 8; bitndx++) { unsigned char flagbit = (0x80 >> bitndx); if (bbset.bytes[flagndx] & flagbit) result += 1; } } if (debug) { char buf[BS256_REPR_BUF_SZ]; bs256_repr(bbset, buf, sizeof(buf)); printf("(%s) Returning %d. bbset: %s\n", __func__, result, buf); } return result; } #ifdef COMPILE_ERRORS int bs256_count( Bit_Set_256 bbset) { // regard the array of 32 bytes as an array of 8 4-byte unsigned integers uint64_t list2 = (uint64_t) bbset.bytes; unsigned int ct = 0; for (int ndx = 0; ndx < 4; ndx++) { // clever algorithm for counting number of bits per Brian Kernihgan uint64_t v = list2[ndx]; for (; v; ct++) { v &= v - 1; // clear the least significant bit set } // DBGMSG("feature_list_count() returning: %d", ct); } // #ifdef OLD assert(ct == bs256_count0(bbset)); // #endif return ct; } #endif /** Returns a string representation of a #Bit_Set_256 as a list of hex numbers. * * The value returned is valid until the next call to this function in the * current thread. * * @param bitset value to represent * @param decimal_format if true, represent values as decimal numbers * if false, represent values as hex numbers * @param value_prefix prefix for each hex number, typically "0x" or "" * @param sepstr string to insert between each value, typically "", ",", or " " * @return string representation, caller should not free */ static char * bs256_to_string_general_t( Bit_Set_256 bitset, bool decimal_format, const char * value_prefix, const char * sepstr) { bool debug = false; if (debug) { printf("(%s) value_prefix=|%s|, sepstr=|%s| bitset: ", __func__, value_prefix, sepstr); for (int ndx = 0; ndx < 32; ndx++) { printf("%02x", bitset.bytes[ndx]); } printf("\n"); // rpt_hex_dump((Byte*)feature_list, 32, 2); } static GPrivate key = G_PRIVATE_INIT(g_free); static GPrivate len_key = G_PRIVATE_INIT(g_free); if (!value_prefix) value_prefix = ""; if (!sepstr) sepstr = ""; int vsize = strlen(value_prefix) + 2 + strlen(sepstr); // for hex if (decimal_format) vsize = strlen(value_prefix) + 3 + strlen(sepstr); // for decimal int bit_ct = bs256_count(bitset); int reqd_size = (bit_ct*vsize)+1; // +1 for trailing null char * buf = get_thread_dynamic_buffer(&key, &len_key, reqd_size); // char * buf = calloc(1, reqd_size); buf[0] = '\0'; // printf("(%s) feature_ct=%d, vsize=%d, buf size = %d", // __func__, feature_ct, vsize, vsize*feature_ct); for (int ndx = 0; ndx < 256; ndx++) { if ( bs256_contains(bitset, ndx) ) { if (decimal_format) sprintf(buf + strlen(buf), "%s%d%s", value_prefix, ndx, sepstr); else sprintf(buf + strlen(buf), "%s%02x%s", value_prefix, ndx, sepstr); } } if (bit_ct > 0) buf[ strlen(buf)-strlen(sepstr)] = '\0'; // printf("(%s) wolf 4\n", __func__); // DBGMSG("Returned string length: %d", strlen(buf)); // DBGMSG("Returning %p - %s", buf, buf); if (debug) printf("(%s) Returning: string of length %d: |%s|\n", __func__, (int) strlen(buf), buf); return buf; } /** Returns a string representation of a #Bit_Set_256 as a list of hex numbers. * * The value returned is valid until the next call to this function or to * #bs256_to_string_decimal() in the current thread. * * @param bitset value to represent * @param value_prefix prefix for each hex number, typically "0x" or "" * @param sepstr string to insert between each value, typically "", ",", or " " * @return string representation, caller should not free */ char * bs256_to_string_t( Bit_Set_256 bitset, const char * value_prefix, const char * sepstr) { return bs256_to_string_general_t(bitset, false, value_prefix, sepstr); } /** Returns a string representation of a #Bit_Set_256 as a list of decimal numbers. * * The value returned is valid until the next call to this function or to * #bs256_to_string() in the current thread. * * @param bitset value to represent * @param value_prefix prefix for each decimal number * @param sepstr string to insert between each value, typically "", ",", or " " * @return string representation, caller should not free */ char * bs256_to_string_decimal_t( Bit_Set_256 bitset, const char * value_prefix, const char * sepstr) { return bs256_to_string_general_t(bitset, true, value_prefix, sepstr); } int bs256_to_bytes(Bit_Set_256 flags, Byte * buffer, int buflen) { // printf("(%s) Starting\n", __func__); #ifndef NDEBUG int bit_set_ct = bs256_count(flags); assert(buflen >= bit_set_ct); #endif unsigned int bufpos = 0; unsigned int flagno = 0; // printf("(%s) bs256lags->byte=0x%s\n", __func__, hexstring(flags->byte,32)); for (flagno = 0; flagno < 256; flagno++) { Byte flg = (Byte) flagno; // printf("(%s) flagno=%d, flg=0x%02x\n", __func__, flagno, flg); if (bs256_contains(flags, flg)) { // printf("(%s) Flag is set: %d, 0x%02x\n", __func__, flagno, flg); buffer[bufpos++] = flg; } } // printf("(%s) Done. Returning: %d\n", __func__, bupos); return bufpos; } /** Converts a **Bit_Set_256** instance to a sequence of bytes whose values * correspond to the bits that are set. * The byte sequence is returned in a newly allocated **Buffer**. * * @param bs256lags instance handle * @return pointer to newly allocated **Buffer** */ Buffer * bs256_to_buffer(Bit_Set_256 flags) { int bit_set_ct = bs256_count(flags); Buffer * buf = buffer_new(bit_set_ct, __func__); for (unsigned int flagno = 0; flagno < 256; flagno++) { Byte flg = (Byte) flagno; // printf("(%s) flagno=%d, flg=0x%02x\n", __func__, flagno, flg); if (bs256_contains(flags, flg)) { buffer_add(buf, flg); } } // printf("(%s) Done. Returning: %s\n", __func__, buffer); return buf; } #define BS256_ITER_MARKER "BSIM" typedef struct { char marker[4]; Bit_Set_256 bbflags; int lastpos; } _Bit_Set_256_Iterator; /** Creates an iterator for a #Bit_Set_256 instance. * The iterator is an opaque object. */ Bit_Set_256_Iterator bs256_iter_new(Bit_Set_256 bbflags) { _Bit_Set_256_Iterator * result = malloc(sizeof(_Bit_Set_256_Iterator)); memcpy(result->marker, BS256_ITER_MARKER, 4); result->bbflags = bbflags; // TODO: save pointer to unopaque _BitByteFlags result->lastpos = -1; return result; } /** Free a #Bit_Set_256_Iterator. * * @param bs256_iter handle to iterator (may be NULL) */ void bs256_iter_free( Bit_Set_256_Iterator bs256_iter) { _Bit_Set_256_Iterator * iter = (_Bit_Set_256_Iterator *) bs256_iter; if (bs256_iter) { assert(memcmp(iter->marker, BS256_ITER_MARKER, 4) == 0); iter->marker[3] = 'x'; free(iter); } } /** Reinitializes an iterator. Sets the current position before the first * value. * * @param bs256_iter handle to iterator */ void bs256_iter_reset( Bit_Set_256_Iterator bs256_iter) { _Bit_Set_256_Iterator * iter = (_Bit_Set_256_Iterator *) bs256_iter; assert(iter && memcmp(iter->marker, BS256_ITER_MARKER, 4) == 0); iter->lastpos = -1; } /** Returns the number of the next bit that is set. * * @param bs256_iter handle to iterator * @return number of next bit that is set, -1 if no more */ int bs256_iter_next( Bit_Set_256_Iterator bs256_iter) { _Bit_Set_256_Iterator * iter = (_Bit_Set_256_Iterator *) bs256_iter; assert( iter && memcmp(iter->marker, BS256_ITER_MARKER, 4) == 0); // printf("(%s) Starting. lastpos = %d\n", __func__, iter->lastpos); int result = -1; for (int ndx = iter->lastpos + 1; ndx < 256; ndx++) { if (bs256_contains(iter->bbflags, ndx)) { result = ndx; iter->lastpos = ndx; break; } } // printf("(%s) Returning: %d\n", __func__, result); return result; } // TODO: // Extracted from feature_list.cpp in ddcui. parse_custom_feature_list() // should be rewritten to call this function. /** Parse a string containing a list of hex values. * * @param unparsed_string * @param error_msgs_loc if non-null, return null terminated string array of error messages here, * caller is responsible for freeing * @return #Bit_Set_256, will be EMPTY_BIT_SET_256 if errors * * @remark * If error_msgs_loc is non-null on entry, on return the value it points to * is non-null iff there are error messages, i.e. a 0 length array is never returned */ Bit_Set_256 bs256_from_string( char * unparsed_string, Null_Terminated_String_Array * error_msgs_loc) { assert(unparsed_string); assert(error_msgs_loc); bool debug = false; if (debug) printf("(bs256_from_string) unparsed_string = |%s|\n", unparsed_string ); Bit_Set_256 result = EMPTY_BIT_SET_256; *error_msgs_loc = NULL; GPtrArray * errors = g_ptr_array_new(); // convert all commas to blanks char * x = unparsed_string; while (*x) { if (*x == ',') *x = ' '; x++; } // gchar ** pieces = g_strsplit(features_work, " ", -1); // doesn't handle multiple blanks Null_Terminated_String_Array pieces = strsplit(unparsed_string, " "); int ntsal = ntsa_length(pieces); if (debug) printf("(bs256_from_string) ntsal=%d\n", ntsal ); if (ntsal == 0) { if (debug) printf("(bs256_from_string) Empty string\n"); } else { bool ok = true; int ndx = 0; for (; pieces[ndx] != NULL; ndx++) { // char * token = strtrim_r(pieces[ndx], trimmed_piece, 10); char * token = g_strstrip(pieces[ndx]); if (debug) printf("(parse_features_list) token= |%s|\n", token); Byte hex_value = 0; if ( any_one_byte_hex_string_to_byte_in_buf(token, &hex_value) ) { result = bs256_insert(result, hex_value); } else { if (debug) printf("(bs256_from_string) Invalid hex value: %s\n", token); char * s = g_strdup_printf("Invalid hex value: %s", token); g_ptr_array_add(errors, s); ok = false; } } assert(ndx == ntsal); ASSERT_IFF(ok, errors->len == 0); if (ok) { g_ptr_array_free(errors,true); *error_msgs_loc = NULL; } else { result = EMPTY_BIT_SET_256; *error_msgs_loc = g_ptr_array_to_ntsa(errors, false); g_ptr_array_free(errors, false); } } ntsa_free(pieces, /* free_strings */ true); if (debug) { const char * s = bs256_to_string_t(result, /*prefix*/ "x", /*sepstr*/ ","); printf("Returning bit set: %s\n", s); if (*error_msgs_loc) { printf("(bs256_from_string) Returning error messages:\n"); ntsa_show(*error_msgs_loc); } } return result; } Bit_Set_256 bs256_from_bva(Byte_Value_Array bva) { Bit_Set_256 result = EMPTY_BIT_SET_256; int ct = bva_length(bva); for (int ndx = 0; ndx < ct; ndx++) { Byte bitno = bva_get(bva, ndx); result = bs256_insert(result, bitno); } return result; } // // Bit_Set_32 - A set of 32 flags // const Bit_Set_32 EMPTY_BIT_SET_32 = 0; const int BIT_SET_32_MAX = 32; #define BS32_REPR_BUF_SZ 10 /** Represents a #Bit_Set_32 value as a sequence of 4 hex values. * * @param buf buffer in which to return value * @param bufsz buffer size, must be at least #BB256_REPR_BUF_SZ * @param bbset value to represent */ void bs32_repr(Bit_Set_32 bbset, char * buf, int bufsz) { assert(bufsz >= BS32_REPR_BUF_SZ); g_snprintf(buf, bufsz, "0x%08x", bbset); } /** Returns the number of bits set in a #Bit_Set_32 instance. * * @param bbset value to examine * @return number of bits set */ int bs32_count( Bit_Set_32 bbset) { bool debug = false; int result = 0; for (int bitndx = 0; bitndx < 32; bitndx++) { unsigned char flagbit = (0x80 >> bitndx); if (bbset & flagbit) result += 1; } if (debug) { char buf[BS32_REPR_BUF_SZ]; bs32_repr(bbset, buf, sizeof(buf)); printf("(%s) Returning %d. bbset: %s\n", __func__, result, buf); } return result; } bool bs32_contains(Bit_Set_32 flags, uint8_t val) { assert(val < BIT_SET_32_MAX); bool result = flags & (1 << val); return result; } Bit_Set_32 bs32_insert(Bit_Set_32 flags, uint8_t val) { Bit_Set_32 result = flags | (1 << val); return result; } /** Returns a string representation of a #Bit_Set_32 as a list of hex numbers. * * The value returned is valid until the next call to this function in the * current thread. * * @param bitset value to represent * @param decimal_format if true, represent values as decimal numbers * if false, represent values as hex numbers * @param value_prefix prefix for each hex number, typically "0x" or "" * @param sepstr string to insert between each value, typically "", ",", or " " * @return string representation, caller should not free */ static char * bs32_to_string_general( Bit_Set_32 bitset, bool decimal_format, const char * value_prefix, const char * sepstr) { bool debug = false; if (debug) { printf("(%s) value_prefix=|%s|, sepstr=|%s| bitset: 0x%08x", __func__, value_prefix, sepstr, bitset); // rpt_hex_dump((Byte*)feature_list, 32, 2); } static GPrivate key = G_PRIVATE_INIT(g_free); static GPrivate len_key = G_PRIVATE_INIT(g_free); if (!value_prefix) value_prefix = ""; if (!sepstr) sepstr = ""; int vsize = strlen(value_prefix) + 2 + strlen(sepstr); // for hex if (decimal_format) vsize = strlen(value_prefix) + 3 + strlen(sepstr); // for decimal int bit_ct = bs32_count(bitset); int reqd_size = (bit_ct*vsize)+1; // +1 for trailing null char * buf = get_thread_dynamic_buffer(&key, &len_key, reqd_size); // char * buf = calloc(1, reqd_size); buf[0] = '\0'; // printf("(%s) feature_ct=%d, vsize=%d, buf size = %d", // __func__, feature_ct, vsize, vsize*feature_ct); for (int ndx = 0; ndx < 32; ndx++) { if ( bs32_contains(bitset, ndx) ) { if (decimal_format) sprintf(buf + strlen(buf), "%s%d%s", value_prefix, ndx, sepstr); else sprintf(buf + strlen(buf), "%s%02x%s", value_prefix, ndx, sepstr); } } if (bit_ct > 0) buf[ strlen(buf)-strlen(sepstr)] = '\0'; // printf("(%s) wolf 4\n", __func__); // DBGMSG("Returned string length: %d", strlen(buf)); // DBGMSG("Returning %p - %s", buf, buf); if (debug) printf("(%s) Returning: len=%d, %s\n", __func__, (int) strlen(buf), buf); return buf; } char* bs32_to_bitstring(Bit_Set_32 val, char * buf, int bufsz) { assert(bufsz >= BIT_SET_32_MAX+1); // char result[BIT_SET_32_MAX+1]; for (int ndx = 0; ndx < BIT_SET_32_MAX; ndx++) { buf[(BIT_SET_32_MAX-1)-ndx] = (val & 0x01) ? '1' : '0'; val = val >> 1; } buf[BIT_SET_32_MAX] = '\0'; return buf; } /** Returns a string representation of a #Bit_Set_32 as a list of hex numbers. * * The value returned is valid until the next call to this function or to * #bs32_to_string_decimal() in the current thread. * * @param bitset value to represent * @param value_prefix prefix for each hex number, typically "0x" or "" * @param sepstr string to insert between each value, typically "", ",", or " " * @return string representation, caller should not free */ char * bs32_to_string( Bit_Set_32 bitset, const char * value_prefix, const char * sepstr) { return bs32_to_string_general(bitset, false, value_prefix, sepstr); } /** Returns a string representation of a #Bit_Set_32 as a list of decimal numbers. * * The value returned is valid until the next call to this function or to * #bs32_to_string() in the current thread. * * @param bitset value to represent * @param value_prefix prefix for each decimal number * @param sepstr string to insert between each value, typically "", ",", or " " * @return string representation, caller should not free */ char * bs32_to_string_decimal( Bit_Set_32 bitset, const char * value_prefix, const char * sepstr) { return bs32_to_string_general(bitset, true, value_prefix, sepstr); } // // Cross data structure functions bba <-> bs256 // /** Tests if the bit number of every byte in a #Byte_Value_Array is set * in a #Bit_Set_256, and conversely that for every bit set in the * #Bit_Set_256 there is a corresponding byte in the #Byte_Value_Array. * * Note it is possible that the same byte appears more than once in the * #Byte_Value_Array. * * @param bva #Byte_Value_Array to test * @param bs256 #Bit_Set_256 to test * @return true/false */ bool bva_bs256_same_values( Byte_Value_Array bva , Bit_Set_256 bbflags) { bool result = true; int item; for (item = 0; item < 256; item++) { // printf("item=%d\n", item); bool r1 = bva_contains(bva, item); bool r2 = bs256_contains(bbflags, item); if (r1 != r2) { result = false; break; } } return result; } /** Convert a #Byte_Value_Array to a #Bit_Set_256 * * @param bva Byte_Value_Array * @return Bit_Set_256 */ Bit_Set_256 bva_to_bs256(Byte_Value_Array bva) { Bit_Set_256 bitset = EMPTY_BIT_SET_256; for (int ndx = 0; ndx < bva_length(bva); ndx++) { Byte b = bva_get(bva, ndx); bitset = bs256_insert(bitset, b); } return bitset; } /** Function matching signature #Byte_Appender that adds a byte * to a #Byte_Value_Array. * * @param data_struct pointer to #Byte_Value_Array to modify * @param val byte to append */ void bva_appender(void * data_struct, Byte val) { Byte_Value_Array bva = (Byte_Value_Array) data_struct; bva_append(bva, val); } /** Function matching signature #Byte_Appender that sets a bit * in a #Bit_Set_256. * * @param data_struct pointer to #Bit_Set_256 to modify * @param val number of bit to set */ void bs256_appender(void * data_struct, Byte val) { assert(data_struct); Bit_Set_256 * bitset = (Bit_Set_256*) data_struct; *bitset = bs256_insert(*bitset, val); } /** Stores a list of bytehex values in either a **Byte_Value_Array**, or a **Bit_Set_256**. * * @param start starting address of hex values * @param len length of hex values * @param data_struct opaque handle to either a **Byte_Value_Array** or a **Bit_Set_256** * @param appender function to add a value to **data_struct** * * @return false if any input data cannot be parsed, true otherwise */ bool store_bytehex_list(char * start, int len, void * data_struct, Byte_Appender appender){ bool ok = true; char * buf = malloc(len+1); memcpy(buf, start, len); buf[len] = '\0'; char * curpos = buf; char * nexttok; Byte byteVal = 0x00; // initialization logically unnecessary, but makes compiler happy while ( (nexttok = strtok(curpos, " ")) != NULL) { if (curpos) curpos = NULL; // for all calls after first int ln = strlen(nexttok); bool hexok = false; if (ln == 2) { // normal case // byteVal = hhc_to_byte(nexttok); hexok = hhc_to_byte_in_buf(nexttok, &byteVal); } else if (ln == 1) { // on old ultrasharp connected to blackrock (pre v2), values in capabilities // string are single digits. Not clear whether to regard them as decimal or hex, // since all values are < 9. But in that case decimal and single digit hex // give the same value. char buf[2]; buf[0] = '0'; buf[1] = *nexttok; // byteVal = hhc_to_byte(buf); hexok = hhc_to_byte_in_buf(buf, &byteVal); } if (!hexok) { // printf("(%s) Invalid hex value in list: %s\n", __func__, nexttok); ok = false; } // printf("(%s) byteVal=0x%02x \n", __func__, byteVal ); if (hexok) appender(data_struct, byteVal); } free(buf); // printf("(%s) Returning %s\n", __func__, sbool(ok)); return ok; } /** Parses a list of bytehex values and stores the result in a **Byte_Value_Array**. * * @param bva handle of **Byte_Value_Array** instance * @param start starting address of hex values * @param len length of hex values * * @return false if any input data cannot be parsed, true otherwise */ bool bva_store_bytehex_list(Byte_Value_Array bva, char * start, int len) { return store_bytehex_list(start, len, bva, bva_appender); } /** Parses a list of bytehex values and stores the result in a **Bit_Set_256**. * * @param pbitset where to return result **Bit_Set_256** instance * @param start starting address of hex values * @param len length of hex values * * @return false if any input data cannot be parsed, true otherwise */ bool bs256_store_bytehex_list(Bit_Set_256 * pbitset, char * start, int len) { return store_bytehex_list(start, len, pbitset, bs256_appender); } // // Generic code to register and deregister callback functions. // /** Adds function to a set of registered callbacks * * @param registered_callback_loc address of ptr to GPtrArray of registered callbacks * @param function to add * * If **registered_callcack_loc** is null on entry, a new GPtrArray is allocated and * its address is returned in **registered_callback_loc**. * * @remark * It is not an error if the function is already registered. */ void generic_register_callback(GPtrArray** registered_callbacks_loc, void * func) { bool debug = false; DBGF(debug, "Starting. registered_callbacks=%p, func=%p", *registered_callbacks_loc, func); if (!*registered_callbacks_loc) { *registered_callbacks_loc = g_ptr_array_new(); } bool new_registration = true; for (int ndx = 0; ndx < (*registered_callbacks_loc)->len; ndx++) { if (func == g_ptr_array_index(*registered_callbacks_loc, ndx)) { new_registration = false; break; } } if (new_registration) { g_ptr_array_add(*registered_callbacks_loc, func); } // DBGF(debug, "Done. Returning %s", SBOOL(new_registration)); // return new_registration; DBGF(debug, "Done. new_registration = %s", SBOOL(new_registration)); } /** Unregisters a callback function * * @param func function to remove * @retval true function deregistered * @retval false function not found * */ bool generic_unregister_callback(GPtrArray* registered_callbacks, void *func) { bool debug = false; DBGF(debug, "Starting. registered_callbacks=%p, func=%p", registered_callbacks, func); bool found = false; if (registered_callbacks) { for (int ndx = 0; ndx < registered_callbacks->len; ndx++) { if ( func == g_ptr_array_index(registered_callbacks, ndx)) { g_ptr_array_remove_index(registered_callbacks,ndx); found = true; } } } DBGF(debug, "Done. Returning: %s", SBOOL(found)); return found; } ddcutil-2.2.0/src/util/ddcutil_config_file.c0000644000175000001440000002727114634171455014527 /** \file ddcutil_config_file.c * Processes an INI file used for ddcutil options * * This is not a generic utility file, but is included in * the util directory to simplify its copying unmodified into * the ddcui source tree. */ // Copyright (C) 2021-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include "debug_util.h" #include "error_info.h" #include "report_util.h" #include "simple_ini_file.h" #include "string_util.h" #include "xdg_util.h" #include "ddcutil_config_file.h" /** Tokenize a string as per the command line * * @param string to tokenize * @param tokens_loc where to return the address of a null-terminated list of tokens * @return number of tokens * * @remark * The caller is responsible for freeing the list of tokens */ int tokenize_options_line(const char * string, char ***tokens_loc) { bool debug = false; DBGF(debug,"string -> |%s|", string); wordexp_t p; int flags = WRDE_NOCMD; if (debug) flags |= WRDE_SHOWERR; int rc = wordexp(string, &p, flags); DBGF(debug, "wordexp returned %d", rc); *tokens_loc = p.we_wordv; if (debug) { DBGF(debug,"Tokens:"); ntsa_show(*tokens_loc); DBGF(debug, "Returning: %zd", p.we_wordc); } return p.we_wordc; } /** Processes a ddcutil configuration file, returning an options string obtained by * merging the global and application-specific sections of the configuration file. * * @param ddcutil_application "ddcutil", "libddcutil", "ddcui" * @param config_filename_loc where to return fully qualified name of configuration file * @param untokenized_option_string_loc * where to return untokenized string of options obtained from * the configuration file * @param errmsgs if non-NULL, collects error messages as text strings * @retval 0 success * @retval -ENOENT config file not found * @retval -EBADMSG config file syntax error * @retval < 0 other error * * An untokenized option string is returned iff rc == 0. * * @todo * Settle on either errmsgs or errinfo_accumulator */ int read_ddcutil_config_file( const char * ddcutil_application, char ** config_fn_loc, char ** untokenized_option_string_loc, GPtrArray * errmsgs) { bool debug = false; DBGF(debug, "Starting. ddcutil_application=%s, errmsgs=%p", ddcutil_application, (void*)errmsgs); int result = 0; *untokenized_option_string_loc = NULL; *config_fn_loc = NULL; // char * config_fn = find_xdg_config_file("ddcutil", "ddcutilrc"); char * config_fn = (streq(ddcutil_application, "ddcui")) ? find_xdg_config_file("ddcutil", "ddcuirc") : find_xdg_config_file("ddcutil", "ddcutilrc"); if (!config_fn) { DBGF(debug, "Configuration file not found"); result = -ENOENT; goto bye; } DBGF(debug, "Found configuration file: %s", config_fn); *config_fn_loc = config_fn; Parsed_Ini_File * ini_file = NULL; int load_rc = ini_file_load(config_fn, errmsgs, &ini_file); ASSERT_IFF(load_rc==0, ini_file); DBGF(debug, "ini_file_load() returned %d", load_rc); if (debug) { if (errmsgs && errmsgs->len > 0) { fprintf(stderr, "(read_ddcutil_config_file) Error(s) processing configuration file: %s\n", config_fn); for (guint ndx = 0; ndx < errmsgs->len; ndx++) { fprintf(stderr, " %s\n", (char*) g_ptr_array_index(errmsgs, ndx)); } } } if (load_rc == 0) { if (debug) { ini_file_dump(ini_file); } char * global_options = ini_file_get_value(ini_file, "global", "options"); char * ddcutil_options = ini_file_get_value(ini_file, ddcutil_application, "options"); char * s = g_strdup_printf("%s %s", (global_options) ? global_options : "", (ddcutil_options) ? ddcutil_options : ""); char * combined_options = strtrim(s); free(s); DBGF(debug, "combined_options= |%s|", combined_options); *untokenized_option_string_loc = combined_options; ini_file_free(ini_file); } else result = load_rc; bye: ASSERT_IFF(result==0, *untokenized_option_string_loc); // check for null to avoid -Wstringop-overflow DBGF(debug, "Done. untokenized options: |%s|, *config_fn_loc=%s, returning: %d", (*untokenized_option_string_loc) ? *untokenized_option_string_loc : "(null)", (*config_fn_loc) ? *config_fn_loc : "(null)", result); return result; } /** Merges the tokenized command string passed to the program with tokens * obtained from the configuration file. * * @param old_argc original argument count * @param old_argv original argument list * @param config_token_ct number of tokens to insert * @param config_tokens list of tokens * @param merged_argv_loc where to return address of merged argument list * @return length of merged argument list * * @remark * old_argc/old_argv are argc/argv as passed on the command line */ static int merge_command_tokens( int old_argc, char ** old_argv, int config_token_ct, char ** config_tokens, char *** merged_argv_loc) { bool debug = false; DBGF(debug, "Starting. old_argc=%d, old_argv=%p, config_token_ct=%d, config_tokens=%p, merged_argv_loc=%p", old_argc, old_argv, config_token_ct, config_tokens, merged_argv_loc); assert(old_argc == ntsa_length(old_argv)); assert(config_token_ct == ntsa_length(config_tokens)); *merged_argv_loc = NULL; int merged_argc = 0; if (config_token_ct > 0) { int new_ct = config_token_ct + old_argc + 1; DBGF(debug, "config_token_ct = %d, argc=%d, new_ct=%d", config_token_ct, old_argc, new_ct); char ** combined = calloc(new_ct, sizeof(char *)); DBGF(debug, "Allocated combined=%p", combined); combined[0] = g_strdup(old_argv[0]); // command DBGF(debug, "Allocated combined[0] = %p -> |%s|", combined[0], combined[0] ); DBGF(debug, "Copying config_token_ct=%d config file tokens", config_token_ct); int new_ndx = 1; for (int prefix_ndx = 0; prefix_ndx < config_token_ct; prefix_ndx++, new_ndx++) { combined[new_ndx] = g_strdup(config_tokens[prefix_ndx]); DBGF(debug, "Allocated combined[%d]=%p -> |%s|", new_ndx, combined[new_ndx], combined[new_ndx]); } DBGF(debug, "Copying %d arguments from old_argv", old_argc-1); for (int old_ndx = 1; old_ndx < old_argc; old_ndx++, new_ndx++) { combined[new_ndx] = g_strdup(old_argv[old_ndx]); DBGF(debug, "Allocated combined[%d] = %p -> |%s|", new_ndx, combined[new_ndx], combined[new_ndx]); } combined[new_ndx] = NULL; DBGF(debug, "Final new_ndx = %d", __func__, new_ndx); *merged_argv_loc = combined; merged_argc = new_ct - 1; assert(merged_argc == ntsa_length(combined)); } else { *merged_argv_loc = ntsa_copy(old_argv, true); merged_argc = old_argc; } if (debug) { printf("(%s) Returning %d, *merged_argv_loc=%p\n", __func__, merged_argc, (void*)*merged_argv_loc); printf("(%s) *merged_arv_loc tokens:\n", __func__); rpt_ntsa(*merged_argv_loc, 3); } assert(merged_argc == ntsa_length(*merged_argv_loc)); return merged_argc; } /** Reads and tokenizes the appropriate options entries in the config file, * then combines the tokenized options from the ddcutil configuration file * with the command line arguments, returning a new argument list * * @param application_name for selecting config file segment * @param old_argc argc as passed on the command line * @param old_argv argv as passed on the command line * @param new_argc_loc where to return length of updated argv, * contains old_argc if error * @param new_argv_loc where to return the address of the updated argv * as a Null_Terminated_String_Array, contains old_argv if error * @param untokenized_config_options_loc * where to return untokenized option string obtained from ini file * @param configure_fn_loc where to return name of configuration file, * NULL if not found * @param errmsgs if non-NULL, collects error messages as text strings * @retval 0 success. * @retval -EBADMSG config file syntax error * @retval < 0 error reading or parsing the configuration file. * n. it is not an error if the configuration file does not exist. */ int apply_config_file( const char * application_name, // "ddcutil", "ddcui", "libddcutil" int old_argc, char ** old_argv, int * new_argc_loc, char *** new_argv_loc, char** untokenized_config_options_loc, char** configure_fn_loc, GPtrArray * errmsgs) { bool debug = false; DBGF(debug, "Starting. application_name=%s, errmsgs=%p", application_name, (void*)errmsgs); assert(old_argc == ntsa_length(old_argv)); if (debug) { for (int ndx = 0; ndx < old_argc; ndx++) { DBGF(true, "old_argv[%d] = |%s|", ndx, old_argv[ndx]); } } *untokenized_config_options_loc = NULL; *configure_fn_loc = NULL; *new_argv_loc = NULL; *new_argc_loc = 0; int result = 0; int read_config_rc = read_ddcutil_config_file( application_name, configure_fn_loc, untokenized_config_options_loc, errmsgs); ASSERT_IFF(read_config_rc==0, *untokenized_config_options_loc); DBGF(debug, "read_ddcutil_config_file() returned %d, configure_fn: %s", read_config_rc, *configure_fn_loc); if (read_config_rc == -ENOENT) { *new_argv_loc = ntsa_copy(old_argv, true); *new_argc_loc = old_argc; result = 0; } else if (read_config_rc < 0) { *new_argv_loc = ntsa_copy(old_argv, true); *new_argc_loc = old_argc; result = read_config_rc; } else { char ** cmd_prefix_tokens = NULL; int prefix_token_ct = tokenize_options_line(*untokenized_config_options_loc, &cmd_prefix_tokens); DBGF(debug, "prefix_token_ct = %d, cmd_prefix_tokens: ", prefix_token_ct); if (debug) ntsa_show(cmd_prefix_tokens); *new_argc_loc = merge_command_tokens( old_argc, old_argv, prefix_token_ct, cmd_prefix_tokens, new_argv_loc); assert(*new_argc_loc == ntsa_length(*new_argv_loc)); DBGF(debug, "calling ntsa_free() for cmd_prefix_tokens=%p ...", cmd_prefix_tokens); ntsa_free(cmd_prefix_tokens, true); // ntsa_free(old_argv, false); // can't free system's argv } if (debug) { DBGF(debug, "Done. *new_argc_loc=%d, *new_argv_loc=%p, returning %d", *new_argc_loc, *new_argv_loc, result); printf("(%s) *new_argv_loc tokens:\n", __func__); rpt_ntsa(*new_argv_loc, 3); printf("(%s) *untokenized_config_options_loc=%p->|%s|\n", __func__, *untokenized_config_options_loc, *untokenized_config_options_loc); } return result; } ddcutil-2.2.0/src/util/debug_util.c0000644000175000001440000000521414754153540012665 /** @file debug_util.c * * Functions for debugging */ // Copyright (C) 2016-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #ifdef HAVE_EXECINFO_H #include #endif #include #include #include #include #include #include #include #ifdef UNUSED #ifdef TARGET_BSD #include #else #include #include #include #endif #endif /** \endcond */ #include "backtrace.h" #include "common_printf_formats.h" #include "common_inlines.h" #include "report_util.h" #include "string_util.h" #include "debug_util.h" void show_backtrace(int stack_adjust) { int depth = 0; GPtrArray * callstack = get_backtrace(stack_adjust+2); // +2 for get_backtrace(), backtrace() if (!callstack) { perror("backtrace() unavailable"); } else { rpt_label(depth, "Current call stack (using backtrace()):"); for (int ndx = 0; ndx < callstack->len; ndx++) { rpt_vstring(depth, " %s", (char *) g_ptr_array_index(callstack, ndx)); } g_ptr_array_set_free_func(callstack, g_free); g_ptr_array_free(callstack, true); } } static int min_funcname_size = 30; void set_simple_dbgmsg_min_funcname_size(int new_size) { min_funcname_size = new_size; } // n. uses no report_util functions bool simple_dbgmsg( bool debug_flag, const char * funcname, const int lineno, const char * filename, const char * format, ...) { bool debug_func = false; if (debug_func) printf(PRItid"(simple_dbgmsg) Starting. debug_flag=%s, funcname=%s filename=%s, lineno=%d\n", TID(), sbool(debug_flag), funcname, filename, lineno); #ifdef UNUSED char thread_prefix[15] = ""; int tid = pthread_getthreadid_np(); pid_t pid = syscall(SYS_getpid); snprintf(thread_prefix, 15, "[%7jd]", (intmax_t) pid); // is this proper format for pid_t #endif bool msg_emitted = false; if ( debug_flag ) { va_list(args); va_start(args, format); char * buffer = g_strdup_vprintf(format, args); va_end(args); char * buf2 = g_strdup_printf("(%-*s) %s", min_funcname_size, funcname, buffer); // f0puts(buf2, stdout); // f0putc('\n', stdout); rpt_vstring(0, "%s", buf2); fflush(stdout); free(buffer); free(buf2); msg_emitted = true; } if (debug_func) printf(PRItid"(simple_dbgmsg) Done. Returning: %s\n", TID(), SBOOL(msg_emitted)); return msg_emitted; } ddcutil-2.2.0/src/util/backtrace.c0000644000175000001440000001304614754153540012463 /** @file backtrace.c */ // Copyright (C) 2016-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #ifdef HAVE_EXECINFO_H #include #endif #include #include #include #include #include #include #include #include #ifdef UNUSED #ifdef TARGET_BSD #include #else #include #include #include #endif #endif /** \endcond */ #include "string_util.h" #include "backtrace.h" // HACK #ifdef TARGET_BSD #undef HAVE_EXECINFO_H #endif #ifdef HAVE_EXECINFO_H /* Extracts the function name and offset from a backtrace line * * \param bt_line line returned by backtrace() * \param name_only if true, return only the name * \return string of form "name+offset" or just "name". * It is the responsibility of the caller to free this string. */ static char * extract_function(char * bt_line, bool name_only) { bool debug = false; if (debug) printf("\n(%s) bt_line = |%s|\n", __func__, bt_line); char * result = NULL; char * start = strchr(bt_line, '('); if (!start) { result = g_strdup("???"); } else { start++; // character after paren char * end = strchr(start, ')'); if (!end) end = bt_line + strlen(bt_line); int len = end - start; if (debug) { printf("(%s) start=%p, end=%p, len=%d\n", __func__, start, end, len); printf("(%s) extract is |%.*s|\n", __func__, len, start); } result = malloc(len+1); memcpy(result, start, len); result[len] = '\0'; } if (name_only) { char *p = strchr(result, '+'); if (p) { *p = '\0'; char * res = g_strdup(result); free(result); result = res; } } if (debug) printf("(%s) Returning %p -> |%s|\n", __func__, result, result); return result; } #endif #ifdef OLD /** Show the call stack. * * @param stack_adjust number of initial stack frames to ignore, to hide this * function and possibly some number of immediate callers * * @remark * Note that the call stack is approximate. The underlying system function, backtrace() * relies on external symbols, so static functions will not be properly shown. */ void show_backtrace(int stack_adjust) { bool debug = false; if (debug) printf("(%s) Starting. stack_adjust = %d\n", __func__, stack_adjust); int j, nptrs; const int MAX_ADDRS = 100; void *buffer[MAX_ADDRS]; char **strings; nptrs = backtrace(buffer, MAX_ADDRS); if (debug) printf("(%s) backtrace() returned %d addresses\n", __func__, nptrs); strings = backtrace_symbols(buffer, nptrs); if (strings == NULL) { perror("backtrace_symbols unavailable"); } else { printf("Current call stack\n"); for (j = 0; j < nptrs; j++) { if (j < stack_adjust) { if (debug) printf("(%s) Suppressing %s\n", __func__, strings[j]); } else { // printf(" %s\n", strings[j]); char * s = extract_function(strings[j], true); printf(" %s\n", s); bool final = (streq(s, "main")) ? true : false; free(s); if (final) break; } } free(strings); } } #endif /** Returns an array of function names for the backtrace stack. * * @param stack_adjust adjust the start of the reported functions * @return array of strings of names of functions, caller must deep free */ GPtrArray * get_backtrace(int stack_adjust) { #ifdef HAVE_EXECINFO_H bool debug = false; if (debug) printf("(%s) Starting. stack_adjust = %d\n", __func__, stack_adjust); GPtrArray * result = NULL; int j, nptrs; const int MAX_ADDRS = 100; void *buffer[MAX_ADDRS]; char **strings; nptrs = backtrace(buffer, MAX_ADDRS); if (debug) printf("(%s) backtrace() returned %d addresses\n", __func__, nptrs); strings = backtrace_symbols(buffer, nptrs); if (strings == NULL) { if (debug) perror("backtrace_symbols unavailable"); } else { result = g_ptr_array_sized_new(nptrs-stack_adjust); if (debug) printf("Current call stack\n"); for (j = 0; j < nptrs; j++) { if (j < stack_adjust) { if (debug) printf("(%s) Suppressing %s\n", __func__, strings[j]); } else { // printf(" %s\n", strings[j]); char * s = extract_function(strings[j], true); // caller must free s if (debug) printf(" %s\n", s); g_ptr_array_add(result, s); bool final = (streq(s, "main")) ? true : false; if (final) break; } } free(strings); } return result; #else return NULL; #endif } #ifdef FUTURE void gptrarray_to_syslog(int priority, GPtrArray* lines) { } #endif void backtrace_to_syslog(int syslog_priority, int stack_adjust) { GPtrArray * callstack = get_backtrace(stack_adjust+2); // +2 for get_backtrace(), backtrace() if (!callstack) { syslog(LOG_PERROR|LOG_ERR, "backtrace unavailable"); } else { syslog(syslog_priority, "Current call stack:"); for (int ndx = 0; ndx < callstack->len; ndx++) { syslog(syslog_priority, " %s", (char *) g_ptr_array_index(callstack, ndx)); } g_ptr_array_set_free_func(callstack, g_free); g_ptr_array_free(callstack, true); } } ddcutil-2.2.0/src/util/edid.c0000644000175000001440000005442714754153540011461 /** @file edid.c * * Functions to interpret the EDID data structure, irrespective of how * the bytes of the EDID are obtained. * * This should be the only source module that understands the internal * structure of the EDID. * * While the code here is generic to all EDIDs, only fields of use * to **ddcutil** are interpreted. */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include // printf() format macros for stdint.h #include #include /** \endcond */ #include "debug_util.h" #include "pnp_ids.h" #include "report_util.h" #include "string_util.h" #include "debug_util.h" #include "edid.h" // Direct writes to stdout/stderr: NO /** Calculates checksum for a 128 byte EDID * * @param edid pointer to 128 byte EDID block * @return checksum byte * * Note that the checksum byte (offset 127) is itself * included in the checksum calculation. */ Byte edid_checksum(const Byte * edid) { Byte checksum = 0; for (int ndx = 0; ndx < 128; ndx++) { checksum += edid[ndx]; } return checksum; } bool is_valid_edid_checksum(const Byte * edidbytes) { return (edid_checksum(edidbytes) == 0); } bool is_valid_edid_header(const Byte * edidbytes) { bool debug = false; bool result = true; const Byte edid_header_tag[] = {0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}; if (memcmp(edidbytes, edid_header_tag, 8) != 0) { if (debug) { char * hs = hexstring(edidbytes,8); printf("(%s) Invalid initial EDID bytes: %s\n", __func__, hs); free(hs); } result = false; } return result; } bool is_valid_raw_edid(const Byte * edid, int len) { return (len >= 128) && is_valid_edid_header(edid) && is_valid_edid_checksum(edid); } bool is_valid_raw_cea861_extension_block(const Byte * edid, int len) { return (len >= 128) && edid[0] == 0x02 && is_valid_edid_checksum(edid); } /** Unpacks the 2 byte manufacturer id field from the EDID into a 3 character * string. * * @param mfg_id_bytes address of first byte * @param result address of buffer in which to return result * @param bufsize buffer size; must be >= 4 * * @remark * Since the unpacked value is 4 bytes in length (3 characters plus a trailing '\0') * it could easily be returned on the stack. Consider. */ void parse_mfg_id_in_buffer(const Byte * mfg_id_bytes, char * result, int bufsize) { assert(bufsize >= 4); result[0] = (mfg_id_bytes[0] >> 2) & 0x1f; result[1] = ((mfg_id_bytes[0] & 0x03) << 3) | ((mfg_id_bytes[1] >> 5) & 0x07); result[2] = mfg_id_bytes[1] & 0x1f; // printf("result[0] = 0x%02x\n", result[0]); // printf("result[1] = 0x%02x\n", result[1]); // printf("result[2] = 0x%02x\n", result[2]); result[0] += 64; result[1] += 64; result[2] += 64; result[3] = 0; // terminating null } /** Extracts the 3 character manufacturer id from an EDID byte array. * The id is returned with a trailing null in a buffer provided by the caller. * * @param edidbytes pointer to start of EDID * @param result buffer in which to return manufacturer ID * @param bufsize buffer size (must be >= 4) */ void get_edid_mfg_id_in_buffer(const Byte* edidbytes, char * result, int bufsize) { parse_mfg_id_in_buffer(edidbytes+8, result, bufsize); } #define EDID_DESCRIPTORS_BLOCKS_START 54 #define EDID_DESCRIPTOR_BLOCK_SIZE 18 #define EDID_DESCRIPTOR_DATA_SIZE 13 #define EDID_DESCRIPTOR_BLOCK_CT 4 /** Extracts the non-timing descriptors from an EDID, i.e. * ASCII model name, serial number, and other descriptor. * The extracted values are returned as null-terminated strings. * * Note that the maximum length of these strings is 13 bytes. * * @param edidbytes pointer to 128 byte EDID * @param namebuf pointer to buffer where model name will be returned. * @param namebuf_len size of namebuf, must be >= 14 * @param snbuf pointer to buffer where serial number will be returned * @param snbuf_len size of snbuf, must be >= 14 * @param otherbuf pointer to buffer where addl descriptor will be returned * @param otherbuf_len size of otherbuf, must be >= 14 * * Buffers will be set to "Unspecified" for descriptors that are not found. * * @remark * - Use Buffers as parms instead of pointers and lengths? * - Buffer for edidbytes, and just return pointers to newly allocated memory for found strings */ static void get_edid_descriptor_strings( const Byte* edidbytes, char* namebuf, int namebuf_len, char* snbuf, int snbuf_len, char* otherbuf, int otherbuf_len) { bool debug = false; assert(namebuf_len >= 14 && snbuf_len >= 14 && otherbuf_len >= 14); strcpy(namebuf, ""); strcpy(snbuf, ""); strcpy(otherbuf, ""); int fields_found = 0; // 4 descriptor blocks beginning at offset 54. Each block is 18 bytes. // In each block, bytes 0-3 indicates the contents. int descriptor_ndx = 0; for (descriptor_ndx = 0; descriptor_ndx < EDID_DESCRIPTOR_BLOCK_CT; descriptor_ndx++) { const Byte * descriptor = edidbytes + EDID_DESCRIPTORS_BLOCKS_START + descriptor_ndx * EDID_DESCRIPTOR_BLOCK_SIZE; if (debug) printf("(%s) full descriptor: %s\n", __func__, hexstring(descriptor, EDID_DESCRIPTOR_BLOCK_SIZE)); // test if a string descriptor if ( descriptor[0] == 0x00 && // 0x00 if not a timing descriptor descriptor[1] == 0x00 && // 0x00 if not a timing descriptor descriptor[2] == 0x00 && // 0x00 for all descriptors descriptor[4] == 0x00 ) { char * nameslot = NULL; switch(descriptor[3]) { case 0xff: nameslot = snbuf; break; // monitor serial number case 0xfe: nameslot = otherbuf; break; // arbitrary ASCII string case 0xfc: nameslot = namebuf; break; // monitor name } if (nameslot) { const Byte * textstart = descriptor+5; // DBGMSF(debug, "String in descriptor: %s", hexstring(textstart, 14)); int offset = 0; while (textstart[offset] != 0x0a && offset < 13) { nameslot[offset] = textstart[offset]; offset++; } nameslot[offset] = '\0'; rtrim_in_place(nameslot); // handle no terminating LF but blank padded if (debug) printf("(%s) name = %s\n", __func__, nameslot); fields_found++; } } } } /** Parses an EDID. * * @param edidbytes pointer to 128 byte EDID block * * @return pointer to newly allocated Parsed_Edid struct, * or NULL if the bytes could not be parsed. * It is the responsibility of the caller to free this memory. * * @remark * The bytes pointed to by **edidbytes** are copied into the newly * allocated Parsed_Edid. If they were previously malloc'd they * need to free'd. */ Parsed_Edid * create_parsed_edid(const Byte* edidbytes) { assert(edidbytes); // bool debug = false; Parsed_Edid* parsed_edid = NULL; if ( !is_valid_edid_header(edidbytes) || !is_valid_edid_checksum(edidbytes) ) goto bye; parsed_edid = calloc(1,sizeof(Parsed_Edid)); assert(sizeof(parsed_edid->bytes) == 128); memcpy(parsed_edid->marker, EDID_MARKER_NAME, 4); memcpy(parsed_edid->bytes, edidbytes, 128); get_edid_mfg_id_in_buffer( edidbytes, parsed_edid->mfg_id, sizeof(parsed_edid->mfg_id) ); parsed_edid->product_code = edidbytes[0x0b] << 8 | edidbytes[0x0a]; parsed_edid->serial_binary = edidbytes[0x0c] | edidbytes[0x0d] << 8 | edidbytes[0x0e] << 16 | edidbytes[0x0f] << 24; get_edid_descriptor_strings( edidbytes, parsed_edid->model_name, sizeof(parsed_edid->model_name), parsed_edid->serial_ascii, sizeof(parsed_edid->serial_ascii), parsed_edid->extra_descriptor_string, sizeof(parsed_edid->extra_descriptor_string) ); parsed_edid->year = edidbytes[17] + 1990; parsed_edid->is_model_year = edidbytes[16] == 0xff; parsed_edid->manufacture_week = edidbytes[16]; parsed_edid->edid_version_major = edidbytes[18]; parsed_edid->edid_version_minor = edidbytes[19]; parsed_edid->rx = edidbytes[0x1b] << 2 | ( (edidbytes[0x19]&0b11000000)>>6 ); parsed_edid->ry = edidbytes[0x1c] << 2 | ( (edidbytes[0x19]&0b00110000)>>4 ); parsed_edid->gx = edidbytes[0x1d] << 2 | ( (edidbytes[0x19]&0b00001100)>>2 ); parsed_edid->gy = edidbytes[0x1e] << 2 | ( (edidbytes[0x19]&0b00000011)>>0 ); parsed_edid->bx = edidbytes[0x1f] << 2 | ( (edidbytes[0x1a]&0b11000000)>>6 ); parsed_edid->by = edidbytes[0x20] << 2 | ( (edidbytes[0x1a]&0b00110000)>>4 ); parsed_edid->wx = edidbytes[0x21] << 2 | ( (edidbytes[0x1a]&0b00001100)>>2 ); // parsed_edid->wy = edidbytes[0x22] << 2 | ( (edidbytes[0x1a]&0b00000011)>>0 ); // low order digits wrong, try another way parsed_edid->wy = edidbytes[0x22] * 4 + ((edidbytes[0x1a]&0b00000011)>>0); parsed_edid->video_input_definition = edidbytes[0x14]; // printf("(%s) video_input_parms_bitmap = 0x%02x\n", __func__, video_input_parms_bitmap); // parsed_edid->is_digital_input = (parsed_edid->video_input_definition & 0x80) ? true : false; parsed_edid->supported_features = edidbytes[0x18]; parsed_edid->extension_flag = edidbytes[0x7e]; bye: return parsed_edid; } /** Parses an EDID and sets the edid_source field. * * @param edidbytes pointer to 128 byte EDID block * @param source source of EDID, typically I2C but may be X11, * USB, SYSFS, DRM * * @return pointer to newly allocated Parsed_Edid struct, * or NULL if the bytes could not be parsed. * It is the responsibility of the caller to free this memory. * * **source** is copied to the Parsed_Edid and should be freed is it * was allocated. */ Parsed_Edid * create_parsed_edid2(const Byte* edidbytes, const char * source) { Parsed_Edid * edid = create_parsed_edid(edidbytes); if (edid) { assert(source && strlen(source) < EDID_SOURCE_FIELD_SIZE); STRLCPY(edid->edid_source, source, EDID_SOURCE_FIELD_SIZE); } return edid; } Parsed_Edid * copy_parsed_edid(Parsed_Edid * original) { bool debug = false; DBGF(debug, "Starting. original=%p", original); Parsed_Edid * copy = NULL; if (original) { // it's easier to simply reparse the bytes we know successfully parsed // than to perform a deep copy copy = create_parsed_edid(original->bytes); assert(copy); // the one field that won't have been reparsed memcpy(©->edid_source, original->edid_source, sizeof(original->edid_source)); // report_parsed_edid(copy, true, 2); } DBGF(debug, "Done. returning %p -> ", copy); return copy; } /** Frees a Parsed_Edid struct. * * @param parsed_edid pointer to Parsed_Edid struct to free */ void free_parsed_edid(Parsed_Edid * parsed_edid) { bool debug = false; assert( parsed_edid ); // show_backtrace(1); DBGF(debug, "(free_parsed_edid) parsed_edid=%p", parsed_edid); // ASSERT_WITH_BACKTRACE(memcmp(parsed_edid->marker, EDID_MARKER_NAME, 4)==0); if ( memcmp(parsed_edid->marker, EDID_MARKER_NAME, 4)==0 ) { parsed_edid->marker[3] = 'x'; // n. Parsed_Edid contains no pointers free(parsed_edid); } else { char * s = g_strdup_printf("Invalid free of Parsed_Edid@%p, marker=%s", parsed_edid, hexstring_t((unsigned char *) parsed_edid->marker, 4)); DBGF(true, "%s", s); syslog(LOG_USER|LOG_ERR, "(%s) %s", __func__, s); free(s); } } // TODO: generalize to base_asciify(char* s, char* prefix, char* suffix) // move to string_util.h /** Replaces every character in a string whose value is > 127 with * the string "", where HH is the hex value of the character. * * @param s string to convert * @return newly allocated modified character string * * The caller is responsible for freeing the returned string */ char * base_asciify(char * s) { int badct = 0; int ndx = 0; while (s[ndx]) { if (s[ndx] & 0x80 || s[ndx] < 32) badct++; ndx++; } int reqd = ndx + 1 + 4*badct; char* result = malloc(reqd); int respos = 0; ndx = 0; while(s[ndx]) { // printf("s[ndx] = %u\n", (unsigned char)s[ndx]); bool is_printable = s[ndx] >=32 && s[ndx] < 128 ; if ( is_printable) { result[respos++] = s[ndx]; } else { sprintf(result+respos, "", (unsigned char) s[ndx]); respos += 5; } ndx++; } result[respos] = '\0'; // printf("respos=%d, reqd=%d\n", respos, reqd); assert(respos == (reqd-1)); return result; } /** Replaces every character in a string whose value is > 127 with * the string "", where HH is the hex value of the character. * * @param s string to convert * @return converted string * * The returned value is valid until the next call to this function * in the current thread. */ char * base_asciify_t(char * s) { static GPrivate x_key = G_PRIVATE_INIT(g_free); static GPrivate x_len_key = G_PRIVATE_INIT(g_free); char * buftemp = base_asciify(s); char * buf = get_thread_dynamic_buffer(&x_key, &x_len_key, strlen(s)+1); strcpy(buf, buftemp); free(buftemp); return buf; } /** Writes EDID summary to the current report output destination. * (normally stdout, but may be changed by rpt_push_output_dest()) * * @param edid pointer to parsed edid struct * @param verbose_synopsis show additional EDID detail * @param show_raw include hex dump of EDID * @param depth logical indentation depth * * @remark * Output is written using rpt_ functions. */ void report_parsed_edid_base( Parsed_Edid * edid, bool verbose_synopsis, bool show_raw, int depth) { bool debug = false; if (debug) printf("(%s) Starting. edid=%p, verbose_synopsis=%s, show_raw=%s\n", __func__, (void*)edid, SBOOL(verbose_synopsis), sbool(show_raw)); if (debug) { show_backtrace(0); if (redirect_reports_to_syslog) backtrace_to_syslog(LOG_NOTICE, 0); } int d1 = depth+1; int d2 = depth+2; // verbose = true; if (edid) { rpt_vstring(depth,"EDID synopsis:"); rpt_vstring(d1,"Mfg id: %s - %s", edid->mfg_id, pnp_name(edid->mfg_id)); rpt_vstring(d1,"Model: %s", base_asciify_t(edid->model_name)); rpt_vstring(d1,"Product code: %u (0x%04x)", edid->product_code, edid->product_code); // rpt_vstring(d1,"Product code: %u", edid->product_code); rpt_vstring(d1,"Serial number: %s", base_asciify_t(edid->serial_ascii)); // Binary serial number is typically 0x00000000 or 0x01010101, but occasionally // useful for differentiating displays that share a generic ASCII "serial number" rpt_vstring(d1,"Binary serial number: %"PRIu32" (0x%08x)", edid->serial_binary, edid->serial_binary); if (edid->is_model_year) rpt_vstring(d1,"Model year: %d", edid->year); else rpt_vstring(d1,"Manufacture year: %d, Week: %d", edid->year, edid->manufacture_week); if (verbose_synopsis) { rpt_vstring(d1,"EDID version: %d.%d", edid->edid_version_major, edid->edid_version_minor); #ifdef TEST_ASCIIFY char bad[] = {0x81, 0x32, 0x83, 0x34, 0x85, 0x00}; strcpy(edid->extra_descriptor_string, bad); #endif rpt_vstring(d1,"Extra descriptor: %s", base_asciify_t(edid->extra_descriptor_string)); char explbuf[100]; explbuf[0] = '\0'; if (edid->video_input_definition & 0x80) { strcpy(explbuf, "Digital Input"); if (edid->edid_version_major == 1 && edid->edid_version_minor >= 4) { switch (edid->video_input_definition & 0x0f) { case 0x00: strcat(explbuf, " (Digital interface not defined)"); break; case 0x01: strcat(explbuf, " (DVI)"); break; case 0x02: strcat(explbuf, " (HDMI-a)"); break; case 0x03: strcat(explbuf, " (HDMI-b"); break; case 0x04: strcat(explbuf, " (MDDI)"); break; case 0x05: strcat(explbuf, " (DisplayPort)"); break; default: strcat(explbuf, " (Invalid DVI standard)"); } strcat(explbuf, ", Bit depth: "); switch ( (edid->video_input_definition & 0x70) >> 4) { case 0x00: strcat(explbuf, "undefined"); break; case 0x01: strcat(explbuf, "6"); break; case 0x02: strcat(explbuf, "8"); break; case 0x03: strcat(explbuf, "10"); break; case 0x04: strcat(explbuf, "12"); break; case 0x05: strcat(explbuf, "14"); break; case 0x06: strcat(explbuf, "16"); break; case 0x07: strcat(explbuf, " (x07 reserved)"); } } } else { strcpy(explbuf, "Analog Input"); } rpt_vstring(d1,"Video input definition: 0x%02x - %s", edid->video_input_definition, explbuf); // end, video_input_definition interpretation rpt_vstring(d1, "Supported features:"); if (edid->supported_features & 0x80) rpt_vstring(d2, "DPMS standby"); if (edid->supported_features & 0x40) rpt_vstring(d2, "DPMS suspend"); if (edid->supported_features & 0x20) rpt_vstring(d2, "DPMS active-off"); Byte display_type = (edid->supported_features & 0x18) >> 3; // bits 4-3 // printf("(%s) supported_features = 0x%02x, display_type = 0x%02x=%d\n", // __func__, edid->supported_features, display_type, display_type); if (edid->video_input_definition & 0x80) { // digital input switch(display_type) { case 0: rpt_vstring(d2, "Digital display type: RGB 4:4:4"); break; case 1: rpt_vstring(d2, "Digital display type: RGB 4:4:4 + YCrCb 4:4:4"); break; case 2: rpt_vstring(d2, "Digital display type: RGB 4:4:4 + YCrCb 4:2:2"); break; case 3: rpt_vstring(d2, "Digital display type: RGB 4:4:4 + YCrCb 4:4:4 + YCrCb 4:2:2"); break; default: rpt_vstring(d2, "Invalid digital display type: 0x%02x", display_type); } } else { // analog input switch(display_type) { case 0: rpt_vstring(d2, "Analog display type: Monochrome or grayscale"); break; case 1: rpt_vstring(d2, "Analog display type: Color"); break; case 2: rpt_vstring(d2, "Analog display type: Non-RGB color"); break; case 3: rpt_vstring(d2, "Undefined analog display type"); break; default: // should be PROGRAM_LOGIC_ERROR, but that would violate layering rpt_vstring(d2, "Invalid analog display type: 0x%02x", display_type); } } rpt_vstring(d2, "Standard sRGB color space: %s", (display_type & 0x02) ? "True" : "False"); // end supported_features interpretation rpt_vstring(d1,"White x,y: %.3f, %.3f", edid->wx/1024.0, edid->wy/1024.0); rpt_vstring(d1,"Red x,y: %.3f, %.3f", edid->rx/1024.0, edid->ry/1024.0); rpt_vstring(d1,"Green x,y: %.3f, %.3f", edid->gx/1024.0, edid->gy/1024.0); rpt_vstring(d1,"Blue x,y: %.3f, %.3f", edid->bx/1024.0, edid->by/1024.0); // restrict to EDID version >= 1.3? rpt_vstring(d1,"Extension blocks: %u", edid->extension_flag); if (strlen(edid->edid_source) > 0) // will be set only for USB devices, values "USB", "X11" rpt_vstring(depth,"EDID source: %s", edid->edid_source); } // if (verbose_synopsis) if (show_raw) { rpt_vstring(depth,"EDID hex dump:"); rpt_hex_dump(edid->bytes, 128, d1); } } // if (edid) else { if (verbose_synopsis) rpt_vstring(d1,"No EDID"); } if (debug) printf("(%s) Done.\n", __func__); } /** Reports whether this is an analog or digital display. * * @param edid pointer to parse edid struct * @retval false analog display * @retval true digital display */ bool is_input_digital(Parsed_Edid * edid) { return edid->video_input_definition & 0x80; } /** Writes a summary of an EDID to the current report output destination. * (normally stdout, but may be changed by rpt_push_output_dest()) * * @param edid pointer to parsed edid struct * @param verbose include hex dump of EDID * @param depth logical indentation depth */ void report_parsed_edid(Parsed_Edid * edid, bool verbose, int depth) { bool debug = false; if (debug) printf("(%s) Starting. verbose=%s\n", __func__, SBOOL(verbose)); report_parsed_edid_base(edid, verbose, verbose, depth); if (debug) printf("(%s) Done.\n", __func__); } /** Heuristic test for a laptop display. Observed laptop displays * never have the model name and serial numbers set. */ bool is_laptop_parsed_edid(Parsed_Edid * parsed_edid) { assert(parsed_edid); // 12/10/2024: seen laptop screen w. model name but not serial_ascii bool result = streq(parsed_edid->model_name, "") && streq(parsed_edid->serial_ascii,""); return result; } ddcutil-2.2.0/src/util/error_info.c0000644000175000001440000006676014754153540012723 /** \f error_info.c * * Struct for reporting errors. * * #Error_Info provides a pseudo-exception framework that can be integrated * with more traditional status codes. Instead of returning a status code, * a C function returns a pointer to an #Error_Info instance in the case of * an error, or NULL if there is no error. Information about the cause of an * error is retained for use by higher levels in the call stack. */ // Copyright (C) 2017-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include /** \endcond */ #include "debug_util.h" #include "glib_util.h" #include "msg_util.h" #include "report_util.h" #include "string_util.h" #include "traced_function_stack.h" #include "error_info.h" // Validates a pointer to an #Error_Info, using asserts #define VALID_ERROR_INFO_PTR(ptr) \ assert(ptr); \ if (memcmp(ptr->marker, ERROR_INFO_MARKER, 4) != 0) { \ DBG("Invalid ptr->marker, ptr=%p", ptr); \ show_backtrace(1); \ debug_current_traced_function_stack(false); \ } \ assert(memcmp(ptr->marker, ERROR_INFO_MARKER, 4) == 0); // Forward references static char * default_status_code_desc(int rc); // Constants // allows cause list to always be null terminated, even when no causes: static Error_Info * empty_list[] = {NULL}; static const int CAUSE_ALLOC_INCREMENT = 10; // Globals // status code to string functions: static ErrInfo_Status_String errinfo_desc_func = default_status_code_desc; static ErrInfo_Status_String errinfo_name_func = NULL; // // Initialization // /** Initializes the module. * * \param name_func function returning the name of a status code * \param desc_func function returning a description of a status code */ void errinfo_init( ErrInfo_Status_String name_func, ErrInfo_Status_String desc_func) { errinfo_name_func = name_func; errinfo_desc_func = desc_func; } // // Utilities // /** Checks whether all causes have the same status code. * If **status_code** != 0, all causes must have that value. * If **status_code** == 0, all causes must have the same status code * value as the first cause. * * @param erec pointer to #Error_Info instance * @param status_code status code value to check * @return true/false * * if **erec** == NULL or the instance has no causes, returns false. */ bool errinfo_all_causes_same_status( Error_Info * erec, int status_code) { bool debug = false; DBGF(debug, "Starting. status_code=%d, erec=%s", status_code, errinfo_summary(erec)); bool all_same = false; if (erec) { VALID_ERROR_INFO_PTR(erec); if (erec->cause_ct > 0) { if (status_code == 0) status_code = erec->causes[0]->status_code; all_same = true; for (int ndx = 0; ndx < erec->cause_ct; ndx++) { if (erec->causes[ndx]->status_code != status_code) { all_same = false; break; } } } } DBGF(debug, "Returning: %s", SBOOL(all_same)); return all_same; } #ifdef ALT bool errinfo_all_causes_same_status(Error_Info * ddc_excp, int status_code) { bool all_same = true; for (int ndx = 0; ndx < ddc_excp->cause_ct; ndx++) { if (ddc_excp->causes[ndx]->status_code != status_code) { all_same = false; break; } } return all_same; } #endif // // Instance destruction // /** Releases a #Error_Info instance, including all instances it points to. * * \param erec pointer to #Error_Info instance, do nothing if NULL */ void errinfo_free(Error_Info * erec){ bool debug = false; if (debug) { DBG("Starting. erec=%p", (void*)erec); // show_backtrace(2); // errinfo_report(erec, 2); } if (erec) { VALID_ERROR_INFO_PTR(erec); if (debug) { DBG("Freeing exception:"); errinfo_report(erec, 2); } if (erec->detail) free(erec->detail); if (erec->cause_ct > 0) { DBGF(debug, "Freeing causes..."); for (int ndx = 0; ndx < erec->cause_ct; ndx++) { errinfo_free(erec->causes[ndx]); } DBGF(debug, "Freeing erec->causes = %p", erec->causes); free(erec->causes); } #ifdef ALT if (erec->causes_alt) { for (int ndx = 0; ndx < erec->causes_alt->len; ndx++) { errinfo_free( g_ptr_array_index(erec->causes_alt, ndx) ); } } #endif free(erec->func); erec->marker[3] = 'x'; free(erec); } DBGF(debug, "Done. Free'd: %p", (void*) erec); } /** Releases a #Error_Info instance, including all instances it points to. * Optionally reports the instance before freeing it. * * \param erec pointer to #Error_Info instance, * do nothing if NULL * \param report if true, report the instance * \param func name of calling function */ void errinfo_free_with_report( Error_Info * erec, bool report, const char * func) { if (erec) { if (report) { rpt_vstring(0, "(%s) Freeing exception:", func); errinfo_report(erec, 1); } errinfo_free(erec); } } #ifdef ALT // signature satisfying GDestroyNotify() static void ddc_error_free2(void * erec) { Error_Info* erec2 = (Error_Info *) erec; VALID_ERROR_INFO_PTR(erec2); errinfo_free(erec2); } #endif // // Instance modification // /** Sets the status code in a existing #Error_Info instance. * * \param erec pointer to instance * \param code status code */ void errinfo_set_status(Error_Info * erec, int code) { VALID_ERROR_INFO_PTR(erec); erec->status_code = code; } /** Sets the detail string in a existing #Error_Info instance. * If there is already a detail string in the instance, it is replaced. * The substitution values for the detail string are specified as a va_list. * * \param erec pointer to instance * \param detail detail format string * \param args arguments for detail string */ static void errinfo_set_detailv( Error_Info * erec, const char * detail, va_list args) { if (detail) { erec->detail = g_strdup_vprintf(detail, args); } } /** Sets the detail string in a existing #Error_Info instance. * If there is already a detail string in the instance, it is replaced. * * \param erec pointer to instance * \param detail detail format string * \param ... arguments for detail format string */ void errinfo_set_detail( Error_Info * erec, const char * detail_fmt, ...) { VALID_ERROR_INFO_PTR(erec); if (erec->detail) { free(erec->detail); erec->detail = NULL; } va_list ap; va_start(ap, detail_fmt); errinfo_set_detailv(erec, detail_fmt, ap); va_end(ap); } /** Make a deep copy of a #Error_Info record. * * @param old record to copy * @return copy of record */ Error_Info * errinfo_copy(Error_Info* old) { bool debug = false; DBGF(debug, "Starting. old=%p", (void*) old); Error_Info * new = calloc(1, sizeof(Error_Info)); memcpy(new->marker, old->marker, 4); new->status_code = old->status_code; if (old->func) new->func = g_strdup(old->func); if (old->detail) new->detail = g_strdup(old->detail); new->max_causes = old->max_causes; new->cause_ct = old->cause_ct; if (new->cause_ct == 0) new->causes = empty_list; else { new->causes = calloc(new->max_causes+1, sizeof(Error_Info*)); DBGF(debug, "Allocated new->causes=%p, new->cause_ct=%d", (void*) new->causes, new->cause_ct); } for (int ndx = 0; ndx < new->cause_ct; ndx++) { new->causes[ndx] = errinfo_copy(old->causes[ndx]); } DBGF(debug, "Done. Returning %p", (void*) new); return new; } /** Adds a cause to an existing #Error_Info instance * * \param parent instance to which cause will be added * \param cause instance to add */ void errinfo_add_cause( Error_Info * parent, Error_Info * cause) { bool debug = false; DBGF(debug, "parent=%p, cause=%p", parent, cause); VALID_ERROR_INFO_PTR(parent); VALID_ERROR_INFO_PTR(cause); DBGF(debug, "parent->cause_ct = %d, parent->max_causes = %d", parent->cause_ct, parent->max_causes); if (parent->cause_ct == parent->max_causes) { int new_max = parent->max_causes + CAUSE_ALLOC_INCREMENT; #ifdef ALT Error_Info ** new_causes = calloc(new_max+1, sizeof(Error_Info *) ); memcpy(new_causes, parent->causes, parent->cause_ct * sizeof(Error_Info *) ); free(parent->causes); parent->causes = new_causes; #endif if (parent->causes == empty_list) { DBGF(debug, "empty_list"); parent->causes = calloc(new_max+1, sizeof(Error_Info *) ); } else { // works, but requires _GNU_SOURCE feature test macro: // parent->causes = reallocarray(parent->causes, new_max+1, sizeof(Error_Info*) ); void * new_causes = calloc(new_max+1, sizeof(Error_Info*) ); memcpy(new_causes, parent->causes, parent->max_causes * sizeof(Error_Info *) ); free(parent->causes); parent->causes = new_causes; } parent->max_causes = new_max; } DBGF(debug, "causes = %p, cause_ct=%d", parent->causes, parent->cause_ct); // DBGF(debug, "%p", &parent->causes[parent->cause_ct]); parent->causes[parent->cause_ct++] = cause; #ifdef ALT if (!parent->causes_alt) { parent->causes_alt = g_ptr_array_new_with_free_func(ddc_error_free2); // parent->causes_alt = g_ptr_array_new(); // *** TRANSITIONAL *** } g_ptr_array_add(parent->causes_alt, cause); #endif DBGF(debug, "Done. causes = %p, cause_ct=%d", parent->causes, parent->cause_ct); } // // Instance creation // /** Creates a new #Error_Info instance with the specified status code, * function name, and detail string. The substitution values for the * detail string are specified as a va_list. * * \param status_code status code * \param func name of function generating status code * \param detail detail string, may be NULL * \param args substitution values * \return pointer to new instance */ static Error_Info * errinfo_newv( int status_code, const char * func, const char * detail, va_list args) { bool debug = false; DBGF(debug, "Starting. status_code=%d, func=%s, detail=%s", status_code, func, detail); Error_Info * erec = calloc(1, sizeof(Error_Info)); memcpy(erec->marker, ERROR_INFO_MARKER, 4); erec->status_code = status_code; erec->causes = empty_list; erec->func = g_strdup(func); // g_strdup to avoid constness warning, must free if (detail) { erec->detail = g_strdup_vprintf(detail, args); } DBGF(debug, "Done: Returning %p", erec); return erec; } /** Creates a new #Error_Info instance with the specified status code, * function name, and detail string. * * \param status_code status code * \param func name of function generating status code * \param detail optional detail string * \param ... substitution values * \return pointer to new instance */ Error_Info * errinfo_new( int status_code, const char * func, const char * detail, ...) { Error_Info * erec = NULL; va_list ap; va_start(ap, detail); erec = errinfo_newv(status_code, func, detail, ap); va_end(ap); // errinfo_report(erec, 1); return erec; } /** Creates a new #Error_Info instance with a detail string, including a * reference to another instance that is the cause of the current error. * The substitution values for the detail string are specified as a va_list. * * \param status_code status code * \param cause pointer to another #Error_Info that is included as a cause * \param func name of function creating new instance * \param detail_fmt optional detail format string * \param args substitution value for detail_fmt * \return pointer to new instance */ static Error_Info * errinfo_new_with_causev( int status_code, Error_Info * cause, const char * func, const char * detail_fmt, va_list args) { Error_Info * erec = errinfo_newv(status_code, func, detail_fmt, args); if (cause) errinfo_add_cause(erec, cause); return erec; } /** Creates a new #Error_Info instance with a detail string, including a * reference to another instance that is the cause of the current error. * * \param status_code status code * \param cause pointer to another #Error_Info that is included as a cause * \param func name of function creating new instance * \param detail_fmt optional detail format string * \param ... optional arguments for detail_fmt * \return pointer to new instance */ Error_Info * errinfo_new_with_cause( int status_code, Error_Info * cause, const char * func, const char * detail_fmt, ...) { Error_Info * erec = NULL; va_list ap; va_start(ap, detail_fmt); erec = errinfo_new_with_causev(status_code, cause, func, detail_fmt, ap); va_end(ap); return erec; } #ifdef UNUSED /** Creates a new #Error_Info instance, including a reference to another * instance that is the cause of the current error. The status code * of the new instance is the same as that of the referenced instance. * * \param cause pointer to another #Error_Info that is included as a cause * \param func name of function creating new instance * \return pointer to new instance */ Error_Info * errinfo_new_chained( Error_Info * cause, const char * func) { VALID_ERROR_INFO_PTR(cause); Error_Info * erec = errinfo_new_with_cause(cause->status_code, cause, func); return erec; } #endif /** Creates a new #Error_Info instance with a collection of * instances specified as the causes. * * \param code status code of the new instance * \param causes array of #Error_Info instances * \param cause_ct number of causes * \param func name of function creating the new #Error_Info * \param detail detail format string * \param ... optional arguments for detail format string * \return pointer to new instance */ Error_Info * errinfo_new_with_causes( int status_code, Error_Info ** causes, int cause_ct, const char * func, char * detail, ...) { va_list ap; va_start(ap, detail); Error_Info * result = errinfo_newv(status_code, func, detail, ap); va_end(ap); for (int ndx = 0; ndx < cause_ct; ndx++) { errinfo_add_cause(result, causes[ndx]); } return result; } /** Creates a new #Error_Info instance with a collection of instances specified * as the causes. The collection is passed as a GPtrArray. A deep copy is * made of each instance in the collection, and the causes collection * is unchanged. * * \param code status code of the new instance * \param causes GPtrArray of #Error_Info instances * \param func name of function creating the new #Error_Info * \param detail detail format string * \param ... optional arguments for detail format string * \return pointer to new instance */ Error_Info * errinfo_new_with_causes_gptr( int status_code, GPtrArray* causes, const char * func, char * detail, ...) { bool debug = false; DBGF(debug, "Starting. status_code-%d, detail=%s", status_code, detail); va_list ap; va_start(ap, detail); Error_Info * result = errinfo_newv(status_code, func, detail, ap); va_end(ap); for (int ndx = 0; ndx < causes->len; ndx++) { errinfo_add_cause(result, errinfo_copy(g_ptr_array_index(causes,ndx))); } DBGF(debug, "Returning: %p", (void*) result); return result; } #ifdef UNUSED // For creating a new Ddc_Error when the called functions // return status codes not Ddc_Errors. /** Creates a new #Error_Info instance, including references to multiple * status codes from called functions that contribute to the current error. * Each of the callee status codes is wrapped in a synthesized #Error_Info * instance that is included as a cause. * * \param status_code * \param callee_status_codes array of status codes * \param callee_status_code_ct number of status codes in **callee_status_codes** * \param callee_func name of function that returned **callee** status codes * \param func name of function generating new #Error_Info * \return pointer to new instance */ Error_Info * errinfo_new_with_callee_status_codes( int status_code, int * callee_status_codes, int callee_status_code_ct, const char * callee_func, const char * func) { Error_Info * result = errinfo_new(status_code, func); for (int ndx = 0; ndx < callee_status_code_ct; ndx++) { Error_Info * cause = errinfo_new(callee_status_codes[ndx],callee_func); errinfo_add_cause(result, cause); } return result; } #endif // // Reporting // /** Status code description function to be used if none was set * by #errinfo_init() * * \param code status code * \return description of status code * * The value returned is valid until the next call to this function * in the current thread. */ static char * default_status_code_desc(int rc) { static GPrivate status_code_key = G_PRIVATE_INIT(g_free); const int default_status_code_buffer_size = 20; char * buf = get_thread_fixed_buffer(&status_code_key, default_status_code_buffer_size); g_snprintf(buf, default_status_code_buffer_size, "%d",rc); return buf; } /** Appends a comma separated string of the status code names of the * causes in an array of #Error_Info to an existing string. * Multiple consecutive identical names are replaced with a * single name and a parenthesized instance count. * * \param erec pointer to array of pointers to #Error_Info instances * \param error_ct number of errors * \return modified comma separated string */ static GString * errinfo_array_summary_gs( struct error_info ** errors, ///< pointer to array of pointers to #Error_Info int error_ct, ///< number of causal errors GString * gs) ///< append result here { bool first = true; int ndx = 0; while (ndx < error_ct) { // printf("(%s) this error = %p\n", __func__, errors[ndx]); int this_psc = errors[ndx]->status_code; int cur_ct = 1; for (int i = ndx+1; i < error_ct; i++) { if (errors[i]->status_code != this_psc) break; cur_ct++; } if (first) first = false; else g_string_append(gs, ", "); if (errinfo_name_func) g_string_append(gs, errinfo_name_func(this_psc)); else { char buf[20]; snprintf(buf, 20, "%d",this_psc); buf[19] = '\0'; g_string_append(gs, buf); } if (cur_ct > 1) g_string_append_printf(gs, "(%d)", cur_ct); ndx += cur_ct; } return gs; } /** Returns a comma separated string of the status code names of the * causes in an array of #Error_Info. * Multiple consecutive identical names are replaced with a * single name and a parenthesized instance count. * * \param errors pointer to array of pointers to #Error_Info instances * \param error_ct number of instances * \return comma separated string, caller is responsible for freeing */ char * errinfo_array_summary( struct error_info ** errors, ///< pointer to array of pointers to Error_Info int error_ct) { GString * gs = g_string_new(NULL); // printf("(%s) errors=%p\n", __func__, errors); errinfo_array_summary_gs(errors, error_ct, gs); char * result = gs->str; g_string_free(gs, false); // DBGMSF(debug, "Done. Returning: |%s|", result); return result; } /** Returns a comma separated string of the names of the status codes in the * causes of the specified #Error_Info. * Multiple consecutive identical names are replaced with a * single name and a parenthesized instance count. * * \param erec pointer to #Error_Info instance * \return comma separated string, caller is responsible for freeing */ char * errinfo_causes_string(Error_Info * erec) { // bool debug = false; GString * gs = g_string_new(NULL); if (erec) { assert(memcmp(erec->marker, ERROR_INFO_MARKER, 4) == 0); errinfo_array_summary_gs(erec->causes, erec->cause_ct, gs); } char * result = gs->str; g_string_free(gs, false); // DBGMSF(debug, "Done. Returning: |%s|", result); return result; #ifdef OLD GString * gs = g_string_new(NULL); if (erec) { assert(memcmp(erec->marker, ERROR_INFO_MARKER, 4) == 0); bool first = true; int ndx = 0; while (ndx < erec->cause_ct) { int this_psc = erec->causes[ndx]->status_code; int cur_ct = 1; for (int i = ndx+1; i < erec->cause_ct; i++) { if (erec->causes[i]->status_code != this_psc) break; cur_ct++; } if (first) first = false; else g_string_append(gs, ", "); if (errinfo_name_func) g_string_append(gs, errinfo_name_func(this_psc)); else { char buf[20]; snprintf(buf, 20, "%d",this_psc); buf[19] = '\0'; g_string_append(gs, buf); } if (cur_ct > 1) g_string_append_printf(gs, "(%d)", cur_ct); ndx += cur_ct; } } char * result = gs->str; g_string_free(gs, false); // DBGMSF(debug, "Done. Returning: |%s|", result); return result; #endif } #ifdef ALT char * errinfo_causes_string_alt(Error_Info * erec) { // bool debug = false; // DBGMSF(debug, "history=%p, history->ct=%d", history, history->ct); GString * gs = g_string_new(NULL); if (erec) { assert(memcmp(erec->marker, ERROR_INFO_MARKER, 4) == 0); if (erec->causes_alt) { bool first = true; int ndx = 0; int cause_ct = erec->causes_alt->len; while (ndx < cause_ct) { Error_Info * this_cause = g_ptr_array_index( erec->causes_alt, ndx); int this_psc = this_cause->status_code; int cur_ct = 1; for (int i = ndx+1; i < cause_ct; i++) { Error_Info * next_cause = g_ptr_array_index( erec->causes_alt, i); if (next_cause->status_code != this_psc) break; cur_ct++; } if (first) first = false; else g_string_append(gs, ", "); if (errinfo_name_func) g_string_append(gs, errinfo_name_func(this_psc)); else { char buf[20]; snprintf(buf, 20, "%d",this_psc); buf[19] = '\0'; g_string_append(gs, buf); } if (cur_ct > 1) g_string_append_printf(gs, "(x%d)", cur_ct); ndx += cur_ct; } } } char * result = gs->str; g_string_free(gs, false); // DBGMSF(debug, "Done. Returning: |%s|", result); return result; } #endif /** Creates a full report of the contents of the specified #Error_Info, * using report functions. if **collector** is non-null, the lines of * the report are appended to the array. If it is null, the lines * are written the current report output destination. * * \param erec pointer to #Error_Info * \param collector collects lines of the report * \param depth logical indentation depth */ void errinfo_report_collect(Error_Info * erec, GPtrArray* collector, int depth) { assert(erec); int d1 = depth+1; // rpt_vstring(depth, "(%s) Status code: %d", __func__, erec->status_code); // rpt_vstring(depth, "(%s) Location: %s", __func__, (erec->func) ? erec->func : "not set"); // rpt_vstring(depth, "(%s) errinfo_name_func=%p, errinfo_desc_func=%p", __func__, errinfo_name_func, errinfo_desc_func); // rpt_push_output_dest(stderr); rpt_vstring_collect(depth, collector, "Exception in function %s: status=%s", (erec->func) ? erec->func : "not set", errinfo_desc_func(erec->status_code) ); // can't call psc_desc(), violates layering if (erec->detail) rpt_label_collect(depth+1, collector, erec->detail); // rpt_pop_output_dest(); if (erec->cause_ct > 0) { rpt_vstring_collect(depth, collector, "Caused by: "); for (int ndx = 0; ndx < erec->cause_ct; ndx++) { errinfo_report_collect(erec->causes[ndx], collector, d1); } } #ifdef ALT if (erec->causes_alt && erec->causes_alt->len > 0) { rpt_vstring(depth, "Caused by: "); for (int ndx = 0; ndx < erec->causes_alt->len; ndx++) { errinfo_report( g_ptr_array_index(erec->causes_alt,ndx), d1); } } #endif // rpt_vstring(depth, "(%s) Done", __func__); } /** Emits a full report of the contents of the specified #Error_Info, * using report functions. * * \param erec pointer to #Error_Info * \param depth logical indentation depth */ void errinfo_report(Error_Info * erec, int depth) { errinfo_report_collect(erec, NULL, depth); } /** Reports detail strings for a #Error_Info record and * each of its contained errors. * * \param erec pointer = #Error_Info instance * \param depth logical indentation depth */ void errinfo_report_details(Error_Info * erec, int depth) { assert(erec); int d0 = depth; int d1 = depth+1; // rpt_vstring(depth, "Exception in function %s: status=%s", // (erec->func) ? erec->func : "not set", // errinfo_desc_func(erec->status_code) ); // can't call psc_desc(), violates layering if (erec->detail) rpt_label(d0, erec->detail); else rpt_vstring(d0, "Error %d in function %s",erec->status_code, erec->func); // printf("%s) cause_ct = %d\n", __func__, erec->cause_ct); if (erec->cause_ct > 0) { // rpt_vstring(depth, "Caused by: "); for (int ndx = 0; ndx < erec->cause_ct; ndx++) { errinfo_report_details(erec->causes[ndx], d1); } } } /** Returns a string summary of the specified #Error_Info. * The returned value is valid until the next call to this function in the * current thread, and should not be freed by the caller. * * \param erec pointer to #Error_Info instance * \return string summary of error */ char * errinfo_summary(Error_Info * erec) { if (!erec) return "NULL"; VALID_ERROR_INFO_PTR(erec); static GPrivate esumm_key = G_PRIVATE_INIT(g_free); static GPrivate esumm_len_key = G_PRIVATE_INIT(g_free); // rpt_vstring(1, "(%s) errinfo_name_func=%p, errinfo_desc_func=%p", __func__, errinfo_name_func, errinfo_desc_func); char * desc = errinfo_name_func(erec->status_code); // thread safe buffer owned by psc_desc(), do not free() gchar * buf1 = NULL; if (erec->cause_ct == 0) { #ifdef ALT if (erec->causes_alt || erec->causes_alt->len == 0) { #endif buf1 = g_strdup_printf("Error_Info[%s in %s]", desc, erec->func); } else { char * causes = errinfo_causes_string(erec); buf1 = g_strdup_printf("Error_Info[%s in %s, causes: %s]", desc, erec->func, causes); free(causes); } int required_size = strlen(buf1) + 1; char * buf = get_thread_dynamic_buffer(&esumm_key, &esumm_len_key, required_size); strcpy(buf, buf1); free(buf1); return buf; } ddcutil-2.2.0/src/util/file_util.c0000644000175000001440000007230514754153540012523 /** \file file_util.c * File utility functions */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "data_structures.h" #include "debug_util.h" #include "report_util.h" #include "string_util.h" #include "subprocess_util.h" #include "file_util.h" /** Reads the lines of a text file into a GPtrArray, returning a #Error_Info struct * if an error occurs. * * @param fn file name * @param lines pointer to GPtrArray of strings where lines will be saved * * @return NULL if success, newly allocated #Error_Info struct if error * * The caller is responsible for freeing the lines added to line_array. * * @todo * Consider reimplementing with modified code of file_getlines(), to return more granular #Error_Info */ Error_Info * file_getlines_errinfo( const char * filename, GPtrArray * lines) { Error_Info * errs = NULL; int rc = file_getlines(filename, lines, false); if (rc < 0) { char * detail = g_strdup_printf("Error reading file %s", filename); errs = errinfo_new( rc, __func__, detail); free(detail); } return errs; } /** Reads the last lines of a text file into a GPtrArray. * * @param fn file name * @param line_array pointer to GPtrArray of strings where lines will be saved * @param verbose if true, write message to stderr if unable to open file or other error * * @retval >=0: number of lines added to line_array * @retval <0 -errno * * The caller is responsible for freeing the lines added to line_array. */ int file_get_last_lines( const char * fn, int maxlines, GPtrArray** line_array_loc, bool verbose) { bool debug = false; if (debug) printf("(%s) Starting. fn=%s, maxlines=%d\n", __func__, fn, maxlines ); int rc = 0; FILE * fp = fopen(fn, "r"); if (!fp) { int errsv = errno; rc = -errno; if (verbose) fprintf(stderr, "Error opening file %s: %s\n", fn, strerror(errsv)); } else { Circular_String_Buffer* csb = csb_new(maxlines); // if line == NULL && len == 0, then getline allocates buffer for line char * line = NULL; size_t len = 0; int linectr = 0; errno = 0; // line == NULL and len == 0 => getline() allocates buffer, caller must free while (getline(&line, &len, fp) >= 0) { linectr++; rtrim_in_place(line); // strip trailing newline csb_add(csb, line, /*copy=*/ true); // printf("(%s) Retrieved line of length %zu: %s\n", __func__, read, line); free(line); line = NULL; // reset for next getline() call len = 0; } if (errno != 0) { // getline error? rc = -errno; if (verbose) fprintf(stderr, "Error reading file %s: %s\n", fn, strerror(-rc)); } rc = linectr; if (debug) printf("(%s) Read %d lines\n", __func__, linectr); if (rc > maxlines) rc = maxlines; *line_array_loc = csb_to_g_ptr_array(csb); csb_free(csb,false); // if (debug) { // GPtrArray * la = *line_array_loc; // printf("(%s) (*line_array_loc)->len=%d\n", __func__, la->len); // if (la->len > 0) // printf("(%s) Line 0: %s\n", __func__, (char*)g_ptr_array_index(la, 0)); // if (la->len > 1) // printf("(%s) Line 1: %s\n", __func__, (char*)g_ptr_array_index(la, 1)); // if (la->len > 2) { // printf("(%s) Line %d: %s\n", __func__, la->len-2, (char*)g_ptr_array_index(la, la->len-2)); // printf("(%s) Line %d: %s\n", __func__, la->len-1, (char*)g_ptr_array_index(la, la->len-1)); // } // } fclose(fp); } if (debug) printf("(%s) Done. returning: %d\n", __func__, rc); return rc; } /** Reads the first line of a file. * * @param fn file name * @param verbose if true, write message to stderr if unable to open file * * @retval non-NULL pointer to line read (caller responsible for freeing) * @retval NULL if error or no lines in file */ char * file_get_first_line( const char * fn, bool verbose) { FILE * fp = fopen(fn, "r"); char * single_line = NULL; if (!fp) { if (verbose) fprintf(stderr, "Error opening %s: %s\n", fn, strerror(errno)); // TODO: strerror() not thread safe } else { size_t len = 0; ssize_t read; // just one line: read = getline(&single_line, &len, fp); if (read == -1) { if (verbose) printf("Nothing to read from %s\n", fn); } else { if (strlen(single_line) > 0) { // single_line has trailing \n, replace it with '\0' single_line[strlen(single_line)-1] = '\0'; // printf("\n%s", single_line); // single_line has trailing \n } } fclose(fp); } // printf("(%s) fn=|%s|, returning: %p -> |%s|\n", __func__, fn, single_line, single_line); return single_line; } /** Reads a binary file, returning it as a **GByteArray**. * * \param fn file name * \param est_size estimated size * \param verbose if open fails, write message to stderr * \return if file opened, a **GByteArray** of bytes (may be 0 lengh), caller is responsible for freeing * if file cannot be opened, then NULL */ GByteArray * read_binary_file( const char * fn, int est_size, bool verbose) { assert(fn); bool debug = false; if (debug) printf("(%s) Starting. fn=%s,est_size=%d\n", __func__, fn, est_size); Byte buf[1]; GByteArray * gbarray = NULL; FILE * fp; if (!(fp = fopen(fn, "r"))) { int errsv = errno; if (verbose){ fprintf(stderr, "Error opening \"%s\", %s\n", fn, strerror(errsv)); } goto bye; } if (est_size <= 0) gbarray = g_byte_array_new(); else gbarray = g_byte_array_sized_new(est_size); // TODO: read bigger hunks size_t ct = 0; while ( (ct = fread(buf, /*size*/ 1, /*nmemb*/ 1, fp) ) > 0) { assert(ct == 1); g_byte_array_append(gbarray, buf, ct); } fclose(fp); bye: // printf("(%s) bye\n", __func__); if (debug) { if (gbarray) printf("(%s) Done. Returning GByteArray at %p, gbarray->data=%p, gbarray->len=%d\n", __func__, (void*)gbarray, (void*)gbarray->data, gbarray->len); else printf("(%s) Returning NULL\n", __func__); } // printf("(%s) byebye\n", __func__); return gbarray; } /** Reads an entire file as a single string. * As a precaution, a trailing \0 is appended to the returned value. * * The caller is responsible for freeing the returned buffer. * * @param filename file name * @param verbose white error message to stderr if unable to read * @return pointer to newly allocated buffer, NULL if file not read */ char * read_file_single_string(const char * filename, bool verbose) { char * buffer = NULL; long length; FILE * fp = fopen (filename, "rb"); if (!fp) { if (verbose) fprintf(stderr, "Error opening \"%s\", %s\n", filename, strerror(errno)); goto bye; } if (fp) { fseek (fp, 0, SEEK_END); length = ftell (fp); if (length < 0) { // make coverity happy if (verbose) { fprintf(stderr, "ftell() error on file \"%s\", %s\n", filename, strerror(errno)); } fclose(fp); goto bye; } fseek(fp, 0, SEEK_SET); buffer = malloc (length+1); assert(buffer); size_t len1 = fread(buffer, 1, length, fp); // len1 assignment to avoid unused result error assert(len1 == length); fclose (fp); buffer[len1] = '\0'; // ensure there's a trailing null } bye: return buffer; } /** Checks if a file exists, without checking type * * @param fqfn fully qualified file name * @return true/false */ bool any_file_exists(const char * fqfn) { struct stat stat_buf; int rc = stat(fqfn, &stat_buf); return (rc == 0); } /** Checks if a regular file exists. * * @param fqfn fully qualified file name * @return true/false */ bool regular_file_exists(const char * fqfn) { bool result = false; struct stat stat_buf; int rc = stat(fqfn, &stat_buf); if (rc == 0) { result = S_ISREG(stat_buf.st_mode); } return result; } /** Checks if a directory exists. * * @param fqfn fully qualified directory name * @return true/false */ bool directory_exists(const char * fqfn) { bool result = false; struct stat stat_buf; int rc = stat(fqfn, &stat_buf); if (rc == 0) { result = S_ISDIR(stat_buf.st_mode); } return result; } /** Scans list of directories to obtain file names matching a criterion * * @param dirnames null terminated array of pointers to directory names * @param filter_func tests directory entry * * @return GPtrArray of fully qualified file names * * A free function is set on the returned GPtrArray, so g_ptr_array_free() releases * all the file names * * Adapted from usbmonctl */ GPtrArray * get_filenames_by_filter( const char * dirnames[], Dirent_Filter filter_func) { // const char *hiddev_paths[] = { "/dev/", "/dev/usb/", NULL }; bool debug = false; GPtrArray * devnames = g_ptr_array_new(); g_ptr_array_set_free_func(devnames, g_free); char path[PATH_MAX]; for (int i = 0; dirnames[i] != NULL; i++) { struct dirent ** filelist; int count = scandir(dirnames[i], &filelist, filter_func, alphasort); if (count < 0) { assert(count == -1); fprintf(stderr, "(%s) scandir() error: %s\n", __func__, strerror(errno)); continue; } for (int j = 0; j < count; j++) { snprintf(path, PATH_MAX, "%s%s", dirnames[i], filelist[j]->d_name); g_ptr_array_add(devnames, g_strdup(path)); free(filelist[j]); } free(filelist); } if (debug) { printf("(%s) Found %d file names:\n", __func__, devnames->len); for (int ndx = 0; ndx < devnames->len; ndx++) printf(" %s\n", (char *) g_ptr_array_index(devnames, ndx) ); } return devnames; } /** Gets the file name for a file descriptor * * @param fd file descriptor * @param filename_loc where to return a pointer to the file name * The caller is responsible for freeing this memory * * @retval 0 success * @retval -errno if error (see readlink() doc for possible error numbers) */ int filename_for_fd(int fd, char** filename_loc) { bool debug = false; if (debug) printf("(%s) Starting. fd=%d, filname_loc=%p\n", __func__, fd, filename_loc); char * result = calloc(1, PATH_MAX+1); char workbuf[40]; int rc = 0; snprintf(workbuf, 40, "/proc/self/fd/%d", fd); if (debug) printf("(%s) workbuf = |%s|\n", __func__, workbuf); ssize_t ct = readlink(workbuf, result, PATH_MAX); if (debug) { char b0[100]; snprintf(b0, 100, "ls -l %s", workbuf); execute_shell_cmd(b0); } if (ct < 0) { rc = -errno; free(result); *filename_loc = NULL; } else { assert(ct <= PATH_MAX); result[ct] = '\0'; *filename_loc = result; } if (debug) printf("(%s) fd=%d, ct=%zd, returning: %d, *filename_loc=%p -> |%s|\n", __func__, fd, ct, rc, *filename_loc, *filename_loc); return rc; } /** Gets the file name for a file descriptor. * * The value returned is valid until the next call to this function * in the current thread. * * @param fd file descriptor * @return file name, NULL if error */ char * filename_for_fd_t(int fd) { bool debug = false; if (debug) printf("(%s) Starting. fd=%d\n", __func__, fd); static GPrivate key = G_PRIVATE_INIT(g_free); char * fn_buf = get_thread_fixed_buffer(&key, PATH_MAX); char * result = NULL; // value to return char * filename; int rc = filename_for_fd(fd, &filename); if (debug) printf("(%s) filename_for_fd() returned rc=%d filename->|%s|\n", __func__, rc, filename); if (rc == 0) { int ct = g_strlcpy(fn_buf, filename, PATH_MAX); if (debug) printf("(%s) ct=%d\n", __func__, ct); free(filename); result = fn_buf; } if (debug) printf("(%s) Returning: |%s|\n", __func__, result); return result; } /** Handles the boilerplate of iterating over a directory. * * \param dirname directory name * \param fn_filter tests the name of a file in a directory to see if should * be processed. If NULL, all files are processed. * \param func function to be called for each filename in the directory * \param accumulator pointer to a data structure passed * \param depth logical indentation depth */ void dir_foreach( const char * dirname, Filename_Filter_Func fn_filter, Dir_Foreach_Func func, void * accumulator, int depth) { // bool debug = true; // DBGF(debug, "Starting. accumulator=%p", accumulator); struct dirent *dent; DIR *d; d = opendir(dirname); if (!d) { rpt_vstring(depth,"Unable to open directory %s: %s", dirname, strerror(errno)); } else { while ((dent = readdir(d)) != NULL) { // DBGMSG("%s", dent->d_name); if (!streq(dent->d_name, ".") && !streq(dent->d_name, "..") ) { if (!fn_filter || fn_filter(dent->d_name)) { func(dirname, dent->d_name, accumulator, depth); } } } closedir(d); } // DBGF(debug, "Done. accumlator=%p", accumulator); } void dir_foreach_terminatable( const char * dirname, Filename_Filter_Func fn_filter, Terminating_Dir_Foreach_Func func, void * accumulator, int depth) { struct dirent *dent; DIR *d; d = opendir(dirname); if (!d) { rpt_vstring(depth,"Unable to open directory %s: %s", dirname, strerror(errno)); } else { while ((dent = readdir(d)) != NULL) { // DBGMSG("%s", dent->d_name); if (!streq(dent->d_name, ".") && !streq(dent->d_name, "..") ) { if (!fn_filter || fn_filter(dent->d_name)) { bool halt = func(dirname, dent->d_name, accumulator, depth); if (halt) break; } } } closedir(d); } } /** Iterates over a directory in an ordered manner. * * \param dirname directory name * \param fn_filter tests the name of a file in a directory to see if should * be processed. If NULL, all files are processed. * \param compare_func qsort style function to compare filenames. If NULL perform string comparison * \param func function to be called for each filename in the directory * \param accumulator pointer to a data structure passed * \param depth logical indentation depth */ void dir_ordered_foreach( const char * dirname, Filename_Filter_Func fn_filter, GCompareFunc compare_func, Dir_Foreach_Func func, void * accumulator, int depth) { GPtrArray * simple_filenames = g_ptr_array_new_with_free_func(g_free); struct dirent *dent; DIR *d; d = opendir(dirname); if (!d) { rpt_vstring(depth,"Unable to open directory %s: %s", dirname, strerror(errno)); } else { while ((dent = readdir(d)) != NULL) { // DBGMSG("%s", dent->d_name); if (!streq(dent->d_name, ".") && !streq(dent->d_name, "..") ) { if (!fn_filter || fn_filter(dent->d_name)) { g_ptr_array_add(simple_filenames, g_strdup(dent->d_name)); } } } closedir(d); if (compare_func) g_ptr_array_sort(simple_filenames, compare_func); else g_ptr_array_sort(simple_filenames, indirect_strcmp); for (int ndx = 0; ndx < simple_filenames->len; ndx++) { char * fn = g_ptr_array_index(simple_filenames, ndx); func(dirname, fn, accumulator, depth); } } g_ptr_array_free(simple_filenames, true); } void dir_ordered_foreach_with_arg( const char * dirname, Filename_Filter_Func_With_Arg fn_filter, const char * fn_filter_argument, GCompareFunc compare_func, Dir_Foreach_Func func, void * accumulator, int depth) { bool debug = false; if (debug) printf("(%s) Starting. dirname=%s, fn_filter_argument=|%s|\n", __func__, dirname, fn_filter_argument); GPtrArray * simple_filenames = g_ptr_array_new_with_free_func(g_free); struct dirent *dent; DIR *d; d = opendir(dirname); if (!d) { rpt_vstring(depth,"Unable to open directory %s: %s", dirname, strerror(errno)); } else { while ((dent = readdir(d)) != NULL) { if (debug) printf("(%s) %s\n", __func__, dent->d_name); if (!streq(dent->d_name, ".") && !streq(dent->d_name, "..") ) { if (!fn_filter || fn_filter(dent->d_name, fn_filter_argument)) { if (debug) printf("(%s) Adding simple filename |%s|\n", __func__, dent->d_name); g_ptr_array_add(simple_filenames, g_strdup(dent->d_name)); } } } closedir(d); if (compare_func) g_ptr_array_sort(simple_filenames, compare_func); else g_ptr_array_sort(simple_filenames, indirect_strcmp); for (int ndx = 0; ndx < simple_filenames->len; ndx++) { char * fn = g_ptr_array_index(simple_filenames, ndx); if (debug) printf("(%s) Calling Dir_Foreach_Func, dirname=%s, fn=%s\n", __func__, dirname, fn); func(dirname, fn, accumulator, depth); } g_ptr_array_free(simple_filenames, true); } if (debug) printf("(%s) Done.\n", __func__); } /** Selects files from a directory using a filter function, * then Iterates over the selected files in an ordered manner. * * \param dirname directory name * \param dir_filter tests the name of a file in a directory to see if should * be processed. If NULL, all files are processed. * \param compare_func qsort style function to compare filenames. If NULL perform string comparison * \param func function to be called for each file processed * \param accumulator pointer to a data structure passed * \param depth logical indentation depth */ void dir_filtered_ordered_foreach( const char * dirname, Dir_Filter_Func dir_filter, GCompareFunc compare_func, Dir_Foreach_Func func, void * accumulator, int depth) { GPtrArray * simple_filenames = g_ptr_array_new(); g_ptr_array_set_free_func(simple_filenames, free); struct dirent *dent; DIR *d; d = opendir(dirname); if (!d) { rpt_vstring(depth,"Unable to open directory %s: %s", dirname, strerror(errno)); } else { while ((dent = readdir(d)) != NULL) { // DBGMSG("%s", dent->d_name); if (!streq(dent->d_name, ".") && !streq(dent->d_name, "..") ) { if (!dir_filter || dir_filter(dirname, dent->d_name)) { g_ptr_array_add(simple_filenames, g_strdup(dent->d_name)); } } } closedir(d); if (compare_func) g_ptr_array_sort(simple_filenames, compare_func); else g_ptr_array_sort(simple_filenames, indirect_strcmp); for (int ndx = 0; ndx < simple_filenames->len; ndx++) { char * fn = g_ptr_array_index(simple_filenames, ndx); func(dirname, fn, accumulator, depth); } } g_ptr_array_free(simple_filenames, true); } /** Reads the contents of a file into a #GPtrArray of lines, optionally keeping only * those lines containing at least one in a list of terms. After filtering, the set * of returned lines may be further reduced to either the first or last N number of * lines. * * \param line_array #GPtrArray in which to return the lines read * \param fn file name * \param filter_terms #Null_Terminated_String_Away of filter terms * \param ignore_case ignore case when testing filter terms * \param limit if 0, return all lines that pass filter terms * if > 0, return at most the first #limit lines that satisfy the filter terms * if < 0, return at most the last #limit lines that satisfy the filter terms * \return if >= 0, number of lines before filtering and limit applied * if < 0, -errno, from file_getlines(), i.e. fopen(), getline() * * **line_array** is emptied at start of function execution. * Lines read are appended to existing lines in line_array * \remark * This function was created because using grep in conjunction with pipes was * producing obscure shell errors. * \remark * Returning the count of unfiltered lines is a bit odd, but the caller can * get the filtered count from line_array->len */ int read_file_with_filter( GPtrArray * line_array, const char * fn, char ** filter_terms, bool ignore_case, int limit, bool free_strings) { bool debug = false; if (debug) { printf("(%s) line_array=%p, fn=%s, ct(filter_terms)=%d, ignore_case=%s, limit=%d\n", __func__, (void*)line_array, fn, ntsa_length(filter_terms), sbool(ignore_case), limit); if (ntsa_length(filter_terms) > 0) { printf("(%s) filter_terms:\n", __func__); for (char ** term_ptr = filter_terms; *term_ptr; term_ptr++) printf("(%s) |%s|\n", __func__, *term_ptr); } } g_ptr_array_set_free_func(line_array, g_free); // in case not already set g_ptr_array_remove_range(line_array, 0, line_array->len); int rc = file_getlines(fn, line_array, /*verbose*/ false); if (debug) printf("(%s) file_getlines() returned %d\n", __func__, rc); if (rc > 0) { filter_and_limit_g_ptr_array( line_array, filter_terms, ignore_case, limit, free_strings); } else { // rc == 0 if (debug) printf("(%s) Empty file\n", __func__); } if (debug) printf("(%s) Done. Returning: %d\n", __func__, rc); return rc; } /** Deletes lines from a #GPtrArray of text lines. If filter terms * are specified, lines not satisfying any of the search terms are * deleted. Then, if **limit** is specified, at most the limit * number of lines are left. * * \param line_array GPtrArray of null-terminated strings * \param filter_terms null-terminated string array of terms * \param ignore_case if true, ignore case when testing filter terms * \param limit if 0, return all lines that pass filter terms * if > 0, return at most the first #limit lines that satisfy the filter terms * if < 0, return at most the last #limit lines that satisfy the filter terms * \param free_strings free strings removed from the array * \remark * Consider allowing filter_terms to be regular expressions. * * 1/2024: rare segfault seen */ void filter_and_limit_g_ptr_array( GPtrArray * line_array, char ** filter_terms, bool ignore_case, int limit, bool free_strings) { // bool debug = false; // if (debug) { // DBGMSG("line_array=%p, line_array->len=%d, ct(filter_terms)=%d, ignore_case=%s, limit=%d", // line_array, line_array->len, ntsa_length(filter_terms), sbool(ignore_case), limit); // // (const char **) cast to conform to strjoin() signature // char * s = strjoin( (const char **) filter_terms, -1, ", "); // DBGMSG("Filter terms: %s", s); // free(s); // }; #ifdef TOO_MUCH if (debug) { if (filter_terms) { printf("(%s) filter_terms:\n", __func__); ntsa_show(filter_terms); } } #endif // inefficient, just make it work for now for (int ndx = (line_array->len)-1 ; ndx >= 0; ndx--) { char * s = g_ptr_array_index(line_array, ndx); assert(s); // printf("s=|%s|\n", s); bool keep = true; if (filter_terms) keep = apply_filter_terms(s, filter_terms, ignore_case); if (!keep) { g_ptr_array_remove_index(line_array, ndx); if (free_strings) free(s); } } gaux_ptr_array_truncate(line_array, limit); // DBGMSF(debug, "Done. line_array->len=%d", line_array->len); } void filter_and_limit_g_ptr_array2( GPtrArray * line_array, char ** filter_terms, bool ignore_case, int limit) { bool debug = false; if (debug) { DBG("line_array=%p, line_array->len=%d, ct(filter_terms)=%d, ignore_case=%s, limit=%d", line_array, line_array->len, ntsa_length(filter_terms), sbool(ignore_case), limit); // (const char **) cast to conform to strjoin() signature char * s = strjoin( (const char **) filter_terms, -1, ", "); DBG("Filter terms: %s", s); free(s); } int max_size = line_array->len; if (limit > 0) max_size = limit; else if (limit < 0) max_size = -limit; GPtrArray * new_array = g_ptr_array_sized_new(max_size); g_ptr_array_set_free_func(new_array, g_free); for (int ndx = 0; ndx < line_array->len; ndx++) { char * s = g_ptr_array_index(line_array, ndx); assert(s); DBGF(debug, "s=|%s|", s); bool keep = true; if (filter_terms) keep = apply_filter_terms(s, filter_terms, ignore_case); if (keep) g_ptr_array_add(new_array, g_strdup(s)); } // g_ptr_array_remove_range(line_array, 0, line_array->len); g_ptr_array_set_size(line_array, 0); for (int ndx = 0; ndx < new_array->len; ndx++) { g_ptr_array_add(line_array, g_ptr_array_index(new_array, ndx)); } g_ptr_array_free(new_array, false); DBGF(debug, "Done. line_array->len=%d", line_array->len); } /** Given a directory, if the directory does not already exist, * creates the directory along with any required parent directories. * * \param path * \ferr if non-null, destination for error messages * \return 0 if success, -errno if error * * \remark * Based on answer by Jens Harms to * https://stackoverflow.com/questions/7430248/creating-a-new-directory-in-c */ int rek_mkdir( const char *path, FILE * ferr) { bool debug = false; if (debug) printf("(%s) Starting, path=%s\n", __func__, path); int result = 0; if (!directory_exists(path)) { char *sep = strrchr(path, '/'); if (sep) { *sep = 0; result = rek_mkdir(path, ferr); // create parent dir *sep = '/'; } if (result == 0) { if (debug) printf("(%s) Creating path %s\n", __func__, path); if ( mkdir(path, 0777) < 0) { result = -errno; if (ferr) f0printf(ferr, "Unable to create '%s', %s\n", path, strerror(errno)); } } } if (debug) printf("(%s) Done. returning %d\n", __func__, result); return result; } /** Opens a file for writing, creating parent directories if necessary. * * \param path * \param mode * \param ferr if non-null, destination for error messages * \param fp_loc address at which a pointer to the open file is returned * \return 0 if successful, -errno if error */ int fopen_mkdir( const char *path, const char *mode, FILE *ferr, FILE **fp_loc) { bool debug = false; if (debug) printf("(%s) Starting. path=%s, mode=%s, fp_loc=%p\n", __func__, path, mode, (void*)fp_loc); int rc = 0; *fp_loc = NULL; char *sep = strrchr(path, '/'); if (sep) { char *path0 = g_strdup(path); path0[ sep - path ] = 0; rc = rek_mkdir(path0, ferr); free(path0); } if (!rc) { *fp_loc = fopen(path,mode); if (!*fp_loc) { rc = -errno; if (ferr) f0printf(ferr, "Unable to open %s with mode %s: %s\n", path, mode, strerror(errno)); } } assert( (rc == 0 && *fp_loc) || (rc != 0 && !*fp_loc ) ); if (debug) printf("(%s) Done. returning %d\n", __func__, rc); return rc; } long get_inode_by_fn(const char * fqfn) { long result = -1; if (fqfn) { struct stat stat_buf; int rc = stat(fqfn, &stat_buf); if (rc == 0) { result = stat_buf.st_ino; } } return result; } long get_inode_by_fd(int fd) { long result = -1; struct stat stat_buf; int rc = fstat(fd, &stat_buf); if (rc == 0) { result = stat_buf.st_ino; } return result; } #ifdef UNUSED void set_fd_blocking(int fd) { int flags = fcntl(fd, F_GETFL, /* ignored for F_GETFL */ 0); assert (flags != -1); flags &= ~O_NONBLOCK; (void) fcntl(fd, F_SETFL, flags); assert(rc != -1); } #endif ddcutil-2.2.0/src/util/file_util_base.c0000644000175000001440000000547614754153540013522 /** @file file_util_base.c * * Core file utility functions. * Factored out of file_util.h so that includes in directory util form * a directed graph. */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include /** \endcond */ #include "data_structures.h" #include "string_util.h" #include "file_util_base.h" /** Reads the lines of a text file into a GPtrArray. * * @param fn file name * @param line_array pointer to GPtrArray of strings where lines will be saved * @param verbose if true, write message to stderr if unable to open file or other error * * @retval >=0: number of lines added to line_array * @retval <0 -errno from fopen() or getline() * * The caller is responsible for freeing the lines added to line_array. * * Strings are appended to #line_array. It is not cleared at start of * function execution. */ int file_getlines( const char * fn, GPtrArray* line_array, bool verbose) { bool debug = false; if (debug) printf("(%s) Starting. fn=%s \n", __func__, fn ); int rc = 0; FILE * fp = fopen(fn, "r"); if (!fp) { int errsv = errno; rc = -errno; if (verbose || debug) fprintf(stderr, "Error opening file %s: %s\n", fn, strerror(errsv)); } else { // if line == NULL && len == 0, then getline allocates buffer for line char * line = NULL; size_t len = 0; int linectr = 0; errno = 0; // int getline_rc = 0; while ( getline(&line, &len, fp) >= 0) { linectr++; rtrim_in_place(line); // strip trailing newline g_ptr_array_add(line_array, line); // line will be freed when line_array is freed if (debug) { printf("(%s) Retrieved line of length %zu, trimmed length %zu: %s\n", __func__, len, strlen(line), line); } line = NULL; // reset for next getline() call len = 0; } // From the getline() man page: // If *lineptr is set to NULL and *n is set 0 before the call, // then getline() will allocate a buffer for storing the line. // This buffer should be freed by the user program even if getline() failed. free(line); // assert(getline_rc < 0); if (errno != 0) { // was it an error or eof? rc = -errno; if (verbose || debug) fprintf(stderr, "Error reading file %s: %s\n", fn, strerror(-rc)); } else rc = linectr; fclose(fp); } if (debug) printf("(%s) Done. returning: %d\n", __func__, rc); return rc; } ddcutil-2.2.0/src/util/glib_util.c0000644000175000001440000002612614634376340012523 /** @file glib_util.c * * Utility functions for glib. */ // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include /** \endcond */ #include "glib_util.h" #include "string_util.h" #ifdef ALTERNATIVE // create private copy of g_hash_table_get_keys_as_array() /** * g_hash_table_get_keys_as_array: * @hash_table: a #GHashTable * @length: (out): the length of the returned array * * Retrieves every key inside @hash_table, as an array. * * The returned array is %NULL-terminated but may contain %NULL as a * key. Use @length to determine the true length if it's possible that * %NULL was used as the value for a key. * * Note: in the common case of a string-keyed #GHashTable, the return * value of this function can be conveniently cast to (gchar **). * * You should always free the return result with g_free(). In the * above-mentioned case of a string-keyed hash table, it may be * appropriate to use g_strfreev() if you call g_hash_table_steal_all() * first to transfer ownership of the keys. * * Returns: (array length=length) (transfer container): a * %NULL-terminated array containing each key from the table. * * Since: 2.40 **/ gpointer * g_hash_table_get_keys_as_array_local (GHashTable *hash_table, guint *length) { gpointer *result; guint i, j = 0; result = g_new(gpointer, hash_table->nnodes + 1); for (i = 0; i < hash_table->size; i++) { if (HASH_IS_REAL (hash_table->hashes[i])) result[j++] = hash_table->keys[i]; } g_assert_cmpint (j, ==, hash_table->nnodes); result[j] = NULL; if (length) *length = j; return result; } #endif /** Converts a doubly linked list of pointers into a null-terminated array * of pointers. * * @param glist pointer to doubly linked list * @param length where to return number of items in the allocated array, * (not including the final NULL terminating entry * * @return pointer to the newly allocated gpointer array * * @remark The pointers in the linked list are copied to the newly allocated array. * The data pointed to is not duplicated. * @remark This function is needed because glib function g_hash_table_get_keys_as_array() * does not exist in glib versions less than 2.40 */ gpointer * g_list_to_g_array( GList * glist, guint * length) { int len = 0; gpointer * result = NULL; guint ndx = 0; GList * lptr; len = g_list_length(glist); result = g_new(gpointer, len+1); for (lptr = glist; lptr!=NULL; lptr=lptr->next) { result[ndx++] = lptr->data; } result[ndx] = NULL; *length = len; return result; } // GCompareFunc functions // signature: // gint // (* GCompareFunc) ( // gconstpointer a, // gconstpointer b // ) /** String comparison function with signature GCompareFunc * * @param a pointer to first string * @param b pointer to second string * @return -1, 0, +1 in the usual way * * @remark Used by g_ptr_array_sort() */ gint gaux_ptr_scomp( gconstpointer a, gconstpointer b) { char ** ap = (char **) a; char ** bp = (char **) b; // printf("(%s) ap = %p -> -> %p -> |%s|\n", __func__, ap, *ap, *ap); // printf("(%s) bp = %p -> -> %p -> |%s|\n", __func__, bp, *bp, *bp); return g_ascii_strcasecmp(*ap,*bp); } /** Integer comparison function with signature GCompareFunc */ gint gaux_ptr_intcomp( gconstpointer a, gconstpointer b) { int ia = GPOINTER_TO_INT(a); int ib = GPOINTER_TO_INT(b); gint result = 0; if (ia < ib) result = -1; else if (ia > ib) result = 1; // printf("(%s) a=%p, ia=%d, b=%p, ib=%d, returning %d\n", __func__, a, ia, b, ib, result); return result; } GPtrArray * gaux_ptr_array_truncate( GPtrArray * gpa, int limit) { assert(gpa); bool debug = false; if (debug) printf("(%s) Starting. gpa->len=%d, limit=%d\n", __func__, gpa->len, limit); if (limit > 0) { int removect = gpa->len - limit; if (removect > 0) { g_ptr_array_remove_range(gpa, limit, removect); } } else if (limit < 0) { int removect = gpa->len + limit; if (removect > 0) { g_ptr_array_remove_range(gpa, 0, removect); } } if (debug) printf("(%s) Done. gpa->len=%d\n", __func__, gpa->len); return gpa; } // Future: GPtrArray * gaux_ptr_array_append_array( GPtrArray * dest, GPtrArray * src, GAuxDupFunc dup_func) { assert(dest); if (src) { for (guint ndx = 0; ndx < src->len; ndx++) { gpointer v = g_ptr_array_index(src,ndx); if (dup_func) v = dup_func(v); g_ptr_array_add(dest, v); } } return dest; } GPtrArray * gaux_ptr_array_join( GPtrArray * gpa1, GPtrArray * gpa2, GAuxDupFunc dup_func, GDestroyNotify element_free_func) { int new_len = gpa1->len + gpa2->len; GPtrArray * dest = g_ptr_array_sized_new(new_len); if (element_free_func) g_ptr_array_set_free_func(dest,element_free_func); for (guint ndx = 0; ndx < gpa1->len; ndx++) { gpointer v = g_ptr_array_index(gpa1,ndx); if (dup_func) v = dup_func(v); g_ptr_array_add(dest, v); } for (guint ndx = 0; ndx < gpa2->len; ndx++) { gpointer v = g_ptr_array_index(gpa2,ndx); if (dup_func) v = dup_func(v); g_ptr_array_add(dest, v); } return dest; } GPtrArray * gaux_ptr_array_copy( GPtrArray * src, GAuxDupFunc dup_func, GDestroyNotify element_free_func) { GPtrArray * dest = g_ptr_array_sized_new(src->len); if (element_free_func) g_ptr_array_set_free_func(dest, element_free_func); for (guint ndx = 0; ndx < src->len; ndx++) { gpointer v = g_ptr_array_index(src,ndx); if (dup_func) v = dup_func(v); g_ptr_array_add(dest, v); } return dest; } // has signature GCopyFunc gpointer g_string_copy_func(gconstpointer src, gpointer data) { return (gpointer) g_strdup((gchar*) src); } GPtrArray * gaux_deep_copy_string_array(GPtrArray * old_array) { // g_ptr_array_copy() requires glib 2.62 //GPtrArray * result = g_ptr_array_copy(old_array, g_string_copy_func, NULL); GPtrArray * result = g_ptr_array_sized_new(old_array->len); g_ptr_array_set_free_func(result, g_free); for (int ndx = 0; ndx < old_array->len; ndx++) { g_ptr_array_add(result, g_strdup(g_ptr_array_index(old_array, ndx))); } return result; } GPtrArray * gaux_ptr_array_from_null_terminated_array( gpointer * src, GAuxDupFunc dup_func, GDestroyNotify element_free_func) { GPtrArray * result = g_ptr_array_new(); if (dup_func) g_ptr_array_set_free_func(result, element_free_func); gpointer* p = src; while (*p) { gpointer v = (dup_func) ? dup_func(*p) : *p; g_ptr_array_add(result, v); } return result; } // GEqualFunc gboolean gaux_streq(gconstpointer a, gconstpointer b) { gboolean result = streq((const char *) a, (const char *) b); // printf("(%s) a=|%s|, b=|%s|, returning %s\n", __func__, (const char * )a, (const char *) b, sbool(result)); return result; } /** Implements g_ptr_array_find_with_equal_func(), which requires glib 2.54. * */ gboolean gaux_ptr_array_find_with_equal_func( GPtrArray * haystack, gconstpointer needle, GEqualFunc equal_func, guint * index_loc) { bool result = false; if (index_loc) *index_loc = -1; if (haystack && (haystack->len > 0) && needle) { for (guint ndx = 0; ndx < haystack->len; ndx++) { if (equal_func) result = equal_func(g_ptr_array_index(haystack,ndx), needle); else result = g_ptr_array_index(haystack,ndx) == needle; if (result) { if (index_loc) *index_loc = ndx; break; } } } return result; } // // Thread utilities // /** Handles the boilerplate of obtaining a thread specific buffer that can * change size. * * If parm **bufsz_key_ptr** is NULL, the buffer is reallocated with the * specified size with each call to this function. * * If parm **bufsz_key_ptr** is non-NULL, then the buffer is reallocated * only if the requested size is larger than the current size. That is, * the buffer can grow in size but never shrink. * * \param buf_key_ptr address of a **GPrivate** used as the identifier * for the buffer * \param bufsz_key_ptr address of **GPrivate** used as an identifier for * the current buffer size * \param required_size size of buffer to allocate * \return pointer to thread specific buffer */ void * get_thread_dynamic_buffer( GPrivate * buf_key_ptr, GPrivate * bufsz_key_ptr, guint16 required_size) { // printf("(%s) buf_key_ptr=%p, bufsz_key_ptr=%p, required_size=%d\n", // __func__, buf_key_ptr, bufsz_key_ptr, required_size); char * buf = g_private_get(buf_key_ptr); int * bufsz_ptr = NULL; if (bufsz_key_ptr) bufsz_ptr = g_private_get(bufsz_key_ptr); // GThread * this_thread = g_thread_self(); // printf("(%s) this_thread=%p, buf=%p, bufsz_ptr=%p\n", __func__, this_thread, buf, bufsz_ptr); // if (bufsz_ptr) // printf("(%s) *bufsz_ptr = %d\n", __func__, *bufsz_ptr); // unnecessary if use g_private_replace() instead of g_private_set() // if (buf) // g_free(buf); if ( !bufsz_ptr || *bufsz_ptr < required_size) { buf = g_new(char, required_size); // printf("(%s) Calling g_private_set()\n", __func__); g_private_replace(buf_key_ptr, buf); if (bufsz_key_ptr) { if (!bufsz_ptr) { bufsz_ptr = g_new(int, 1); g_private_set(bufsz_key_ptr, bufsz_ptr); } *bufsz_ptr = required_size; } } // printf("(%s) Returning: %p\n", __func__, buf); return buf; } /** Handles the boilerplate of obtaining a thread specific fixed size buffer. * The first call to this function in a thread with a given key address * allocates the buffer. Subsequent calls in the thread for the same key * address return the same buffer. * * \param buf_key_ptr address of a **GPrivate** used as the identifier * for the buffer * \param buffer_size size of buffer to allocate * \return pointer to thread specific buffer * * \remark * When the buffer is first allocated, all bytes are set to 0. */ void * get_thread_fixed_buffer( GPrivate * buf_key_ptr, guint16 buffer_size) { // printf("(%s) buf_key_ptr=%p, buffer_size=%d\n", __func__, buf_key_ptr, buffer_size); assert(buffer_size > 0); char * buf = g_private_get(buf_key_ptr); // GThread * this_thread = g_thread_self(); // printf("(%s) this_thread=%p, buf=%p\n", __func__, this_thread, buf); if (!buf) { buf = g_new0(char, buffer_size); //g_new0 initializes to 0 g_private_set(buf_key_ptr, buf); } // printf("(%s) Returning: %p\n", __func__, buf); return buf; } ddcutil-2.2.0/src/util/glib_string_util.c0000644000175000001440000002040514634376340014103 /** @file glib_string_util.c * * Functions that depend on both glib_util.c and string_util.c. * * glib_string_util.c/h exists to avoid circular dependencies within directory util. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include /** \endcond */ #include "string_util.h" #include "glib_string_util.h" /** Joins a GPtrArray containing pointers to character strings * into a single string, * * @param strings GPtrArray of strings * @param sepstr if non-null, separator to insert between joined strings * @return joined string, "" if strings==NULL, caller is responsible for freeing */ char * join_string_g_ptr_array(GPtrArray* strings, char * sepstr) { bool debug = false; char * catenated = NULL; if (strings) { int ct = strings->len; if (debug) fprintf(stdout, "(%s) ct = %d\n", __func__, ct); char ** pieces = calloc(ct, sizeof(char*)); int ndx; for (ndx=0; ndx < ct; ndx++) { pieces[ndx] = g_ptr_array_index(strings,ndx); if (debug) fprintf(stdout, "(%s) pieces[%d] = %s\n", __func__, ndx, pieces[ndx]); } catenated = strjoin((const char**) pieces, ct, sepstr); if (debug) fprintf(stdout, "(%s) strlen(catenated)=%zd, catenated=%p, catenated=|%s|\n", __func__, strlen(catenated), catenated, catenated); #ifdef GLIB_VARIANT // GLIB variant failing when used with file. why? Null_Terminated_String_Array ntsa_pieces = g_ptr_array_to_ntsa(strings); if (debug) { DBGMSG("ntsa_pieces before call to g_strjoinv():"); null_terminated_string_array_show(ntsa_pieces); } // n. our Null_Terminated_String_Array is identical to glib's GStrv gchar sepchar = ';'; gchar * catenated2 = g_strjoinv(&sepchar, ntsa_pieces); DBGMSF(debug, "catenated2=%p", catenated2); *pstring = catenated2; assert(strcmp(catenated, catenated2) == 0); #endif free(pieces); } else catenated = g_strdup(""); return catenated; } /** Joins a GPtrArray containing pointers to character strings into * a single string, optionally sorting the strings before joining. * * @param strings GPtrArray of strings * @param sepstr if non-null, separator to insert between joined strings * @param sort if true, sort the strings before joining * @return joined string, "" if strings==NULL, caller is responsible for freeing */ char * join_string_g_ptr_array2( GPtrArray* strings, char * sepstr, bool sort) { char * result = NULL; if (strings) { if (sort) g_ptr_array_sort(strings, gaux_ptr_scomp); result = join_string_g_ptr_array(strings, sepstr); } else result = g_strdup(""); return result; } /** Joins a GPtrArray containing pointers to character strings * into a single string, * * The result is returned in a thread-specific private buffer that is * valid until the next call of this function in the current thread. * * @param strings GPtrArray of strings * @param sepstr if non-null, separator to insert between joined strings * @return joined string, "" if strings==NULL, do not free */ char * join_string_g_ptr_array_t(GPtrArray* strings, char * sepstr) { static GPrivate buffer_key = G_PRIVATE_INIT(g_free); static GPrivate buffer_len_key = G_PRIVATE_INIT(g_free); char * catenated = join_string_g_ptr_array(strings, sepstr); int required_size = strlen(catenated) + 1; char * buf = get_thread_dynamic_buffer(&buffer_key, &buffer_len_key, required_size); strncpy(buf, catenated, required_size); free(catenated); return buf; } /** Joins a GPtrArray containing pointers to character strings * into a single string, optionally sorting the strings before joining. * * The result is returned in a thread-specific private buffer that is * valid until the next call of this function in the current thread. * * @param strings GPtrArray of strings * @param sepstr if non-null, separator to insert between joined strings * @oaram sort if true, sort strings before joining * @return joined string, "" if strings=NULL, do not free */ char * join_string_g_ptr_array2_t(GPtrArray* strings, char * sepstr, bool sort) { static GPrivate buffer_key = G_PRIVATE_INIT(g_free); static GPrivate buffer_len_key = G_PRIVATE_INIT(g_free); char * catenated = join_string_g_ptr_array2(strings, sepstr, sort); int required_size = strlen(catenated) + 1; char * buf = get_thread_dynamic_buffer(&buffer_key, &buffer_len_key, required_size); strncpy(buf, catenated, required_size); free(catenated); return buf; } /** Looks for a string in a **GPtrArray** of strings. * * @param haystack **GPtrArray** to search * @param needle string to search for (case sensitive) * @return index of string if found, -1 if not found * * @remark * glib function **g_ptr_array_find_with_equal_funct()** is an obvious alternative, * but it requires glib version >= 2.54 */ int gaux_string_ptr_array_find(GPtrArray * haystack, const char * needle) { int result = -1; for (int ndx = 0; ndx < haystack->len; ndx++) { if (streq(needle, g_ptr_array_index(haystack, ndx))) { result = ndx; break; } } return result; } /** Compares two instances of #GPtrArray of pointers to unique strings. * * @param first first array * @param second second array * @return true if they contain the same strings, false if not * * @remark * The string values are compared, not the pointers. * @remark * Order of the strings does not matter. */ bool gaux_unique_string_ptr_arrays_equal(GPtrArray *first, GPtrArray* second) { assert(first); assert(second); bool result = false; // assumes each entry in first and second is unique if (first->len == second->len) { result = true; for (int ndx = 0; ndx < first->len; ndx++) { guint found_index; gpointer cur = g_ptr_array_index(first, ndx); bool found = gaux_ptr_array_find_with_equal_func(second, cur, g_str_equal, &found_index); if (!found) { result = false; break; } } } return result; } /** Creates a new #GPtrArray of unique strings containing only those in the * first array that are not in the second. * * @param first first array * @param second second array * @result new array containing the difference * * @remark * The returned array may have length 0. */ GPtrArray * gaux_unique_string_ptr_arrays_minus(GPtrArray *first, GPtrArray* second) { assert(first); assert(second); // to consider: only allocate result if there's actually a difference GPtrArray * result = g_ptr_array_new_with_free_func(g_free); guint found_index; for (int ndx = 0; ndx < first->len; ndx++) { gpointer cur = g_ptr_array_index(first, ndx); // g_ptr_array_find_with_equal_func() requires glib 2.54 // instead use our own implementation bool found = gaux_ptr_array_find_with_equal_func(second, cur, g_str_equal, &found_index); if (!found) { g_ptr_array_add(result, g_strdup(cur)); } } return result; } /** Appends a copy of a string to a #GPtrArray of unique strings. * If the new value already exists in the array, does nothing. * * \param arry array of unique strings * \param new_value string to include, must be non-null */ void gaux_unique_string_ptr_array_include(GPtrArray * arry, char * new_value) { bool debug = false; if (debug) printf("(%s) new_value=|%s|\n", __func__, new_value); assert(new_value); assert(arry); if (new_value) { // ignore bad argument if asserts disabled int ndx = 0; for (; ndx < arry->len; ndx++) { char * old_value = g_ptr_array_index(arry, ndx); if (streq(new_value, old_value) ) { if (debug) printf("(%s) Found. ndx=%d\n", __func__, ndx); break; } } if (ndx == arry->len) { if (debug) printf("(%s) Appending new value\n", __func__); g_ptr_array_add(arry, g_strdup(new_value)); } } } ddcutil-2.2.0/src/util/i2c_util.c0000644000175000001440000001660414711020305012242 /** @file i2c_util.c * * I2C utility functions */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" #ifdef TARGET_BSD #include "bsd/i2c-dev.h" #include "bsd/i2c.h" #else #include #include #endif #include #include #include #include #include #include #include "coredefs_base.h" #include "data_structures.h" #include "file_util.h" #include "report_util.h" #include "string_util.h" #include "sysfs_filter_functions.h" #include "i2c_util.h" /** Converts a string of the form "i2c-N" to a number. * * \param name string to convert * \return extracted number, -1 if conversion fails */ int i2c_name_to_busno(const char * name) { int result = -1; if (name && str_starts_with(name, I2C"-")) { int ival; if (name[4] != '-' && str_to_int(name+4, &ival, 10) ) result = ival; } return result; } /** Converts a string of the form "xxx-N" to a number. * * \param name string to convert * \return extracted number, -1 if conversion fails * * \remark A generalization of #i2c_name_to_busno() */ int extract_number_after_hyphen(const char * name) { int result = -1; if (name) { char * hyphen = strchr(name, '-'); if (hyphen && *(hyphen+1) != '\0') { int ival; if ( str_to_int(hyphen+1, &ival, 10) ) result = ival; } } return result; } /** Compare strings i2c-X by bus number, handling unusual case where "X" is * a string other than a number. Non-numeric values sort before numeric * values. * * This is a qsort type comparison function. The arguments are pointers * to pointers to strings, not pointers to strings. * * Arguments are of type gconstpointer so that the function signature * matches GCompareFunc. * * \param v1 pointer to pointer to first string to compare * \param v2 pointer to pointer to second string to compare * \return -1 if v1 sorts before v2, * 0 v1 equals v2 * 1 v1 sorts after v2 */ gint i2c_compare(gconstpointer v1, gconstpointer v2) { bool debug = false; int result = 0; char * s1 = (v1) ? *(char**)v1 : NULL; char * s2 = (v2) ? *(char**)v2 : NULL; if (debug) printf("(%s) s1=%p->%s, s2=%p->%s\n", __func__, s1, s1, s2, s2); // do something "reasonable" for pathological cases if (!s1 && s2) result = -1; else if (!s1 && !s2) result = 0; else if (s1 && !s2) result = 1; else { // normal case // int i1 = i2c_name_to_busno(s1); // int i2 = i2c_name_to_busno(s2); int i1 = extract_number_after_hyphen(s1); int i2 = extract_number_after_hyphen(s2); if (i1 < 0 && i2 < 0) result = strcmp(s1, s2); else if (i1 < i2) result = -1; else if (i1 == i2) result = 0; else result = 1; } if (debug) printf("(%s) Returning: %d\n", __func__, result); return result; } // // Functionality flags // // Table for interpreting functionality flags. Value_Name_Table functionality_flag_table = { VN(I2C_FUNC_I2C ), //0x00000001 VN(I2C_FUNC_10BIT_ADDR ), //0x00000002 VN(I2C_FUNC_PROTOCOL_MANGLING ), //0x00000004 /* I2C_M_IGNORE_NAK etc. */ VN(I2C_FUNC_SMBUS_PEC ), //0x00000008 // VN(I2C_FUNC_NOSTART ), //0x00000010 /* I2C_M_NOSTART */ // i2c-tools 4.0 // VN(I2C_FUNC_SLAVE ), //0x00000020 // i2c-tools 4.0 {0x00000010, "I2C_FUNC_NOSTART", NULL }, {0x00000020, "I2C_FUNC_SLAVE", NULL }, VN(I2C_FUNC_SMBUS_BLOCK_PROC_CALL ), //0x00008000 /* SMBus 2.0 */ VN(I2C_FUNC_SMBUS_QUICK ), //0x00010000 VN(I2C_FUNC_SMBUS_READ_BYTE ), //0x00020000 VN(I2C_FUNC_SMBUS_WRITE_BYTE ), //0x00040000 VN(I2C_FUNC_SMBUS_READ_BYTE_DATA ), //0x00080000 VN(I2C_FUNC_SMBUS_WRITE_BYTE_DATA ), //0x00100000 VN(I2C_FUNC_SMBUS_READ_WORD_DATA ), //0x00200000 VN(I2C_FUNC_SMBUS_WRITE_WORD_DATA ), //0x00400000 VN(I2C_FUNC_SMBUS_PROC_CALL ), //0x00800000 VN(I2C_FUNC_SMBUS_READ_BLOCK_DATA ), //0x01000000 VN(I2C_FUNC_SMBUS_WRITE_BLOCK_DATA ), //0x02000000 VN(I2C_FUNC_SMBUS_READ_I2C_BLOCK ), //0x04000000 /* I2C-like block xfer */ VN(I2C_FUNC_SMBUS_WRITE_I2C_BLOCK ), //0x08000000 /* w/ 1-byte reg. addr. */ // VN(I2C_FUNC_SMBUS_HOST_NOTIFY ), //0x10000000 // i2c-tools 4.0 {0x10000000, "I2C_FUNC_SMBUS_HOST_NOTIFY", NULL}, VN_END }; /** Gets the I2C functionality flags for an open I2C bus, * specified by its file descriptor. * * @param fd Linux file descriptor * @return functionality flags */ unsigned long i2c_get_functionality_flags_by_fd(int fd) { unsigned long funcs; int rc = ioctl(fd, I2C_FUNCS, &funcs); if (rc < 0) { // should be impossible fprintf(stderr, "(%s) Error in ioctl(I2C_FUNCS), errno=%d\n", __func__, errno); funcs = 0; } // printf("(%s) Functionality for file descriptor %d: %lu, 0x%0lx\n", __func__, fd, funcs, funcs); return funcs; } /** Returns a string representation of functionality flags. * * @param functionality long int of flags * @return string representation of flags */ char * i2c_interpret_functionality_flags(unsigned long functionality) { return vnt_interpret_flags(functionality, functionality_flag_table, false, ", "); } /** Reports functionality flags. * * The output is multiline. * * @param functionality flags to report * @param maxline maximum length of 1 line * @param depth logical indentation depth */ void i2c_report_functionality_flags(long functionality, int maxline, int depth) { char * buf0 = i2c_interpret_functionality_flags(functionality); char * header = "Functionality: "; int hdrlen = strlen(header); int maxpiece = maxline - ( rpt_get_indent(depth) + hdrlen); Null_Terminated_String_Array ntsa = strsplit_maxlength( buf0, maxpiece, " "); int ntsa_ndx = 0; while (true) { char * s = ntsa[ntsa_ndx++]; if (!s) break; rpt_vstring(depth, "%-*s%s", hdrlen, header, s); if (strlen(header) > 0) header = ""; } free(buf0); ntsa_free(ntsa, /* free_strings */ true); } typedef struct { bool found; } Boolean_Accumulator; static void set_true( const char * dirname, const char * fn, void * accumulator, int depth) { Boolean_Accumulator * accum = (Boolean_Accumulator*) accumulator; if (depth >= 0) rpt_vstring(depth, "dirname=%s, fn=%s", dirname, fn); accum->found = true; } /** Checks if any /dev/i2c devices exist. * * @return true/false * * If at least one device exists, we know that driver dev-i2c is built into the kernel or has been loaded. */ bool dev_i2c_devices_exist() { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); Boolean_Accumulator accumulator = {false}; dir_foreach("/dev", predicate_i2c_N, // Dir_Filter_Func, set_true, // Dir_Foreach_Func, &accumulator, (debug) ? 1 : -1); if (debug) printf("(%s) Returning: %s", __func__, SBOOL(accumulator.found)); return accumulator.found; } ddcutil-2.2.0/src/util/linux_util.c0000644000175000001440000002617414754153540012746 /** @file linux_util.c * * Miscellaneous Linux utilities */ // Copyright (C) 2020-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include "config.h" /** \cond */ #include #include #include #include #include #include #include #include #include #include #ifdef TARGET_BSD #include #else #include #include #include #endif /** \endcond */ #include "debug_util.h" #include "file_util.h" #include "report_util.h" #include "string_util.h" #include "subprocess_util.h" #include "linux_util.h" /** Tests whether a file is readable by trying to read from it, as opposed to * considering all the rules re permissions, file type, links, etc. * * \param filename * \return true if file can be read from false if not */ bool is_readable_file(const char * filename) { // avoid all the rules re permissions, file type, links, ls etc // just try to read from the file bool result = false; int fd = open(filename, O_RDONLY); if (fd > 0) { char buf; if (read(fd, &buf, 1) > 0) result = true; close(fd); } return result; } /** Gets the value of a kernel configuration parameter from file * /boot/config-KERNEL_RELEASE", where KERNEL_RELEASE is the kernel release name. * * \param parm_name parameter name * \param buffer buffer in which to return value * \param bufsz size of buffer * \param 1 configuration parm found, value is in buffer * \retval 0 configuration parm not found * \retval < 0 error reading configuration file */ int get_kernel_config_parm(const char * parm_name, char * buffer, int bufsz) { bool debug = false; if (debug) printf("(%s) Staring. parm_name=%s, buffer=%p, bufsz=%d\n", __func__, parm_name, buffer, bufsz); buffer[0] = '\0'; struct utsname utsbuf; int rc = uname(&utsbuf); assert(rc == 0); char config_fn[100]; snprintf(config_fn, 100, "/boot/config-%s", utsbuf.release); char search_str[40]; snprintf(search_str, 40, "%s=", parm_name); if (debug) printf("(%s) search_str=|%s|, len=%ld\n", __func__, search_str, (unsigned long) strlen(search_str)); GPtrArray * lines = g_ptr_array_new_full(15000, g_free); char * terms[2]; terms[0] = search_str; terms[1] = NULL; int unfiltered_ct = read_file_with_filter(lines, config_fn, terms, false, 0, true); if (debug) printf("(%s) read_file_with_filter() returned %d, lines->len=%d\n", __func__, unfiltered_ct, lines->len); if (unfiltered_ct < 0) { rc = unfiltered_ct; // -errno } else if (lines->len == 0) { // count after filtering rc = 0; } else { assert(lines->len == 1); char * aline = g_ptr_array_index(lines, 0); char * value = aline + strlen(search_str); if (debug) printf("(%s) strlen(search_str)=%ld aline=%p->|%s|, value=%p->|%s|\n", __func__, (unsigned long)strlen(search_str), aline, aline, value, value); assert(strlen(value) < bufsz); // snprintf(buffer, bufsz, "%s", value); strcpy(buffer, value); rc = 1; } g_ptr_array_free(lines, true); if (debug) printf("(%s) rc=%d, strlen(buffer) = %ld, buffer=|%s|\n", __func__, rc, (unsigned long) strlen(buffer), buffer); ASSERT_IFF(rc==1, strlen(buffer) > 0); if (debug) printf("(%s) Done. parm=%s, returning %d, result=%s\n", __func__, parm_name, rc, buffer); return rc; } /** Checks whether a module file exists for the current kernel. * * Name variants using underscores (_) and hyphens (-) are both checked. * * Allows for extension .ko.xz etc. as well as .ko. * * @param module_name name of module * @retval true file exists * @retval false file does not exist */ bool find_module_ko(const char * module_name) { bool debug = false; if (debug) printf("(%s) Starting. module_name: %s\n", __func__, module_name); struct utsname utsbuf; int rc = uname(&utsbuf); assert(rc == 0); char * module_name1 = strdup(module_name); char * module_name2 = strdup(module_name); str_replace_char(module_name1, '-','_'); str_replace_char(module_name2, '_','-'); bool result = false; char cmd[200]; g_snprintf(cmd, 200, "find /lib/modules/%s -name \"%s.ko*\" -o -name \"%s.ko*\"", utsbuf.release, module_name1, module_name2); if (debug) printf("(%s) cmd |%s|\n", __func__, cmd); GPtrArray * cmd_result = execute_shell_cmd_collect(cmd); if (cmd_result) { if (debug) printf("(%s) len=%d\n", __func__, cmd_result->len); if (cmd_result->len > 0) { if (debug) printf("(%s) Found: %s\n", __func__, (char*) g_ptr_array_index(cmd_result,0)); result = true; } g_ptr_array_free(cmd_result,true); } free(module_name1); free(module_name2); if (debug) printf("(%s) Done. Returning %s\n", __func__, sbool(result)); return result; } /** Examines file /lib/modules//modules/builtin to determine * whether a module is built into the kernel. * * Name variants using underscores (_) and hyphens (-) are both checked. * * Allows for extension .ko.xz etc. as well as .ko. * * @param module_name name of module * @retval true module is built in * @retval false module is not built in, or modules/builtin file not found * * @remark * It is possible that modules/builtin does not exist for some incorrectly * built kernel. */ bool is_module_built_in(const char * module_name) { bool debug = false; if (debug) printf("(%s) Starting. module_name = |%s|\n", __func__, module_name); // Look for name variants with either "-" or "_" char * module_name1 = g_strdup_printf("%s.ko", module_name); char * module_name2 = g_strdup_printf("%s.ko", module_name); str_replace_char(module_name1, '-','_'); str_replace_char(module_name2, '_','-'); struct utsname utsbuf; int rc = uname(&utsbuf); assert(rc == 0); char builtin_fn[PATH_MAX]; g_snprintf(builtin_fn, PATH_MAX, "/lib/modules/%s/modules.builtin", utsbuf.release); bool found = false; #ifdef ALT if ( !regular_file_exists(builtin_fn) ) { fprintf(stderr, "File not found: %s\n", builtin_fn); } else { char cmd[200]; // not everything is under kernel/drivers e.g. fbdev.ko is under kernel/arch/x86/video g_snprintf(cmd, 200, "grep -e \"^kernel/.*/%s\" -e \"^kernel/.*/%s\" %s ", module_name1, module_name2, builtin_fn); // allow for .ko.xz etc. if (debug) printf("(%s) cmd |%s|\n", __func__, cmd); GPtrArray * cmd_result = execute_shell_cmd_collect(cmd); if (cmd_result) { if (debug) printf("(%s) len=%d\n", __func__, cmd_result->len); if (cmd_result->len > 0) { found = true; } g_ptr_array_free(cmd_result,true); } } #else GPtrArray * lines = g_ptr_array_new_full(400, g_free); char * terms[3]; terms[0] = module_name1; terms[1] = module_name2; // probably same as module_name1, but not worth optimizing terms[2] = NULL; int unfiltered_ct = read_file_with_filter(lines, builtin_fn, terms, false, 0, false); if (unfiltered_ct < 0) { // = -errno fprintf(stderr, "Error reading file %s: %s\n", builtin_fn, strerror(errno)); fprintf(stderr, "Assuming module %s is not built in to kernel\n", module_name); } else { found = (lines->len == 1); } g_ptr_array_free(lines, true); #endif free(module_name1); free(module_name2); if (debug) printf("(%s) Done. module_name=%s, Returning %s\n", __func__, module_name, sbool(found)); return found; } char * kernel_module_types[] = { "KERNEL_MODULE_NOT_FOUND", // 0 "KERNEL_MODULE_BUILTIN", // 1 "KERNEL_MODULE_LOADABLE_FILE"}; // 2 int module_status_by_modules_builtin_or_existence(const char * module_name) { bool debug = false; int result = KERNEL_MODULE_NOT_FOUND; if ( is_module_built_in(module_name) ) result = KERNEL_MODULE_BUILTIN; else { bool found = find_module_ko(module_name); if (found) { result = KERNEL_MODULE_LOADABLE_FILE; } } if (debug) printf("(%s) Executed. module_name=%s, returning %d = %s\n", __func__, module_name, result, kernel_module_types[result]); return result; } /** Examines file /boot/config- to determine whether module * i2c-dev exists and if so whether it is built into the kernel or is a * loadable module. * * @retval y built into kernel * @retval m built as loadable module * @retval n not built * @retval X /boot/config file not found, or CONFIG_I2C_CHARDEV line not found */ char i2c_dev_status_by_boot_config_file() { struct utsname utsbuf; int rc = uname(&utsbuf); assert(rc == 0); char config_fn[PATH_MAX]; g_snprintf(config_fn, PATH_MAX, "/boot/config-%s", utsbuf.release); char status = 'X'; if ( !regular_file_exists(config_fn) ) { fprintf(stderr, "Kernel configuration file not found: %s\n", config_fn); } else { char cmd[100]; g_snprintf(cmd, 100, "grep CONFIG_I2C_CHARDEV= /boot/config-%s", utsbuf.release); int pos = strlen("CONFIG_I2C_CHARDEV="); char * cmd_result = execute_shell_cmd_one_line_result(cmd); if (!cmd_result) { fprintf(stderr, "CONFIG_I2C_CHARDEV not found in %s\n", config_fn); } else { status = cmd_result[pos]; free(cmd_result); } } return status; } /** Gets the id number of the current thread * * \return thread number */ intmax_t get_thread_id() { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); #ifdef TARGET_BSD int tid = pthread_getthreadid_np(); #else pid_t tid = syscall(SYS_gettid); #endif if (debug) printf("(%s) Done. Returning %jd\n", __func__, (intmax_t) tid); return tid; } /** Gets the id number of the current process * * \return process number */ intmax_t get_process_id() { pid_t pid = syscall(SYS_getpid); return pid; } /** Checks that a thread or process id is valid. * * @param id thread or process id * @return true if valid, false if not */ bool is_valid_thread_or_process(pid_t id) { bool debug = false; struct stat buf; char procfn[20]; snprintf(procfn, 20, "/proc/%d", id); int rc = stat(procfn, &buf); bool result = (rc == 0); DBGF(debug, "File: %s, returning %s\n", procfn, sbool(result)); if (!result) DBG("!!! Returning: %s", sbool(result)); return result; } void rpt_lsof(const char * fqfn, int depth) { // rpt_vstring(depth, "Programs with %s open:"); char cmd[PATH_MAX+20]; g_snprintf(cmd, PATH_MAX+20, "lsof %s", fqfn); execute_shell_cmd_rpt(cmd, depth); } // to do: tailor the output to what is useful GPtrArray* rpt_lsof_collect(const char * fqfn) { char cmd[PATH_MAX+20]; g_snprintf(cmd, PATH_MAX+20, "lsof %s", fqfn); return execute_shell_cmd_collect(cmd); } ddcutil-2.2.0/src/util/msg_util.c0000644000175000001440000000662314754153540012372 /** @file msg_util.c * * Creates standardized prefix (time, thread, etc.) for messages, * and maintains a stack of the names of traced functions. */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include "common_inlines.h" #include "common_printf_formats.h" #include "glib_util.h" #include "timestamp.h" #include "traced_function_stack.h" #include "msg_util.h" bool dbgtrc_show_time = false; ///< include elapsed time in debug/trace output bool dbgtrc_show_wall_time = false; ///< include wall time in debug/trace output bool dbgtrc_show_thread_id = false; ///< include thread id in debug/trace output bool dbgtrc_show_process_id = false; ///< include process id in debug/trace output bool dbgtrc_trace_to_syslog_only = false; ///< send trace output only to system log bool stdout_stderr_redirected = false; bool __thread msg_decoration_suspended = false; /** Creates a message prefix. Depending on settings and destination this * prefix may include: * - process id * - thread id * - wall time * - elapsed time since program start * - function name * * @param buf buffer in which to return string * @param bufsz buffer size * @param dest_syslog message destination is the system log */ char * get_msg_decoration(char * buf, uint bufsz, bool dest_syslog) { bool debug = false; assert(bufsz >= 100); if (msg_decoration_suspended) { buf[0] = '\0'; } else { char elapsed_prefix[20] = ""; char walltime_prefix[20] = ""; char thread_prefix[15] = ""; char process_prefix[15] = ""; char funcname_prefix[80] = ""; if (dbgtrc_show_time) g_snprintf(elapsed_prefix, 20, "[%s]", formatted_elapsed_time_t(4)); if (dbgtrc_show_wall_time && !dest_syslog) g_snprintf(walltime_prefix, 20, "[%s]", formatted_wall_time()); if (dbgtrc_show_thread_id || dest_syslog) g_snprintf(thread_prefix, 15, PRItid, (intmax_t) tid()); if (dbgtrc_show_process_id) g_snprintf(thread_prefix, 15, PRItid, (intmax_t) pid()); if (traced_function_stack_enabled) { char * s = peek_traced_function(); if (s) g_snprintf(funcname_prefix, 80, "(%-30s)", s); } g_snprintf(buf, bufsz, "%s%s%s%s%s", process_prefix, thread_prefix, walltime_prefix, elapsed_prefix, funcname_prefix); if (strlen(buf) > 0) strcat(buf, " "); } if (debug) // can't use DBGF(), causes call to get_msg_decoration() printf("tid=%d, buf=%p->|%s|\n", tid(), buf, buf); return buf; } /** Returns the wall time as a formatted string. * * The string is built in a thread specific private buffer. The returned * string is valid until the next call of this function in the same thread. * * @return formatted wall time */ char * formatted_wall_time() { static GPrivate formatted_wall_time_key = G_PRIVATE_INIT(g_free); char * time_buf = get_thread_fixed_buffer(&formatted_wall_time_key, 40); time_t epoch_seconds = time(NULL); struct tm broken_down_time; localtime_r(&epoch_seconds, &broken_down_time); strftime(time_buf, 40, "%b %d %T", &broken_down_time); // printf("(%s) |%s|\n", __func__, time_buf); return time_buf; } ddcutil-2.2.0/src/util/multi_level_map.c0000644000175000001440000002307614572333721013725 /* multi_level_map.c * * * Copyright (C) 2015-2023 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ /** @file multi_level_map.c * Multi_Level_Map data structure */ /** \cond */ #include #include #include #include #include #include #include #include /** \endcond */ #include "report_util.h" #include "multi_level_map.h" // // Data structure creation // /** Creates a new **Multi_Level_Map instance. * * @param table_name name of table * @param levels number of levels * @param level_detail pointer to array if **MLM_Level** descriptors */ Multi_Level_Map * mlm_create(char * table_name, int levels, MLM_Level* level_detail) { // printf("(%s) level_detail=%p\n", __func__, level_detail); // for (int lvlndx=0; lvlndx < levels; lvlndx++) { // report_mlm_level(level_detail+lvlndx, 1); // } Multi_Level_Map * mlm = calloc(1, sizeof(Multi_Level_Map) + levels * sizeof(MLM_Level)); mlm->table_name = g_strdup(table_name); mlm->levels = levels; // MLM_Level* lvldesc = level_detail; int initial_size = level_detail[0].initial_size; // printf("(%s) initial_size=%d\n", __func__, initial_size); mlm->root = g_ptr_array_sized_new(initial_size); memcpy((Byte*) &mlm->level_detail, level_detail, levels*sizeof(MLM_Level)); // report_multi_level_table(mlm,0); return mlm; } /** Adds a node to a **Multi_Level_Map**. * * @param map pointer to **Multi_Level_Map** table * @param parent pointer to parent node * if NULL, this node is a child of the root * @param key key of node * @param value value of node */ MLM_Node * mlm_add_node(Multi_Level_Map * map, MLM_Node * parent, guint key, char * value) { // printf("(%s) parent=%p, key=0x%04x, value=|%s|\n", __func__, parent, key, value); MLM_Node * new_node = calloc(1,sizeof(MLM_Node)); new_node->code = key; new_node->name = value; new_node->children = NULL; if (!parent) { new_node->level = 0; g_ptr_array_add(map->root, new_node); } else { new_node->level = parent->level+1; if (!parent->children) { int initial_size = map->level_detail[parent->level].initial_size; parent->children = g_ptr_array_sized_new(initial_size); } g_ptr_array_add(parent->children, new_node); } map->level_detail[new_node->level].total_entries += 1; return new_node; } // // Debug data structure // /** Reports on a **Multi_Level_Map** level descriptor. * @param level_desc pointer to level descriptor * @param depth logical indentation depth */ void report_mlm_level(MLM_Level * level_desc, int depth) { int d1 = depth+1; rpt_structure_loc("MLM_Level", level_desc, depth); rpt_str("name", NULL, level_desc->name, d1); rpt_int("initial_size", NULL, level_desc->initial_size, d1); rpt_int("total_entries", NULL, level_desc->total_entries, d1); } // Debugging function void mlm_cur_entries(Multi_Level_Map * mlt) { int d1 = 1; rpt_vstring(0, "Multi_Level_Table. levels=%d", mlt->levels); for (int ndx=0; ndx < mlt->levels; ndx++) { rpt_vstring(d1, " mlt->level_detail[%d].cur_entry=%p, addr of entry=%p", ndx, mlt->level_detail[ndx].cur_entry, &mlt->level_detail[ndx].cur_entry); } } static void report_mlm_node( Multi_Level_Map * header, int level, MLM_Node * entry, int depth) { // MLM_Level level_detail = header->level_detail[level]; rpt_vstring(depth, "%04x %s", entry->code, entry->name); if (entry->children) { for (int ndx=0; ndxchildren->len; ndx++) { report_mlm_node( header, level+1, g_ptr_array_index(entry->children, ndx), depth+1); } } } /** Reports the contents of a **Multi_Level_Map**. * * @param header pointer to MLM instance * @param depth logical indentation depth */ void report_multi_level_map(Multi_Level_Map * header, int depth) { int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("Multi_Level_Table", header, depth); rpt_vstring(d1, "%-20s: %s", "Table", header->table_name); rpt_vstring(d1, "%-20s: %s", "Segment tag", header->segment_tag); rpt_int("Number of level 0 entries:", NULL, header->root->len, d1); for (int ndx=0; ndx < header->root->len; ndx++) { report_mlm_node( header, 0, g_ptr_array_index(header->root, ndx), d2); } } // // Data structure query // static MLM_Node * mlm_find_child(GPtrArray * nodelist, guint id) { bool debug = false; if (debug) printf("(%s) Starting, id=0x%08x\n", __func__, id); MLM_Node * result = NULL; for (int ndx = 0; ndx < nodelist->len; ndx++) { MLM_Node * cur_entry = g_ptr_array_index(nodelist, ndx); if (debug) printf("(%s) Comparing code=0x%04x, name=%s\n", __func__, cur_entry->code, cur_entry->name); if (cur_entry->code == id) { result = cur_entry; break; } } if (debug) printf("(%s) Returning %p\n", __func__, (void*)result); return result; } static void report_multi_level_names(Multi_Level_Names * mln, int depth) { int d1 = depth+1; rpt_structure_loc("Multi_Level_Names", mln, depth); rpt_int("levels", NULL, mln->levels, d1); for (int ndx = 0; ndx < mln->levels; ndx++) { rpt_str("names", NULL, mln->names[ndx], d1); } } /** Gets the names associated with the levels of a **Multi_Level_Map** path. * * @param mlm pointer to **Multi_Level_Map** table * @param levelct number of ids * @param ids pointer to array of **levelct** node ids * * @return pointer to **Multi_Level_Names** struct containing the * names for the ids at each level */ Multi_Level_Names mlm_get_names2(Multi_Level_Map * mlm, int levelct, guint* ids) { bool debug = false; assert(levelct >= 1 && levelct <= MLT_MAX_LEVELS); // pciusb_id_ensure_initialized(); // <== WHAT TO DO? if (debug) { printf("(%s) levelct=%d\n", __func__, levelct); for (int ndx = 0; ndx < levelct; ndx++) { printf(" ids[%d] = 0x%08x\n", ndx, ids[ndx]); } } Multi_Level_Names result = {0}; int argndx = 0; GPtrArray * children = mlm->root; result.levels = 0; while (argndx < levelct) { // printf("(%s) argndx=%d\n", __func__, argndx); if (!children) break; MLM_Node * level_entry = mlm_find_child(children, ids[argndx]); if (!level_entry) { break; } result.levels = argndx+1; result.names[argndx] = level_entry->name; children = level_entry->children; argndx++; } if (debug) { printf("(%s) Returning: \n", __func__); report_multi_level_names(&result, 1); } return result; } /** Variant of **mlm_get_names2()** that uses a variable argument list for * the level ids. * * @param table pointer to **Multi_Level_Map** table * @param argct number of ids * @param .. node ids, of type guint * * @return pointer to **Multi_Level_Names** struct containing the * names for the ids at each level */ Multi_Level_Names mlm_get_names(Multi_Level_Map * table, int argct, ...) { // bool debug = false; assert(argct >= 1 && argct <= MLT_MAX_LEVELS); // pciusb_id_ensure_initialized(); // <== WHAT TO DO? guint args[MLT_MAX_LEVELS]; va_list ap; int ndx; va_start(ap, argct); for (ndx=0; ndx= 1 && argct <= MLT_MAX_LEVELS); // pciusb_id_ensure_initialized(); // <== WHAT TO DO? Multi_Level_Names result = {0}; uint args[MLT_MAX_LEVELS]; va_list ap; int ndx; va_start(ap, argct); for (ndx=0; ndxroot; while (argndx < argct) { assert(children); MLM_Node * level_entry = mlm_find_child(children, args[argndx]); if (!level_entry) { result.levels = 0; // indicates not found break; } result.levels = argndx+1; result.names[argndx] = level_entry->name; children = level_entry->children; argndx++; } if (debug) { printf("(%s) Returning: \n", __func__); report_multi_level_names(&result, 1); } return result; } #endif ddcutil-2.2.0/src/util/pnp_ids.c0000644000175000001440000023450114441414365012177 /** \file pnp_ids.c * * Provides a lookup table of 3 character Plug and Play manufacturer codes, * which are used, e.g. in EDIDs. * * The list, originally created by Microsoft, is now maintained at the UEFI * web site. * * \TODO * Instead of the list hard coded here, consider using file * /usr/share/hwdata/pnp.ids from package hwdata, or a flat file extracted * from the UEFI web site. */ // Copyright (C) 2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include /** \endcond */ #include "coredefs_base.h" #include "string_util.h" #include "pnp_ids.h" typedef struct { char* mfg_code; char* mfg_name; } Pnp_Id_Table_Entry; Pnp_Id_Table_Entry pnp_id_table[] = { {"AAA","Avolites Ltd"}, {"AAE","Anatek Electronics Inc."}, {"AAT","Ann Arbor Technologies"}, {"ABA","ABBAHOME INC."}, {"ABC","AboCom System Inc"}, {"ABD","Allen Bradley Company"}, {"ABE","Alcatel Bell"}, {"ABO","D-Link Systems Inc"}, {"ABT","Anchor Bay Technologies, Inc."}, {"ABV","Advanced Research Technology"}, {"ACA","Ariel Corporation"}, {"ACB","Aculab Ltd"}, {"ACC","Accton Technology Corporation"}, {"ACD","AWETA BV"}, {"ACE","Actek Engineering Pty Ltd"}, {"ACG","A&R Cambridge Ltd"}, {"ACH","Archtek Telecom Corporation"}, {"ACI","Ancor Communications Inc"}, {"ACK","Acksys"}, {"ACL","Apricot Computers"}, {"ACM","Acroloop Motion Control Systems Inc"}, {"ACO","Allion Computer Inc."}, {"ACP","Aspen Tech Inc"}, {"ACR","Acer Technologies"}, {"ACS","Altos Computer Systems"}, {"ACT","Applied Creative Technology"}, {"ACU","Acculogic"}, {"ACV","ActivCard S.A"}, {"ADA","Addi-Data GmbH"}, {"ADB","Aldebbaron"}, {"ADC","Acnhor Datacomm"}, {"ADD","Advanced Peripheral Devices Inc"}, {"ADE","Arithmos, Inc."}, {"ADH","Aerodata Holdings Ltd"}, {"ADI","ADI Systems Inc"}, {"ADK","Adtek System Science Company Ltd"}, {"ADL","ASTRA Security Products Ltd"}, {"ADM","Ad Lib MultiMedia Inc"}, {"ADN","Analog & Digital Devices Tel. Inc"}, {"ADP","Adaptec Inc"}, {"ADR","Nasa Ames Research Center"}, {"ADS","Analog Devices Inc"}, {"ADT","Adtek"}, {"ADT","Aved Display Technologies"}, {"ADV","Advanced Micro Devices Inc"}, {"ADX","Adax Inc"}, {"AEC","Antex Electronics Corporation"}, {"AED","Advanced Electronic Designs, Inc."}, {"AEI","Actiontec Electric Inc"}, {"AEJ","Alpha Electronics Company"}, {"AEM","ASEM S.p.A."}, {"AEN","Avencall"}, {"AEP","Aetas Peripheral International"}, {"AET","Aethra Telecomunicazioni S.r.l."}, {"AFA","Alfa Inc"}, {"AGC","Beijing Aerospace Golden Card Electronic Engineering Co.,Ltd."}, {"AGI","Artish Graphics Inc"}, {"AGL","Argolis"}, {"AGM","Advan Int'l Corporation"}, {"AGT","Agilent Technologies"}, {"AHC","Advantech Co., Ltd."}, {"AIC","Arnos Insturments & Computer Systems"}, {"AIE","Altmann Industrieelektronik"}, {"AII","Amptron International Inc."}, {"AIL","Altos India Ltd"}, {"AIM","AIMS Lab Inc"}, {"AIR","Advanced Integ. Research Inc"}, {"AIS","Alien Internet Services"}, {"AIW","Aiwa Company Ltd"}, {"AIX","ALTINEX, INC."}, {"AJA","AJA Video Systems, Inc."}, {"AKB","Akebia Ltd"}, {"AKE","AKAMI Electric Co.,Ltd"}, {"AKI","AKIA Corporation"}, {"AKL","AMiT Ltd"}, {"AKM","Asahi Kasei Microsystems Company Ltd"}, {"AKP","Atom Komplex Prylad"}, {"AKY","Askey Computer Corporation"}, {"ALA","Alacron Inc"}, {"ALC","Altec Corporation"}, {"ALD","In4S Inc"}, {"ALG","Realtek Semiconductor Corp."}, {"ALH","AL Systems"}, {"ALI","Acer Labs"}, {"ALJ","Altec Lansing"}, {"ALK","Acrolink Inc"}, {"ALL","Alliance Semiconductor Corporation"}, {"ALM","Acutec Ltd."}, {"ALN","Alana Technologies"}, {"ALO","Algolith Inc."}, {"ALP","Alps Electric Company Ltd"}, {"ALR","Advanced Logic"}, {"ALS","Avance Logic Inc"}, {"ALS","Texas Advanced optoelectronics Solutions, Inc"}, {"ALT","Altra"}, {"ALV","AlphaView LCD"}, {"ALX","ALEXON Co.,Ltd."}, {"AMA","Asia Microelectronic Development Inc"}, {"AMB","Ambient Technologies, Inc."}, {"AMC","Attachmate Corporation"}, {"AMD","Amdek Corporation"}, {"AMI","American Megatrends Inc"}, {"AML","Anderson Multimedia Communications {HK} Limited"}, {"AMN","Amimon LTD."}, {"AMO","Amino Technologies PLC and Amino Communications Limited"}, {"AMP","AMP Inc"}, {"AMS ","ARMSTEL, Inc."}, {"AMT","AMT International Industry"}, {"AMX","AMX LLC"}, {"ANA","Anakron"}, {"ANC","Ancot"}, {"AND","Adtran Inc"}, {"ANI","Anigma Inc"}, {"ANK","Anko Electronic Company Ltd"}, {"ANL","Analogix Semiconductor, Inc"}, {"ANO","Anorad Corporation"}, {"ANP","Andrew Network Production"}, {"ANR","ANR Ltd"}, {"ANS","Ansel Communication Company"}, {"ANT","Ace CAD Enterprise Company Ltd"}, {"ANX","Acer Netxus Inc"}, {"AOA","AOpen Inc."}, {"AOE","Advanced Optics Electronics, Inc."}, {"AOL","America OnLine"}, {"AOT","Alcatel"}, {"APC","American Power Conversion"}, {"APD","AppliAdata"}, {"APE","Alpine Electronics, Inc."}, {"APG","Horner Electric Inc"}, {"API","A Plus Info Corporation"}, {"APL","Aplicom Oy"}, {"APM","Applied Memory Tech"}, {"APN","Appian Tech Inc"}, {"APP","Apple Computer Inc"}, {"APR","Aprilia s.p.a."}, {"APS","Autologic Inc"}, {"APT","Audio Processing Technology Ltd"}, {"APV","A+V Link "}, {"APX","AP Designs Ltd"}, {"ARC","Alta Research Corporation"}, {"ARE","ICET S.p.A."}, {"ARG","Argus Electronics Co., LTD"}, {"ARI","Argosy Research Inc"}, {"ARK","Ark Logic Inc"}, {"ARL","Arlotto Comnet Inc"}, {"ARM","Arima"}, {"ARO","Poso International B.V."}, {"ARS","Arescom Inc"}, {"ART","Corion Industrial Corporation"}, {"ASC","Ascom Strategic Technology Unit"}, {"ASD","USC Information Sciences Institute"}, {"ASE","AseV Display Labs"}, {"ASI","Ahead Systems"}, {"ASK","Ask A/S"}, {"ASL","AccuScene Corporation Ltd"}, {"ASM","ASEM S.p.A."}, {"ASN","Asante Tech Inc"}, {"ASP","ASP Microelectronics Ltd"}, {"AST","AST Research Inc"}, {"ASU","Asuscom Network Inc"}, {"ASX","AudioScience"}, {"ASY","Rockwell Collins / Airshow Systems"}, {"ATA","Allied Telesyn International {Asia} Pte Ltd"}, {"ATC","Ably-Tech Corporation"}, {"ATD","Alpha Telecom Inc"}, {"ATE","Innovate Ltd"}, {"ATH","Athena Informatica S.R.L."}, {"ATI","Allied Telesis KK"}, {"ATK","Allied Telesyn Int'l"}, {"ATL","Arcus Technology Ltd"}, {"ATM","ATM Ltd"}, {"ATN","Athena Smartcard Solutions Ltd."}, {"ATO","ASTRO DESIGN, INC."}, {"ATP","Alpha-Top Corporation"}, {"ATT","AT&T"}, {"ATV","Office Depot, Inc."}, {"ATX","Athenix Corporation"}, {"AUI","Alps Electric Inc"}, {"AUR","Aureal Semiconductor"}, {"AUT","Autotime Corporation"}, {"AVA","Avaya Communication"}, {"AVC","Auravision Corporation"}, {"AVD","Avid Electronics Corporation"}, {"AVE","Add Value Enterpises {Asia} Pte Ltd"}, {"AVI","Nippon Avionics Co.,Ltd"}, {"AVL","Avalue Technology Inc."}, {"AVM","AVM GmbH"}, {"AVN ","Advance Computer Corporation"}, {"AVO","Avocent Corporation"}, {"AVR","AVer Information Inc."}, {"AVT","Avtek {Electronics} Pty Ltd"}, {"AVV","SBS Technologies {Canada}, Inc. {was Avvida Systems, Inc.}"}, {"AVX","A/Vaux Electronics"}, {"AVX","AVerMedia Technologies, Inc."}, {"AWC","Access Works Comm Inc"}, {"AWL","Aironet Wireless Communications, Inc"}, {"AWS","Wave Systems"}, {"AXB","Adrienne Electronics Corporation"}, {"AXC","AXIOMTEK CO., LTD."}, {"AXE","D-Link Systems Inc"}, {"AXI","American Magnetics"}, {"AXL","Axel"}, {"AXO","Axonic Labs LLC"}, {"AXP","American Express"}, {"AXT","Axtend Technologies Inc"}, {"AXX","Axxon Computer Corporation"}, {"AXY","AXYZ Automation Services, Inc"}, {"AYD","Aydin Displays"}, {"AYR","Airlib, Inc"}, {"AZM","AZ Middelheim - Radiotherapy"}, {"AZT","Aztech Systems Ltd"}, {"BAC","Biometric Access Corporation"}, {"BAN","Banyan"}, {"BBB","an-najah university"}, {"BBH","B&Bh"}, {"BBL","Brain Boxes Limited"}, {"BCC","Beaver Computer Corporaton"}, {"BCD","Barco GmbH"}, {"BCM","Broadcom"}, {"BCQ","Deutsche Telekom Berkom GmbH"}, {"BCS","Booria CAD/CAM systems"}, {"BDO","Brahler ICS"}, {"BDR","Blonder Tongue Labs, Inc."}, {"BDS","Barco Display Systems"}, {"BEC","Elektro Beckhoff GmbH"}, {"BEI","Beckworth Enterprises Inc"}, {"BEK","Beko Elektronik A.S."}, {"BEL","Beltronic Industrieelektronik GmbH"}, {"BEO","Baug & Olufsen"}, {"BFE","B.F. Engineering Corporation"}, {"BGB","Barco Graphics N.V"}, {"BGT","Budzetron Inc"}, {"BHZ","BitHeadz, Inc."}, {"BIC","Big Island Communications"}, {"BII","Boeckeler Instruments Inc"}, {"BIL","Billion Electric Company Ltd"}, {"BIO","BioLink Technologies International, Inc."}, {"BIT","Bit 3 Computer"}, {"BLI","Busicom"}, {"BLN","BioLink Technologies"}, {"BLP","Bloomberg L.P."}, {"BMD","Blackmagic Design"}, {"BMI","Benson Medical Instruments Company"}, {"BML","BIOMED Lab"}, {"BMS","BIOMEDISYS"}, {"BNE","Bull AB"}, {"BNK","Banksia Tech Pty Ltd"}, {"BNO","Bang & Olufsen"}, {"BNS","Boulder Nonlinear Systems"}, {"BOB","Rainy Orchard"}, {"BOE","BOE"}, {"BOI","NINGBO BOIGLE DIGITAL TECHNOLOGY CO.,LTD"}, {"BOS","BOS"}, {"BPD","Micro Solutions, Inc."}, {"BPU","Best Power"}, {"BRA","Braemac Pty Ltd"}, {"BRC","BARC"}, {"BRG","Bridge Information Co., Ltd"}, {"BRI","Boca Research Inc"}, {"BRM","Braemar Inc"}, {"BRO","BROTHER INDUSTRIES,LTD."}, {"BSE","Bose Corporation"}, {"BSL","Biomedical Systems Laboratory"}, {"BSN","BRIGHTSIGN, LLC"}, {"BST","BodySound Technologies, Inc."}, {"BTC","Bit 3 Computer"}, {"BTE","Brilliant Technology"}, {"BTF","Bitfield Oy"}, {"BTI","BusTech Inc"}, {"BTO","BioTao Ltd"}, {"BUF","Yasuhiko Shirai Melco Inc"}, {"BUG","B.U.G., Inc."}, {"BUJ","ATI Tech Inc"}, {"BUL","Bull"}, {"BUR","Bernecker & Rainer Ind-Eletronik GmbH"}, {"BUS","BusTek"}, {"BUT","21ST CENTURY ENTERTAINMENT"}, {"BWK","Bitworks Inc."}, {"BXE","Buxco Electronics"}, {"BYD","byd:sign corporation"}, {"CAA","Castles Automation Co., Ltd"}, {"CAC","CA & F Elettronica"}, {"CAG","CalComp"}, {"CAI","Canon Inc."}, {"CAL","Acon"}, {"CAM","Cambridge Audio"}, {"CAN","Canopus Company Ltd"}, {"CAN","Carrera Computer Inc"}, {"CAN","CORNEA"}, {"CAR","Cardinal Company Ltd"}, {"CAS","CASIO COMPUTER CO.,LTD"}, {"CAT","Consultancy in Advanced Technology"}, {"CAV","Cavium Networks, Inc"}, {"CBI","ComputerBoards Inc"}, {"CBR","Cebra Tech A/S"}, {"CBT","Cabletime Ltd"}, {"CBX","Cybex Computer Products Corporation"}, {"CCC","C-Cube Microsystems"}, {"CCI","Cache"}, {"CCJ","CONTEC CO.,LTD."}, {"CCL","CCL/ITRI"}, {"CCP","Capetronic USA Inc"}, {"CDC","Core Dynamics Corporation"}, {"CDD","Convergent Data Devices"}, {"CDE","Colin.de"}, {"CDG","Christie Digital Systems Inc"}, {"CDI","Concept Development Inc"}, {"CDK","Cray Communications"}, {"CDN","Codenoll Technical Corporation"}, {"CDP","CalComp"}, {"CDS","Computer Diagnostic Systems"}, {"CDT","IBM Corporation"}, {"CDV","Convergent Design Inc."}, {"CEA","Consumer Electronics Association"}, {"CEC","Chicony Electronics Company Ltd"}, {"CED","Cambridge Electronic Design Ltd"}, {"CEF","Cefar Digital Vision"}, {"CEI","Crestron Electronics, Inc."}, {"CEM","MEC Electronics GmbH"}, {"CEN","Centurion Technologies P/L"}, {"CEP","C-DAC"}, {"CER","Ceronix"}, {"CET","TEC CORPORATION"}, {"CFG","Atlantis"}, {"CGA","Chunghwa Picture Tubes, LTD"}, {"CGS","Chyron Corp"}, {"CGT","congatec AG"}, {"CHA","Chase Research PLC"}, {"CHC","Chic Technology Corp."}, {"CHD","ChangHong Electric Co.,Ltd"}, {"CHE","Acer Inc"}, {"CHG","Sichuan Changhong Electric CO, LTD."}, {"CHI","Chrontel Inc"}, {"CHL","Chloride-R&D"}, {"CHM","CHIC TECHNOLOGY CORP."}, {"CHO","Sichuang Changhong Corporation"}, {"CHP","CH Products"}, {"CHS","Agentur Chairos"}, {"CHT","Chunghwa Picture Tubes,LTD."}, {"CHY","Cherry GmbH"}, {"CIC","Comm. Intelligence Corporation"}, {"CII","Cromack Industries Inc"}, {"CIL","Citicom Infotech Private Limited"}, {"CIN","Citron GmbH"}, {"CIP","Ciprico Inc"}, {"CIR","Cirrus Logic Inc"}, {"CIS","Cisco Systems Inc"}, {"CIT","Citifax Limited"}, {"CKC","The Concept Keyboard Company Ltd"}, {"CKJ","Carina System Co., Ltd."}, {"CLA","Clarion Company Ltd"}, {"CLD","COMMAT L.t.d."}, {"CLE","Classe Audio"}, {"CLG","CoreLogic"}, {"CLI","Cirrus Logic Inc"}, {"CLM","CrystaLake Multimedia"}, {"CLO","Clone Computers"}, {"CLT","automated computer control systems"}, {"CLV","Clevo Company"}, {"CLX","CardLogix"}, {"CMC","CMC Ltd"}, {"CMD","Colorado MicroDisplay, Inc."}, {"CMG","Chenming Mold Ind. Corp."}, {"CMI","C-Media Electronics"}, {"CMM","Comtime GmbH"}, {"CMN","Chimei Innolux Corporation"}, {"CMO","Chi Mei Optoelectronics corp."}, {"CMR","Cambridge Research Systems Ltd"}, {"CMS","CompuMaster Srl"}, {"CMX","Comex Electronics AB"}, {"CNB","American Power Conversion"}, {"CNC","Alvedon Computers Ltd"}, {"CNE","Cine-tal"}, {"CNI","Connect Int'l A/S"}, {"CNN","Canon Inc"}, {"CNT","COINT Multimedia Systems"}, {"COB","COBY Electronics Co., Ltd"}, {"COD","CODAN Pty. Ltd."}, {"COI","Codec Inc."}, {"COL","Rockwell Collins, Inc."}, {"COM","Comtrol Corporation"}, {"CON","Contec Company Ltd"}, {"COO","coolux GmbH "}, {"COR","Corollary Inc"}, {"COS","CoStar Corporation"}, {"COT","Core Technology Inc"}, {"COW","Polycow Productions"}, {"COX","Comrex"}, {"CPC","Ciprico Inc"}, {"CPD","CompuAdd"}, {"CPI","Computer Peripherals Inc"}, {"CPL","Compal Electronics Inc"}, {"CPM","Capella Microsystems Inc."}, {"CPQ","Compaq Computer Company"}, {"CPT","cPATH"}, {"CPX","Powermatic Data Systems"}, {"CRC","CONRAC GmbH"}, {"CRD","Cardinal Technical Inc"}, {"CRE","Creative Labs Inc"}, {"CRI","Crio Inc."}, {"CRL","Creative Logic "}, {"CRN","Cornerstone Imaging"}, {"CRO","Extraordinary Technologies PTY Limited"}, {"CRQ","Cirque Corporation"}, {"CRS","Crescendo Communication Inc"}, {"CRV","Cerevo Inc."}, {"CRX","Cyrix Corporation"}, {"CSB","Transtex SA"}, {"CSC","Crystal Semiconductor"}, {"CSD","Cresta Systems Inc"}, {"CSE","Concept Solutions & Engineering"}, {"CSI","Cabletron System Inc"}, {"CSM","Cosmic Engineering Inc."}, {"CSO","California Institute of Technology"}, {"CSS","CSS Laboratories"}, {"CST","CSTI Inc"}, {"CTA","CoSystems Inc"}, {"CTC","CTC Communication Development Company Ltd"}, {"CTE","Chunghwa Telecom Co., Ltd."}, {"CTL","Creative Technology Ltd"}, {"CTM","Computerm Corporation"}, {"CTN","Computone Products"}, {"CTP","Computer Technology Corporation"}, {"CTS","Comtec Systems Co., Ltd."}, {"CTX","Creatix Polymedia GmbH"}, {"CUB","Cubix Corporation"}, {"CUK","Calibre UK Ltd"}, {"CVA","Covia Inc."}, {"CVI","Colorado Video, Inc."}, {"CVS","Clarity Visual Systems"}, {"CWR","Connectware Inc"}, {"CXT","Conexant Systems"}, {"CYB","CyberVision"}, {"CYC","Cylink Corporation"}, {"CYD","Cyclades Corporation"}, {"CYL","Cyberlabs"}, {"CYT","Cytechinfo Inc"}, {"CYV","Cyviz AS"}, {"CYW","Cyberware"}, {"CYX","Cyrix Corporation"}, {"CZE","Carl Zeiss AG"}, {"DAC","Digital Acoustics Corporation"}, {"DAE","Digatron Industrie Elektronik GmbH"}, {"DAI","DAIS SET Ltd."}, {"DAK","Daktronics"}, {"DAL","Digital Audio Labs Inc"}, {"DAN","Danelec Marine A/S"}, {"DAS","DAVIS AS"}, {"DAT","Datel Inc"}, {"DAU","Daou Tech Inc"}, {"DAV","Davicom Semiconductor Inc"}, {"DAW","DA2 Technologies Inc"}, {"DAX","Data Apex Ltd"}, {"DBD","Diebold Inc."}, {"DBI","DigiBoard Inc"}, {"DBK","Databook Inc"}, {"DBL","Doble Engineering Company"}, {"DBN","DB Networks Inc"}, {"DCA","Digital Communications Association"}, {"DCC","Dale Computer Corporation"}, {"DCD","Datacast LLC"}, {"DCE","dSPACE GmbH"}, {"DCI","Concepts Inc"}, {"DCL","Dynamic Controls Ltd"}, {"DCM","DCM Data Products"}, {"DCO","Dialogue Technology Corporation"}, {"DCR","Decros Ltd"}, {"DCS","Diamond Computer Systems Inc"}, {"DCT","Dancall Telecom A/S"}, {"DCV","Datatronics Technology Inc"}, {"DDA","DA2 Technologies Corporation"}, {"DDD","Danka Data Devices"}, {"DDE","Datasat Digital Entertainment"}, {"DDI","Data Display AG"}, {"DDS","Barco, n.v."}, {"DDT","Datadesk Technologies Inc"}, {"DDV","Delta Information Systems, Inc"}, {"DEC","Digital Equipment Corporation"}, {"DEI","Deico Electronics"}, {"DEL","Dell Inc."}, {"DEN","Densitron Computers Ltd"}, {"DEX","idex displays"}, {"DFI","DFI"}, {"DFK","SharkTec A/S"}, {"DFT","DEI Holdings dba Definitive Technology"}, {"DGA","Digiital Arts Inc"}, {"DGC","Data General Corporation"}, {"DGI","DIGI International"}, {"DGK","DugoTech Co., LTD"}, {"DGP","Digicorp European sales S.A."}, {"DGS","Diagsoft Inc"}, {"DGT","Dearborn Group Technology"}, {"DGT","The Dearborn Group"}, {"DHP","DH Print"}, {"DHQ","Quadram"}, {"DHT","Projectavision Inc"}, {"DIA","Diadem"}, {"DIG","Digicom S.p.A."}, {"DII","Dataq Instruments Inc"}, {"DIM","dPict Imaging, Inc."}, {"DIN","Daintelecom Co., Ltd"}, {"DIS","Diseda S.A."}, {"DIT","Dragon Information Technology"}, {"DJE","Capstone Visua lProduct Development "}, {"DJP","Maygay Machines, Ltd"}, {"DKY","Datakey Inc"}, {"DLB","Dolby Laboratories Inc. "}, {"DLC","Diamond Lane Comm. Corporation"}, {"DLG","Digital-Logic GmbH"}, {"DLK","D-Link Systems Inc"}, {"DLL","Dell Inc"}, {"DLT","Digitelec Informatique Park Cadera"}, {"DMB","Digicom Systems Inc"}, {"DMC","Dune Microsystems Corporation"}, {"DMM","Dimond Multimedia Systems Inc"}, {"DMP","D&M Holdings Inc, Professional Business Company"}, {"DMS","DOME imaging systems"}, {"DMT","Distributed Management Task Force, Inc. {DMTF} "}, {"DMV","NDS Ltd"}, {"DNA","DNA Enterprises, Inc."}, {"DNG","Apache Micro Peripherals Inc"}, {"DNI","Deterministic Networks Inc."}, {"DNT","Dr. Neuhous Telekommunikation GmbH"}, {"DNV","DiCon"}, {"DOL","Dolman Technologies Group Inc"}, {"DOM","Dome Imaging Systems"}, {"DON","DENON, Ltd."}, {"DOT","Dotronic Mikroelektronik GmbH"}, {"DPA","DigiTalk Pro AV"}, {"DPC","Delta Electronics Inc"}, {"DPI","DocuPoint"}, {"DPL","Digital Projection Limited"}, {"DPM","ADPM Synthesis sas"}, {"DPS","Digital Processing Systems"}, {"DPT","DPT"}, {"DPX","DpiX, Inc."}, {"DQB","Datacube Inc"}, {"DRB","Dr. Bott KG"}, {"DRC","Data Ray Corp."}, {"DRD","DIGITAL REFLECTION INC."}, {"DRI","Data Race Inc"}, {"DRS","DRS Defense Solutions, LLC"}, {"DSD","DS Multimedia Pte Ltd"}, {"DSI","Digitan Systems Inc"}, {"DSM","DSM Digital Services GmbH"}, {"DSP","Domain Technology Inc"}, {"DTA","DELTATEC "}, {"DTC","DTC Tech Corporation"}, {"DTE","Dimension Technologies, Inc."}, {"DTI","Diversified Technology, Inc."}, {"DTK","Dynax Electronics {HK} Ltd"}, {"DTL","e-Net Inc"}, {"DTN","Datang Telephone Co"}, {"DTO","Deutsche Thomson OHG"}, {"DTT","Design & Test Technology, Inc."}, {"DTX","Data Translation"}, {"DUA","Dosch & Amand GmbH & Company KG"}, {"DUN","NCR Corporation"}, {"DVD","Dictaphone Corporation"}, {"DVL","Devolo AG"}, {"DVS","Digital Video System"}, {"DVT","Data Video"}, {"DWE","Daewoo Electronics Company Ltd"}, {"DXC","Digipronix Control Systems"}, {"DXD","DECIMATOR DESIGN PTY LTD"}, {"DXL","Dextera Labs Inc"}, {"DXP","Data Expert Corporation"}, {"DXS","Signet"}, {"DYC","Dycam Inc"}, {"DYM","Dymo-CoStar Corporation"}, {"DYN","Askey Computer Corporation"}, {"DYX","Dynax Electronics {HK} Ltd"}, {"EAS","Evans and Sutherland Computer"}, {"EBH","Data Price Informatica"}, {"EBT","HUALONG TECHNOLOGY CO., LTD"}, {"ECA","Electro Cam Corp."}, {"ECC","ESSential Comm. Corporation"}, {"ECI","Enciris Technologies"}, {"ECK","Eugene Chukhlomin Sole Proprietorship, d.b.a. "}, {"ECL","Excel Company Ltd"}, {"ECM","E-Cmos Tech Corporation"}, {"ECO","Echo Speech Corporation"}, {"ECP","Elecom Company Ltd"}, {"ECS","Elitegroup Computer Systems Company Ltd"}, {"ECT","Enciris Technologies "}, {"EDC","e.Digital Corporation"}, {"EDG","Electronic-Design GmbH"}, {"EDI","Edimax Tech. Company Ltd"}, {"EDM","EDMI"}, {"EDT","Emerging Display Technologies Corp"}, {"EEE","ET&T Technology Company Ltd"}, {"EEH","EEH Datalink GmbH"}, {"EEP","E.E.P.D. GmbH"}, {"EES","EE Solutions, Inc."}, {"EGA","Elgato Systems LLC"}, {"EGD","EIZO GmbH Display Technologies "}, {"EGL","Eagle Technology"}, {"EGN","Egenera, Inc."}, {"EGO","Ergo Electronics"}, {"EHJ","Epson Research"}, {"EHN","Enhansoft"}, {"EIC","Eicon Technology Corporation"}, {"EKA","MagTek Inc."}, {"EKC","Eastman Kodak Company"}, {"EKS","EKSEN YAZILIM"}, {"ELA","ELAD srl"}, {"ELC","Electro Scientific Ind"}, {"ELE","Elecom Company Ltd"}, {"ELG","Elmeg GmbH Kommunikationstechnik"}, {"ELI","Edsun Laboratories"}, {"ELL","Electrosonic Ltd"}, {"ELM","Elmic Systems Inc"}, {"ELO","Elo TouchSystems Inc"}, {"ELO","Tyco Electronics"}, {"ELS","ELSA GmbH"}, {"ELT","Element Labs, Inc."}, {"ELX","Elonex PLC"}, {"EMB","Embedded computing inc ltd"}, {"EMC","eMicro Corporation"}, {"EME","EMiNE TECHNOLOGY COMPANY, LTD."}, {"EMG","EMG Consultants Inc"}, {"EMI","Ex Machina Inc"}, {"EMK","Emcore Corporation"}, {"EMO","ELMO COMPANY, LIMITED"}, {"EMU","Emulex Corporation"}, {"ENC","Eizo Nanao Corporation"}, {"END","ENIDAN Technologies Ltd"}, {"ENE","ENE Technology Inc."}, {"ENI","Efficient Networks"}, {"ENS","Ensoniq Corporation"}, {"ENT","Enterprise Comm. & Computing Inc"}, {"EPC","Empac"}, {"EPH ","Epiphan Systems Inc. "}, {"EPI","Envision Peripherals, Inc"}, {"EPN","EPiCON Inc."}, {"EPS","KEPS"}, {"EQP","Equipe Electronics Ltd."}, {"EQX","Equinox Systems Inc"}, {"ERG","Ergo System"}, {"ERI","Ericsson Mobile Communications AB"}, {"ERN","Ericsson, Inc."}, {"ERP","Euraplan GmbH"}, {"ERT","Escort Insturments Corporation"}, {"ESA","Elbit Systems of America"}, {"ESC","Eden Sistemas de Computacao S/A"}, {"ESD","Ensemble Designs, Inc"}, {"ESG","ELCON Systemtechnik GmbH"}, {"ESI","Extended Systems, Inc."}, {"ESK","ES&S"}, {"ESL","Esterline Technologies"}, {"ESN","eSATURNUS"}, {"ESS","ESS Technology Inc"}, {"EST","Embedded Solution Technology"}, {"ESY","E-Systems Inc"}, {"ETC","Everton Technology Company Ltd"}, {"ETD","ELAN MICROELECTRONICS CORPORATION"}, {"ETH","Etherboot Project"}, {"ETI","Eclipse Tech Inc"}, {"ETK","eTEK Labs Inc."}, {"ETL","Evertz Microsystems Ltd."}, {"ETS","Electronic Trade Solutions Ltd"}, {"ETT","E-Tech Inc"}, {"EUT","Ericsson Mobile Networks B.V."}, {"EVE ","Advanced Micro Peripherals Ltd"}, {"EVI","eviateg GmbH"}, {"EVX","Everex"}, {"EXA","Exabyte"}, {"EXC","Excession Audio"}, {"EXI","Exide Electronics"}, {"EXN","RGB Systems, Inc. dba Extron Electronics"}, {"EXP","Data Export Corporation"}, {"EXT","Exatech Computadores & Servicos Ltda"}, {"EXX","Exxact GmbH"}, {"EXY","Exterity Ltd"}, {"EYE","eyevis GmbH"}, {"EZE","EzE Technologies"}, {"EZP","Storm Technology"}, {"FAR","Farallon Computing"}, {"FBI","Interface Corporation"}, {"FCB","Furukawa Electric Company Ltd"}, {"FCG","First International Computer Ltd"}, {"FCS","Focus Enhancements, Inc."}, {"FDC","Future Domain"}, {"FDT","Fujitsu Display Technologies Corp."}, {"FEC","FURUNO ELECTRIC CO., LTD."}, {"FEL","Fellowes & Questec"}, {"FEN","Fen Systems Ltd."}, {"FER","Ferranti Int'L"}, {"FFC","FUJIFILM Corporation"}, {"FFI","Fairfield Industries"}, {"FGD","Lisa Draexlmaier GmbH"}, {"FGL","Fujitsu General Limited."}, {"FHL","FHLP"}, {"FIC","Formosa Industrial Computing Inc"}, {"FIL","Forefront Int'l Ltd"}, {"FIN","Finecom Co., Ltd."}, {"FIR","Chaplet Systems Inc"}, {"FIS","FLY-IT Simulators"}, {"FIT","Feature Integration Technology Inc."}, {"FJC","Fujitsu Takamisawa Component Limited"}, {"FJS","Fujitsu Spain"}, {"FJT","F.J. Tieman BV"}, {"FLE","ADTI Media, Inc"}, {"FLI","Faroudja Laboratories"}, {"FLY","Butterfly Communications"}, {"FMA","Fast Multimedia AG"}, {"FMC","Ford Microelectronics Inc"}, {"FMI","Fellowes, Inc."}, {"FMI","Fujitsu Microelect Inc"}, {"FML","Fujitsu Microelect Ltd"}, {"FMZ","Formoza-Altair"}, {"FNC","Fanuc LTD"}, {"FNI","Funai Electric Co., Ltd."}, {"FOA","FOR-A Company Limited"}, {"FOS","Foss Tecator"}, {"FOX","HON HAI PRECISON IND.CO.,LTD."}, {"FPE","Fujitsu Peripherals Ltd"}, {"FPS","Deltec Corporation"}, {"FPX","Cirel Systemes"}, {"FRC","Force Computers"}, {"FRD","Freedom Scientific BLV"}, {"FRE","Forvus Research Inc"}, {"FRI","Fibernet Research Inc"}, {"FRO","FARO Technologies"}, {"FRS","South Mountain Technologies, LTD"}, {"FSC","Future Systems Consulting KK"}, {"FSI","Fore Systems Inc"}, {"FST","Modesto PC Inc"}, {"FTC","Futuretouch Corporation"}, {"FTE","Frontline Test Equipment Inc."}, {"FTG","FTG Data Systems"}, {"FTI","FastPoint Technologies, Inc."}, {"FTL","FUJITSU TEN LIMITED"}, {"FTN","Fountain Technologies Inc"}, {"FTR","Mediasonic"}, {"FTW","MindTribe Product Engineering, Inc."}, {"FUJ","Fujitsu Ltd"}, {"FUN","sisel muhendislik"}, {"FUS","Fujitsu Siemens Computers GmbH"}, {"FVC","First Virtual Corporation"}, {"FVX","C-C-C Group Plc"}, {"FWA","Attero Tech, LLC"}, {"FWR","Flat Connections Inc"}, {"FXX","Fuji Xerox"}, {"FZC","Founder Group Shenzhen Co."}, {"FZI","FZI Forschungszentrum Informatik"}, {"GAG","Gage Applied Sciences Inc"}, {"GAL","Galil Motion Control"}, {"GAU","Gaudi Co., Ltd."}, {"GCC","GCC Technologies Inc"}, {"GCI","Gateway Comm. Inc"}, {"GCS","Grey Cell Systems Ltd"}, {"GDC","General Datacom"}, {"GDI","G. Diehl ISDN GmbH"}, {"GDS","GDS"}, {"GDT","Vortex Computersysteme GmbH"}, {"GED","General Dynamics C4 Systems"}, {"GEF","GE Fanuc Embedded Systems"}, {"GEH","GE Intelligent Platforms - Huntsville "}, {"GEM","Gem Plus"}, {"GEN","Genesys ATE Inc"}, {"GEO","GEO Sense"}, {"GER","GERMANEERS GmbH"}, {"GES","GES Singapore Pte Ltd"}, {"GET","Getac Technology Corporation"}, {"GFM","GFMesstechnik GmbH"}, {"GFN","Gefen Inc."}, {"GGL","Google Inc."}, {"GIC","General Inst. Corporation"}, {"GIM","Guillemont International"}, {"GIP","GI Provision Ltd"}, {"GIS","AT&T Global Info Solutions"}, {"GJN","Grand Junction Networks"}, {"GLD","Goldmund - Digital Audio SA"}, {"GLE","AD electronics"}, {"GLM","Genesys Logic"}, {"GLS","Gadget Labs LLC"}, {"GMK","GMK Electronic Design GmbH"}, {"GML","General Information Systems"}, {"GMM","GMM Research Inc"}, {"GMN","GEMINI 2000 Ltd"}, {"GMX","GMX Inc"}, {"GND","Gennum Corporation"}, {"GNN","GN Nettest Inc"}, {"GNZ","Gunze Ltd"}, {"GRA","Graphica Computer"}, {"GRE","GOLD RAIN ENTERPRISES CORP."}, {"GRH","Granch Ltd"}, {"GRM","Garmin International"}, {"GRV","Advanced Gravis"}, {"GRY","Robert Gray Company"}, {"GSB","NIPPONDENCHI CO,.LTD"}, {"GSC","General Standards Corporation"}, {"GSM","Goldstar Company Ltd (LG)"}, {"GST","Graphic SystemTechnology"}, {"GSY","Grossenbacher Systeme AG"}, {"GTC","Graphtec Corporation"}, {"GTI","Goldtouch"}, {"GTK","G-Tech Corporation"}, {"GTM","Garnet System Company Ltd"}, {"GTS","Geotest Marvin Test Systems Inc"}, {"GTT","General Touch Technology Co., Ltd."}, {"GUD","Guntermann & Drunck GmbH"}, {"GUZ","Guzik Technical Enterprises"}, {"GVC","GVC Corporation"}, {"GVL","Global Village Communication"}, {"GWI","GW Instruments"}, {"GWY","Gateway 2000"}, {"GZE","GUNZE Limited"}, {"HAE","Haider electronics"}, {"HAI","Haivision Systems Inc."}, {"HAL","Halberthal"}, {"HAN","Hanchang System Corporation"}, {"HAR","Harris Corporation"}, {"HAY","Hayes Microcomputer Products Inc"}, {"HCA","DAT"}, {"HCE","Hitachi Consumer Electronics Co., Ltd"}, {"HCL","HCL America Inc"}, {"HCM","HCL Peripherals"}, {"HCP","Hitachi Computer Products Inc"}, {"HCW","Hauppauge Computer Works Inc"}, {"HDC","HardCom Elektronik & Datateknik"}, {"HDI","HD-INFO d.o.o."}, {"HDV","Holografika kft."}, {"HEC","Hisense Electric Co., Ltd."}, {"HEC","Hitachi Engineering Company Ltd"}, {"HEL","Hitachi Micro Systems Europe Ltd"}, {"HER","Ascom Business Systems"}, {"HET","HETEC Datensysteme GmbH"}, {"HHC","HIRAKAWA HEWTECH CORP. "}, {"HHI","Fraunhofer Heinrich-Hertz-Institute"}, {"HIB","Hibino Corporation"}, {"HIC","Hitachi Information Technology Co., Ltd."}, {"HIK","Hikom Co., Ltd."}, {"HIL","Hilevel Technology"}, {"HIQ","Kaohsiung Opto Electronics Americas, Inc."}, {"HIT","Hitachi America Ltd"}, {"HJI","Harris & Jeffries Inc"}, {"HKA","HONKO MFG. CO., LTD."}, {"HKG","Josef Heim KG"}, {"HMC","Hualon Microelectric Corporation"}, {"HMK","hmk Daten-System-Technik BmbH"}, {"HMX","HUMAX Co., Ltd."}, {"HNS","Hughes Network Systems"}, {"HOB","HOB Electronic GmbH"}, {"HOE","Hosiden Corporation"}, {"HOL","Holoeye Photonics AG"}, {"HON","Sonitronix"}, {"HPA","Zytor Communications"}, {"HPC","Hewlett Packard Co."}, {"HPD","Hewlett Packard"}, {"HPI","Headplay, Inc."}, {"HPK","HAMAMATSU PHOTONICS K.K."}, {"HPQ","HP"}, {"HPR","H.P.R. Electronics GmbH"}, {"HRC","Hercules"}, {"HRE","Qingdao Haier Electronics Co., Ltd."}, {"HRI","Hall Research"}, {"HRL","Herolab GmbH"}, {"HRS","Harris Semiconductor"}, {"HRT","HERCULES"}, {"HSC","Hagiwara Sys-Com Company Ltd"}, {"HSD","HannStar Display Corp"}, {"HSM","AT&T Microelectronics"}, {"HSP","HannStar Display Corp"}, {"HTC","Hitachi Ltd"}, {"HTI","Hampshire Company, Inc."}, {"HTK","Holtek Microelectronics Inc"}, {"HTX","Hitex Systementwicklung GmbH"}, {"HUB","GAI-Tronics, A Hubbell Company"}, {"HUM","IMP Electronics Ltd."}, {"HWA","Harris Canada Inc"}, {"HWC","DBA Hans Wedemeyer"}, {"HWD","Highwater Designs Ltd"}, {"HWP","Hewlett Packard"}, {"HXM","Hexium Ltd."}, {"HYC","Hypercope Gmbh Aachen"}, {"HYD","Hydis Technologies.Co.,LTD"}, {"HYO","HYC CO., LTD."}, {"HYP","Hyphen Ltd"}, {"HYR","Hypertec Pty Ltd"}, {"HYT","Heng Yu Technology {HK} Limited"}, {"HYV","Hynix Semiconductor"}, {"IAF","Institut f r angewandte Funksystemtechnik GmbH"}, {"IAI","Integration Associates, Inc."}, {"IAT","IAT Germany GmbH"}, {"IBC","Integrated Business Systems"}, {"IBI","INBINE.CO.LTD"}, {"IBM","IBM Brasil"}, {"IBM","IBM France"}, {"IBP","IBP Instruments GmbH"}, {"IBR","IBR GmbH"}, {"ICA","ICA Inc"}, {"ICC","BICC Data Networks Ltd"}, {"ICD","ICD Inc"}, {"ICE","IC Ensemble"}, {"ICI","Infotek Communication Inc"}, {"ICM","Intracom SA"}, {"ICN","Sanyo Icon"}, {"ICO","Intel Corp"}, {"ICP","ICP Electronics, Inc./iEi Technology Corp."}, {"ICS","Integrated Circuit Systems"}, {"ICV","Inside Contactless"}, {"ICX","ICCC A/S"}, {"IDC","International Datacasting Corporation"}, {"IDE","IDE Associates"}, {"IDK","IDK Corporation"}, {"IDN","Idneo Technologies"}, {"IDO","IDEO Product Development"}, {"IDP","Integrated Device Technology, Inc."}, {"IDS","Interdigital Sistemas de Informacao"}, {"IDT","International Display Technology"}, {"IDX","IDEXX Labs"}, {"IEC","Interlace Engineering Corporation"}, {"IEE","IEE"}, {"IEI","Interlink Electronics"}, {"IFS","In Focus Systems Inc"}, {"IFT","Informtech"}, {"IFX","Infineon Technologies AG"}, {"IFZ","Infinite Z"}, {"IGC","Intergate Pty Ltd"}, {"IGM","IGM Communi"}, {"IHE","InHand Electronics"}, {"IIC","ISIC Innoscan Industrial Computers A/S"}, {"III","Intelligent Instrumentation"}, {"IIN","IINFRA Co., Ltd"}, {"IKS","Ikos Systems Inc"}, {"ILC","Image Logic Corporation"}, {"ILS","Innotech Corporation"}, {"IMA","Imagraph"}, {"IMB","ART s.r.l."}, {"IMC","IMC Networks"}, {"IMD","ImasDe Canarias S.A."}, {"IME","Imagraph"}, {"IMG","IMAGENICS Co., Ltd."}, {"IMI","International Microsystems Inc"}, {"IMM","Immersion Corporation"}, {"IMN","Impossible Production"}, {"IMP","Impinj"}, {"IMP","Impression Products Incorporated"}, {"IMT","Inmax Technology Corporation"}, {"INC","Home Row Inc"}, {"IND","ILC"}, {"INE","Inventec Electronics {M} Sdn. Bhd."}, {"INF","Inframetrics Inc"}, {"ING","Integraph Corporation"}, {"INI","Initio Corporation"}, {"INK","Indtek Co., Ltd."}, {"INL","InnoLux Display Corporation"}, {"INM","InnoMedia Inc"}, {"INN","Innovent Systems, Inc."}, {"INO","Innolab Pte Ltd"}, {"INP","Interphase Corporation"}, {"INS","Ines GmbH"}, {"INT","Interphase Corporation"}, {"INU","Inovatec S.p.A."}, // actually "inu" {"INV","Inviso, Inc."}, {"INX","Communications Supply Corporation {A division of WESCO}"}, {"INZ","Best Buy"}, {"IOA","CRE Technology Corporation"}, {"IOD","I-O Data Device Inc"}, {"IOM","Iomega"}, {"ION","Inside Out Networks"}, {"IOS","i-O Display System"}, {"IOT","I/OTech Inc"}, {"IPC","IPC Corporation"}, {"IPD","Industrial Products Design, Inc."}, {"IPI","Intelligent Platform Management Interface {IPMI} forum {Intel, HP, NEC, Dell}"}, {"IPM","IPM Industria Politecnica Meridionale SpA"}, {"IPN","Performance Technologies"}, {"IPP","IP Power Technologies GmbH "}, {"IPR","Ithaca Peripherals"}, {"IPS","IPS, Inc. {Intellectual Property Solutions, Inc.}"}, {"IPT","International Power Technologies"}, {"IPW","IPWireless, Inc"}, {"IQI","IneoQuest Technologies, Inc"}, {"IQT","IMAGEQUEST Co., Ltd"}, {"IRD","IRdata"}, {"ISA","Symbol Technologies"}, {"ISC","Id3 Semiconductors"}, {"ISG","Insignia Solutions Inc"}, {"ISI","Interface Solutions"}, {"ISL","Isolation Systems"}, {"ISM","Image Stream Medical"}, {"ISP","IntreSource Systems Pte Ltd"}, {"ISR","INSIS Co., LTD."}, {"ISS","ISS Inc"}, {"IST","Intersolve Technologies"}, {"ISY","International Integrated Systems,Inc. {IISI}"}, {"ITA","Itausa Export North America"}, {"ITC","Intercom Inc"}, {"ITD","Internet Technology Corporation"}, {"ITE","Integrated Tech Express Inc"}, {"ITK","ITK Telekommunikation AG"}, {"ITL","Inter-Tel"}, {"ITM","ITM inc."}, {"ITN","The NTI Group"}, {"ITP","IT-PRO Consulting und Systemhaus GmbH"}, {"ITR","Infotronic America, Inc."}, {"ITS","IDTECH"}, {"ITT","I&T Telecom."}, {"ITX","integrated Technology Express Inc"}, {"IUC","ICSL"}, {"IVI","Intervoice Inc"}, {"IVM","Iiyama North America"}, {"IVS","Intevac Photonics Inc."}, {"IWR","Icuiti Corporation"}, {"IWX","Intelliworxx, Inc."}, {"IXD","Intertex Data AB"}, {"JAC","Astec Inc"}, {"JAE","Japan Aviation Electronics Industry, Limited"}, {"JAS","Janz Automationssysteme AG"}, {"JAT","Jaton Corporation"}, {"JAZ","Carrera Computer Inc"}, {"JCE","Jace Tech Inc"}, {"JDL","Japan Digital Laboratory Co.,Ltd."}, {"JEN","N-Vision"}, {"JET","JET POWER TECHNOLOGY CO., LTD."}, {"JFX","Jones Futurex Inc"}, {"JGD","University College"}, {"JIC","Jaeik Information & Communication Co., Ltd."}, {"JKC","JVC KENWOOD Corporation"}, {"JMT","Micro Technical Company Ltd"}, {"JPC","JPC Technology Limited"}, {"JPW","Wallis Hamilton Industries"}, {"JQE","CNet Technical Inc"}, {"JSD","JS DigiTech, Inc"}, {"JSI","Jupiter Systems, Inc."}, {"JSK","SANKEN ELECTRIC CO., LTD"}, {"JTS","JS Motorsports"}, {"JTY","jetway security micro,inc"}, {"JUK","Janich & Klass Computertechnik GmbH"}, {"JUP","Jupiter Systems"}, {"JVC","JVC"}, {"JWD","Video International Inc."}, {"JWL","Jewell Instruments, LLC"}, {"JWS","JWSpencer & Co."}, {"JWY","Jetway Information Co., Ltd"}, {"KAR","Karna"}, {"KBI","Kidboard Inc"}, {"KBL","Kobil Systems GmbH"}, {"KCD","Chunichi Denshi Co.,LTD."}, {"KCL","Keycorp Ltd"}, {"KDE","KDE"}, {"KDK","Kodiak Tech"}, {"KDM","Korea Data Systems Co., Ltd."}, {"KDS","KDS USA"}, {"KDT","KDDI Technology Corporation"}, {"KEC","Kyushu Electronics Systems Inc"}, {"KEM","Kontron Embedded Modules GmbH"}, {"KES","Kesa Corporation"}, {"KEY","Key Tech Inc"}, {"KFC","SCD Tech"}, {"KFE ","Komatsu Forest "}, {"KFX","Kofax Image Products"}, {"KGL","KEISOKU GIKEN Co.,Ltd."}, {"KIS","KiSS Technology A/S"}, {"KMC","Mitsumi Company Ltd"}, {"KME","KIMIN Electronics Co., Ltd."}, {"KML","Kensington Microware Ltd"}, {"KNC","Konica corporation"}, {"KNX","Nutech Marketing PTL"}, {"KOB","Kobil Systems GmbH"}, {"KOD","Eastman Kodak Company"}, {"KOE","KOLTER ELECTRONIC"}, {"KOL","Kollmorgen Motion Technologies Group"}, {"KOU","KOUZIRO Co.,Ltd."}, {"KOW","KOWA Company,LTD. "}, {"KPC","King Phoenix Company"}, {"KRL","Krell Industries Inc."}, {"KRM","Kroma Telecom"}, {"KRY","Kroy LLC"}, {"KSC","Kinetic Systems Corporation"}, {"KSL","Karn Solutions Ltd."}, {"KSX","King Tester Corporation"}, {"KTC","Kingston Tech Corporation"}, {"KTD","Takahata Electronics Co.,Ltd."}, {"KTE","K-Tech"}, {"KTG","Kayser-Threde GmbH"}, {"KTI","Konica Technical Inc"}, {"KTK","Key Tronic Corporation"}, {"KTN","Katron Tech Inc"}, {"KUR","Kurta Corporation"}, {"KVA","Kvaser AB"}, {"KVX","KeyView"}, {"KWD","Kenwood Corporation"}, {"KYC","Kyocera Corporation"}, {"KYE","KYE Syst Corporation"}, {"KYK","Samsung Electronics America Inc"}, {"KZI","K-Zone International co. Ltd."}, {"KZN","K-Zone International"}, {"LAB","ACT Labs Ltd"}, {"LAC","LaCie"}, {"LAF","Microline"}, {"LAG","Laguna Systems"}, {"LAN","Sodeman Lancom Inc"}, {"LAS","LASAT Comm. A/S"}, {"LAV","Lava Computer MFG Inc"}, {"LBO","Lubosoft"}, {"LCC","LCI"}, {"LCD","Toshiba Matsushita Display Technology Co., Ltd"}, {"LCE","La Commande Electronique"}, {"LCI","Lite-On Communication Inc"}, {"LCM","Latitude Comm."}, {"LCN","LEXICON"}, {"LCS","Longshine Electronics Company"}, {"LCT","Labcal Technologies"}, {"LDT","LogiDataTech Electronic GmbH"}, {"LEC","Lectron Company Ltd"}, {"LED","Long Engineering Design Inc"}, {"LEG","Legerity, Inc"}, {"LEN","Lenovo Group Limited"}, {"LEO","First International Computer Inc"}, {"LEX","Lexical Ltd"}, {"LGC","Logic Ltd"}, {"LGI","Logitech Inc"}, {"LGS","LG Semicom Company Ltd"}, {"LGX","Lasergraphics, Inc."}, {"LHA","Lars Haagh ApS"}, {"LHE","Lung Hwa Electronics Company Ltd"}, {"LHT","Lighthouse Technologies Limited"}, {"LIN","Lenovo Beijing Co. Ltd."}, {"LIP","Linked IP GmbH"}, {"LIT","Lithics Silicon Technology"}, {"LJX","Datalogic Corporation"}, {"LKM","Likom Technology Sdn. Bhd."}, {"LLL","L-3 Communications"}, {"LMG","Lucent Technologies"}, {"LMI","Lexmark Int'l Inc"}, {"LMP","Leda Media Products"}, {"LMT","Laser Master"}, {"LND","Land Computer Company Ltd"}, {"LNK","Link Tech Inc"}, {"LNR","Linear Systems Ltd."}, {"LNT","LANETCO International"}, {"LNV","Lenovo"}, {"LOC","Locamation B.V."}, {"LOE","Loewe Opta GmbH"}, {"LOG","Logicode Technology Inc"}, {"LOL","Litelogic Operations Ltd"}, {"LPE","El-PUSK Co., Ltd."}, {"LPI","Design Technology"}, {"LSC","LifeSize Communications"}, {"LSD","Intersil Corporation"}, {"LSI","Loughborough Sound Images"}, {"LSJ","LSI Japan Company Ltd"}, {"LSL","Logical Solutions"}, {"LSY","LSI Systems Inc"}, {"LTC","Labtec Inc"}, {"LTI","Jongshine Tech Inc"}, {"LTK","Lucidity Technology Company Ltd"}, {"LTN","Litronic Inc"}, {"LTS","LTS Scale LLC"}, {"LTV","Leitch Technology International Inc."}, {"LTW","Lightware, Inc"}, {"LUC","Lucent Technologies"}, {"LUM","Lumagen, Inc."}, {"LUX","Luxxell Research Inc"}, {"LVI","LVI Low Vision International AB"}, {"LWC","Labway Corporation"}, {"LWR","Lightware Visual Engineering"}, {"LWW","Lanier Worldwide"}, {"LXC","LXCO Technologies AG"}, {"LXN","Luxeon"}, {"LXS","ELEA CardWare"}, {"LZX","Lightwell Company Ltd"}, {"MAC","MAC System Company Ltd"}, {"MAD","Xedia Corporation"}, {"MAE","Maestro Pty Ltd"}, {"MAG","MAG InnoVision"}, {"MAI","Mutoh America Inc"}, {"MAL","Meridian Audio Ltd"}, {"MAN","LGIC"}, {"MAS","Mass Inc."}, {"MAT","Matsushita Electric Ind. Company Ltd"}, {"MAX","Rogen Tech Distribution Inc"}, {"MAY","Maynard Electronics"}, {"MAZ","MAZeT GmbH"}, {"MBC","MBC"}, {"MBD","Microbus PLC"}, {"MBM","Marshall Electronics"}, {"MBV","Moreton Bay"}, {"MCA","American Nuclear Systems Inc"}, {"MCC","Micro Industries"}, {"MCD","McDATA Corporation"}, {"MCE","Metz-Werke GmbH & Co KG"}, {"MCG","Motorola Computer Group"}, {"MCI","Micronics Computers"}, {"MCL","Motorola Communications Israel"}, {"MCM","Metricom Inc"}, {"MCN","Micron Electronics Inc"}, {"MCO","Motion Computing Inc."}, {"MCP","Magni Systems Inc"}, {"MCQ","Mat's Computers"}, {"MCR","Marina Communicaitons"}, {"MCS","Micro Computer Systems"}, {"MCT","Microtec"}, {"MDA","Media4 Inc"}, {"MDC","Midori Electronics"}, {"MDD","MODIS"}, {"MDG","Madge Networks"}, {"MDI","Micro Design Inc"}, {"MDK","Mediatek Corporation"}, {"MDO","Panasonic"}, {"MDR","Medar Inc"}, {"MDS","Micro Display Systems Inc"}, {"MDT","Magus Data Tech"}, {"MDV","MET Development Inc"}, {"MDX","MicroDatec GmbH"}, {"MDY","Microdyne Inc"}, {"MEC","Mega System Technologies Inc"}, {"MED","Messeltronik Dresden GmbH"}, {"MEE","Mitsubishi Electric Engineering Co., Ltd."}, {"MEG","Abeam Tech Ltd"}, {"MEI","Panasonic Industry Company"}, {"MEJ","Mac-Eight Co., LTD."}, {"MEL","Mitsubishi Electric Corporation"}, {"MEN","MEN Mikroelectronik Nueruberg GmbH"}, {"MEP","Meld Technology"}, {"MEQ","Matelect Ltd."}, {"MET","Metheus Corporation"}, {"MEX","MSC Vertriebs GmbH"}, {"MFG","MicroField Graphics Inc"}, {"MFI","Micro Firmware"}, {"MFR","MediaFire Corp."}, {"MGA","Mega System Technologies, Inc."}, {"MGC","Mentor Graphics Corporation"}, {"MGE","Schneider Electric S.A."}, {"MGL","M-G Technology Ltd"}, {"MGT","Megatech R & D Company"}, {"MIC","Micom Communications Inc"}, {"MID","miro Displays"}, {"MII","Mitec Inc"}, {"MIL","Marconi Instruments Ltd"}, {"MIM","Mimio – A Newell Rubbermaid Company"}, {"MIN","Minicom Digital Signage"}, {"MIP","micronpc.com"}, {"MIR","Miro Computer Prod."}, {"MIS","Modular Industrial Solutions Inc"}, {"MIT","MCM Industrial Technology GmbH"}, {"MJI","MARANTZ JAPAN, INC."}, {"MJS","MJS Designs"}, {"MKC","Media Tek Inc."}, {"MKT","MICROTEK Inc."}, {"MKV","Trtheim Technology"}, {"MLD","Deep Video Imaging Ltd"}, {"MLG","Micrologica AG"}, {"MLI","McIntosh Laboratory Inc."}, {"MLM","Millennium Engineering Inc"}, {"MLN","Mark Levinson"}, {"MLS","Milestone EPE"}, {"MLX","Mylex Corporation"}, {"MMA","Micromedia AG"}, {"MMD","Micromed Biotecnologia Ltd"}, {"MMF","Minnesota Mining and Manufacturing"}, {"MMI","Multimax"}, {"MMM","Electronic Measurements"}, {"MMN","MiniMan Inc"}, {"MMS","MMS Electronics"}, {"MNC","Mini Micro Methods Ltd"}, {"MNL","Monorail Inc"}, {"MNP","Microcom"}, {"MOD","Modular Technology"}, {"MOM","Momentum Data Systems"}, {"MOS","Moses Corporation"}, {"MOT","Motorola UDS"}, {"MPC","M-Pact Inc"}, {"MPI","Mediatrix Peripherals Inc"}, {"MPJ","Microlab"}, {"MPL","Maple Research Inst. Company Ltd"}, {"MPN","Mainpine Limited"}, {"MPS","mps Software GmbH"}, {"MPX","Micropix Technologies, Ltd."}, {"MQP","MultiQ Products AB"}, {"MRA","Miranda Technologies Inc"}, {"MRC","Marconi Simulation & Ty-Coch Way Training"}, {"MRD","MicroDisplay Corporation"}, {"MRK","Maruko & Company Ltd"}, {"MRL","Miratel"}, {"MRO","Medikro Oy"}, {"MRT","Merging Technologies"}, {"MSA","Micro Systemation AB"}, {"MSC","Mouse Systems Corporation"}, {"MSD","Datenerfassungs- und Informationssysteme"}, {"MSF","M-Systems Flash Disk Pioneers"}, {"MSG","MSI GmbH"}, {"MSH","Microsoft"}, {"MSI","Microstep"}, {"MSK","Megasoft Inc"}, {"MSL","MicroSlate Inc."}, {"MSM","Advanced Digital Systems"}, {"MSP","Mistral Solutions [P] Ltd."}, {"MSR","MASPRO DENKOH Corp."}, {"MST","MS Telematica"}, {"MSU","motorola"}, {"MSV","Mosgi Corporation"}, {"MSX","Micomsoft Co., Ltd."}, {"MSY","MicroTouch Systems Inc"}, {"MTB","Media Technologies Ltd."}, {"MTC","Mars-Tech Corporation"}, {"MTD","MindTech Display Co. Ltd"}, {"MTE","MediaTec GmbH"}, {"MTH","Micro-Tech Hearing Instruments"}, {"MTI","MaxCom Technical Inc"}, {"MTI","Motorola Inc."}, {"MTK","Microtek International Inc."}, {"MTL","Mitel Corporation"}, {"MTM","Motium"}, {"MTN","Mtron Storage Technology Co., Ltd."}, {"MTR","Mitron computer Inc"}, {"MTS","Multi-Tech Systems"}, {"MTU","Mark of the Unicorn Inc"}, {"MTX","Matrox"}, {"MUD","Multi-Dimension Institute"}, {"MUK","mainpine limited"}, {"MVD","Microvitec PLC"}, {"MVI","Media Vision Inc"}, {"MVM","SOBO VISION"}, {"MVS","Microvision"}, {"MVX","COM 1"}, {"MWI","Multiwave Innovation Pte Ltd"}, {"MWR","mware"}, {"MWY","Microway Inc"}, {"MXD","MaxData Computer GmbH & Co.KG"}, {"MXI","Macronix Inc"}, {"MXL","Hitachi Maxell, Ltd."}, {"MXP","Maxpeed Corporation"}, {"MXT","Maxtech Corporation"}, {"MXV","MaxVision Corporation"}, {"MYA","Monydata"}, {"MYR","Myriad Solutions Ltd"}, {"MYX","Micronyx Inc"}, {"NAC","Ncast Corporation"}, {"NAD","NAD Electronics"}, {"NAK","Nakano Engineering Co.,Ltd."}, {"NAL","Network Alchemy"}, {"NAT","NaturalPoint Inc."}, {"NAV","Navigation Corporation"}, {"NAX","Naxos Tecnologia"}, {"NBL","N*Able Technologies Inc"}, {"NBS","National Key Lab. on ISN"}, {"NBT","NingBo Bestwinning Technology CO., Ltd"}, {"NCA","Nixdorf Company"}, {"NCC","NCR Corporation"}, {"NCE","Norcent Technology, Inc."}, {"NCI","NewCom Inc"}, {"NCL","NetComm Ltd"}, {"NCR","NCR Electronics"}, {"NCS","Northgate Computer Systems"}, {"NCT","NEC CustomTechnica, Ltd."}, {"NDC","National DataComm Corporaiton"}, {"NDI","National Display Systems"}, {"NDK","Naitoh Densei CO., LTD."}, {"NDL","Network Designers"}, {"NDS","Nokia Data"}, {"NEC","NEC Corporation"}, {"NEO","NEO TELECOM CO.,LTD."}, {"NET","Mettler Toledo"}, {"NEU","NEUROTEC - EMPRESA DE PESQUISA E DESENVOLVIMENTO EM BIOMEDICINA"}, {"NEX","Nexgen Mediatech Inc.,"}, {"NFC","BTC Korea Co., Ltd"}, {"NFS","Number Five Software"}, {"NGC","Network General"}, {"NGS","A D S Exports"}, {"NHT","Vinci Labs"}, {"NIC","National Instruments Corporation"}, {"NIS","Nissei Electric Company"}, {"NIT","Network Info Technology"}, {"NIX","Seanix Technology Inc"}, {"NLC","Next Level Communications"}, {"NME","Navico, Inc."}, {"NMP","Nokia Mobile Phones"}, {"NMS","Natural Micro System"}, {"NMV","NEC-Mitsubishi Electric Visual Systems Corporation"}, {"NMX","Neomagic"}, {"NNC","NNC"}, {"NOE","NordicEye AB"}, {"NOI","North Invent A/S"}, {"NOK","Nokia Display Products"}, {"NOR","Norand Corporation"}, {"NOT","Not Limited Inc"}, {"NPI","Network Peripherals Inc"}, {"NRL","U.S. Naval Research Lab"}, {"NRT","Beijing Northern Radiantelecom Co."}, {"NRV","Taugagreining hf"}, {"NSC","National Semiconductor Corporation"}, {"NSI","NISSEI ELECTRIC CO.,LTD"}, {"NSP","Nspire System Inc."}, {"NSS","Newport Systems Solutions"}, {"NST","Network Security Technology Co"}, {"NTC","NeoTech S.R.L"}, {"NTI","New Tech Int'l Company"}, {"NTL","National Transcomm. Ltd"}, {"NTN","Nuvoton Technology Corporation "}, {"NTR","N-trig Innovative Technologies, Inc."}, {"NTS","Nits Technology Inc."}, {"NTT","NTT Advanced Technology Corporation"}, {"NTW","Networth Inc"}, {"NTX","Netaccess Inc"}, {"NUG","NU Technology, Inc."}, {"NUI","NU Inc."}, {"NVC","NetVision Corporation"}, {"NVD","Nvidia"}, {"NVI","NuVision US, Inc."}, {"NVL","Novell Inc"}, {"NVT","Navatek Engineering Corporation"}, {"NWC","NW Computer Engineering"}, {"NWP","NovaWeb Technologies Inc"}, {"NWS","Newisys, Inc."}, {"NXC","NextCom K.K."}, {"NXG","Nexgen"}, {"NXP","NXP Semiconductors bv."}, {"NXQ","Nexiq Technologies, Inc."}, {"NXS","Technology Nexus Secure Open Systems AB"}, {"NYC","nakayo telecommunications,inc."}, {"OAK","Oak Tech Inc"}, {"OAS","Oasys Technology Company"}, {"OBS","Optibase Technologies"}, {"OCD","Macraigor Systems Inc"}, {"OCN","Olfan"}, {"OCS","Open Connect Solutions"}, {"ODM","ODME Inc."}, {"ODR","Odrac"}, {"OEC","ORION ELECTRIC CO.,LTD"}, {"OEI","Optum Engineering Inc."}, {"OIC","Option Industrial Computers"}, {"OIM","Option International"}, {"OIN","Option International"}, {"OKI","OKI Electric Industrial Company Ltd"}, {"OLC","Olicom A/S"}, {"OLD","Olidata S.p.A."}, {"OLI","Olivetti"}, {"OLT","Olitec S.A."}, {"OLV","Olitec S.A."}, {"OLY","OLYMPUS CORPORATION"}, {"OMC","OBJIX Multimedia Corporation"}, {"OMN","Omnitel"}, {"OMR","Omron Corporation"}, {"ONE","Oneac Corporation"}, {"ONK","ONKYO Corporation"}, {"ONL","OnLive, Inc"}, {"ONS","On Systems Inc"}, {"ONW","OPEN Networks Ltd"}, {"ONX","SOMELEC Z.I. Du Vert Galanta"}, {"OOS","OSRAM"}, {"OPC","Opcode Inc"}, {"OPI","D.N.S. Corporation"}, {"OPP","OPPO Digital, Inc."}, {"OPT","OPTi Inc"}, {"OPV","Optivision Inc"}, {"OQI","Oksori Company Ltd"}, {"ORG","ORGA Kartensysteme GmbH"}, {"ORI","OSR Open Systems Resources, Inc."}, {"ORN","ORION ELECTRIC CO., LTD."}, {"OSA","OSAKA Micro Computer, Inc."}, {"OSP","OPTI-UPS Corporation"}, {"OSR","Oksori Company Ltd"}, {"OTB","outsidetheboxstuff.com"}, {"OTI","Orchid Technology"}, {"OTM","Optoma Corporation "}, {"OTT","OPTO22, Inc."}, {"OUK","OUK Company Ltd"}, {"OVR","Oculus VR, Inc."}, {"OWL","Mediacom Technologies Pte Ltd"}, {"OXU","Oxus Research S.A."}, {"OYO","Shadow Systems"}, {"OZC","OZ Corporation"}, {"OZO","Tribe Computer Works Inc"}, {"PAC","Pacific Avionics Corporation"}, {"PAD","Promotion and Display Technology Ltd."}, {"PAK","Many CNC System Co., Ltd."}, {"PAM","Peter Antesberger Messtechnik"}, {"PAN","The Panda Project"}, {"PAR","Parallan Comp Inc"}, {"PBI","Pitney Bowes"}, {"PBL","Packard Bell Electronics"}, {"PBN","Packard Bell NEC"}, {"PBV","Pitney Bowes"}, {"PCA","Philips BU Add On Card"}, {"PCB","OCTAL S.A."}, {"PCC","PowerCom Technology Company Ltd"}, {"PCG","First Industrial Computer Inc"}, {"PCI","Pioneer Computer Inc"}, {"PCK","PCBANK21"}, {"PCL","pentel.co.,ltd"}, {"PCM","PCM Systems Corporation"}, {"PCO","Performance Concepts Inc.,"}, {"PCP","Procomp USA Inc"}, {"PCS","TOSHIBA PERSONAL COMPUTER SYSTEM CORPRATION"}, {"PCT","PC-Tel Inc"}, {"PCW","Pacific CommWare Inc"}, {"PCX","PC Xperten"}, {"PDM","Psion Dacom Plc."}, {"PDN","AT&T Paradyne"}, {"PDR","Pure Data Inc"}, {"PDS","PD Systems International Ltd"}, {"PDT","PDTS - Prozessdatentechnik und Systeme"}, {"PDV","Prodrive B.V."}, {"PEC","POTRANS Electrical Corp."}, {"PEI","PEI Electronics Inc"}, {"PEL","Primax Electric Ltd"}, {"PEN","Interactive Computer Products Inc"}, {"PEP","Peppercon AG"}, {"PER","Perceptive Signal Technologies"}, {"PET","Practical Electronic Tools"}, {"PFT","Telia ProSoft AB"}, {"PGI","PACSGEAR, Inc."}, {"PGM","Paradigm Advanced Research Centre"}, {"PGP","propagamma kommunikation"}, {"PGS","Princeton Graphic Systems"}, {"PHC","Pijnenburg Beheer N.V."}, {"PHE","Philips Medical Systems Boeblingen GmbH"}, {"PHL","Philips Consumer Electronics Company"}, {"PHO","Photonics Systems Inc."}, {"PHS","Philips Communication Systems"}, {"PHY","Phylon Communications"}, {"PIE","Pacific Image Electronics Company Ltd"}, {"PIM","Prism, LLC"}, {"PIO","Pioneer Electronic Corporation"}, {"PIX","Pixie Tech Inc"}, {"PJA","Projecta"}, {"PJD","Projectiondesign AS"}, {"PJT","Pan Jit International Inc."}, {"PKA","Acco UK ltd. "}, {"PLC","Pro-Log Corporation"}, {"PLF","Panasonic Avionics Corporation"}, {"PLM","PROLINK Microsystems Corp."}, {"PLT","PT Hartono Istana Teknologi"}, {"PLV","PLUS Vision Corp."}, {"PLX","Parallax Graphics"}, {"PLY","Polycom Inc."}, {"PMC","PMC Consumer Electronics Ltd"}, {"PMD","TDK USA Corporation"}, {"PMM","Point Multimedia System"}, {"PMT","Promate Electronic Co., Ltd."}, {"PMX","Photomatrix"}, {"PNG","Microsoft"}, {"PNG","P.I. Engineering Inc"}, {"PNL","Panelview, Inc."}, {"PNP","Microsoft"}, {"PNR","Planar Systems, Inc."}, {"PNS","PanaScope"}, {"PNX","Phoenix Technologies, Ltd."}, {"POL","PolyComp {PTY} Ltd."}, {"PON","Perpetual Technologies, LLC"}, {"POR","Portalis LC"}, {"PPC","Phoenixtec Power Company Ltd"}, {"PPD","MEPhI"}, {"PPI","Practical Peripherals"}, {"PPM","Clinton Electronics Corp."}, {"PPP","Purup Prepress AS"}, {"PPR","PicPro"}, {"PPX","Perceptive Pixel Inc."}, {"PQI","Pixel Qi"}, {"PRA","PRO/AUTOMATION"}, {"PRC","PerComm"}, {"PRD","Praim S.R.L."}, {"PRF","Digital Electronics Corporation"}, {"PRG","The Phoenix Research Group Inc"}, {"PRI","Priva Hortimation BV"}, {"PRM","Prometheus"}, {"PRO","Proteon"}, {"PRS","Leutron Vision"}, {"PRT","Parade Technologies, Ltd."}, {"PRX","Proxima Corporation"}, {"PSA","Advanced Signal Processing Technologies"}, {"PSC","Philips Semiconductors"}, {"PSD","Peus-Systems GmbH"}, {"PSE","Practical Solutions Pte., Ltd."}, {"PSI","PSI-Perceptive Solutions Inc"}, {"PSL","Perle Systems Limited"}, {"PSM","Prosum"}, {"PST","Global Data SA"}, {"PSY","Prodea Systems Inc."}, {"PTA","PAR Tech Inc."}, {"PTC","PS Technology Corporation"}, {"PTG","Cipher Systems Inc"}, {"PTH","Pathlight Technology Inc"}, {"PTI","Promise Technology Inc"}, {"PTL","Pantel Inc"}, {"PTS","Plain Tree Systems Inc"}, {"PUL","Pulse-Eight Ltd"}, {"PVG","Proview Global Co., Ltd"}, {"PVI","Prime view international Co., Ltd"}, {"PVM","Penta Studiotechnik GmbH"}, {"PVN","Pixel Vision"}, {"PVP","Klos Technologies, Inc."}, {"PXC","Phoenix Contact"}, {"PXE","PIXELA CORPORATION"}, {"PXL","The Moving Pixel Company"}, {"PXM","Proxim Inc"}, {"QCC","QuakeCom Company Ltd"}, {"QCH","Metronics Inc"}, {"QCI","Quanta Computer Inc"}, {"QCK","Quick Corporation"}, {"QCL","Quadrant Components Inc"}, {"QCP","Qualcomm Inc"}, {"QDI","Quantum Data Incorporated"}, {"QDM","Quadram"}, {"QDS","Quanta Display Inc."}, {"QFF","Padix Co., Inc."}, {"QFI","Quickflex, Inc"}, {"QLC","Q-Logic"}, {"QQQ","Chuomusen Co., Ltd. "}, {"QSI","Quantum Solutions, Inc."}, {"QTD","Quantum 3D Inc"}, {"QTH","Questech Ltd"}, {"QTI","Quicknet Technologies Inc"}, {"QTM","Quantum"}, {"QTR","Qtronix Corporation"}, {"QUA","Quatographic AG"}, {"QUE","Questra Consulting"}, {"QVU","Quartics"}, {"RAC","Racore Computer Products Inc"}, {"RAD","Radisys Corporation"}, {"RAI","Rockwell Automation/Intecolor"}, {"RAN","Rancho Tech Inc"}, {"RAR","Raritan, Inc."}, {"RAS","RAScom Inc"}, {"RAT","Rent-A-Tech"}, {"RAY","Raylar Design, Inc."}, {"RCE","Parc d'Activite des Bellevues"}, {"RCH","Reach Technology Inc"}, {"RCI","RC International"}, {"RCN","Radio Consult SRL"}, {"RCO","Rockwell Collins"}, {"RDI","Rainbow Displays, Inc."}, {"RDM","Tremon Enterprises Company Ltd"}, {"RDN","RADIODATA GmbH"}, {"RDS","Radius Inc"}, {"REA","Real D"}, {"REC","ReCom"}, {"RED","Research Electronics Development Inc"}, {"REF","Reflectivity, Inc."}, {"REH","Rehan Electronics Ltd."}, {"REL","Reliance Electric Ind Corporation"}, {"REM","SCI Systems Inc."}, {"REN","Renesas Technology Corp."}, {"RES","ResMed Pty Ltd"}, {"RET","Resonance Technology, Inc."}, {"REX","RATOC Systems, Inc."}, {"RGB","RGB Spectrum"}, {"RGL","Robertson Geologging Ltd"}, {"RHD","RightHand Technologies"}, {"RHM","Rohm Company Ltd"}, {"RHT","Red Hat, Inc."}, {"RIC","RICOH COMPANY, LTD."}, {"RII","Racal Interlan Inc"}, {"RIO","Rios Systems Company Ltd"}, {"RIT","Ritech Inc"}, {"RIV","Rivulet Communications"}, {"RJA","Roland Corporation"}, {"RJS","Advanced Engineering"}, {"RKC","Reakin Technolohy Corporation"}, {"RLD","MEPCO"}, {"RLN","RadioLAN Inc"}, {"RMC","Raritan Computer, Inc"}, {"RMP","Research Machines"}, {"RMT","Roper Mobile"}, {"RNB","Rainbow Technologies"}, {"ROB","Robust Electronics GmbH "}, {"ROH","Rohm Co., Ltd."}, {"ROK","Rockwell International"}, {"ROP","Roper International Ltd"}, {"ROS","Rohde & Schwarz"}, {"RPI","RoomPro Technologies"}, {"RPT","R.P.T.Intergroups"}, {"RRI","Radicom Research Inc"}, {"RSC","PhotoTelesis"}, {"RSH","ADC-Centre"}, {"RSI","Rampage Systems Inc"}, {"RSN","Radiospire Networks, Inc."}, {"RSQ","R Squared"}, {"RSS","Rockwell Semiconductor Systems"}, {"RSV","Ross Video Ltd"}, {"RSX","Rapid Tech Corporation"}, {"RTC","Relia Technologies"}, {"RTI","Rancho Tech Inc"}, {"RTL","Realtek Semiconductor Company Ltd"}, {"RTS","Raintree Systems"}, {"RUN","RUNCO International"}, {"RUP","Ups Manufactoring s.r.l."}, {"RVC","RSI Systems Inc"}, {"RVI","Realvision Inc"}, {"RVL","Reveal Computer Prod"}, {"RWC","Red Wing Corporation"}, {"RXT","Tectona SoftSolutions {P} Ltd.,"}, {"SAA","Sanritz Automation Co.,Ltd."}, {"SAE","Saab Aerotech"}, {"SAG","Sedlbauer"}, {"SAI","Sage Inc"}, {"SAK","Saitek Ltd"}, {"SAM","Samsung Electric Company"}, {"SAN","Sanyo Electric Co.,Ltd."}, {"SAS","Stores Automated Systems Inc"}, {"SAT","Shuttle Tech"}, {"SBC","Shanghai Bell Telephone Equip Mfg Co"}, {"SBD","Softbed - Consulting & Development Ltd"}, {"SBI","SMART Technologies Inc."}, {"SBS","SBS-or Industrial Computers GmbH"}, {"SBT","Senseboard Technologies AB"}, {"SCB","SeeCubic B.V."}, {"SCC","SORD Computer Corporation"}, {"SCD","Sanyo Electric Company Ltd"}, {"SCE","Sun Corporation"}, {"SCH","Schlumberger Cards"}, {"SCI","System Craft"}, {"SCL","Sigmacom Co., Ltd."}, {"SCM","SCM Microsystems Inc"}, {"SCN","Scanport, Inc."}, {"SCO","SORCUS Computer GmbH"}, {"SCP","Scriptel Corporation"}, {"SCR","Systran Corporation"}, {"SCS","Nanomach Anstalt"}, {"SCT","Smart Card Technology"}, {"SDA","SAT {Societe Anonyme}"}, {"SDD","Intrada-SDD Ltd"}, {"SDE","Sherwood Digital Electronics Corporation"}, {"SDF","SODIFF E&T CO., Ltd."}, {"SDH","Communications Specialies, Inc."}, {"SDI","Samtron Displays Inc"}, {"SDK","SAIT-Devlonics"}, {"SDR","SDR Systems"}, {"SDS","SunRiver Data System"}, {"SDT","Siemens AG"}, {"SDX","SDX Business Systems Ltd"}, {"SEA","Seanix Technology Inc."}, {"SEB","system elektronik GmbH"}, {"SEC","Seiko Epson Corporation"}, {"SEE","SeeColor Corporation"}, {"SEI","Seitz & Associates Inc"}, {"SEL","Way2Call Communications"}, {"SEM","Samsung Electronics Company Ltd"}, {"SEN","Sencore"}, {"SEO","SEOS Ltd"}, {"SEP","SEP Eletronica Ltda."}, {"SER","Sony Ericsson Mobile Communications Inc."}, {"SES","Session Control LLC"}, {"SET","SendTek Corporation"}, {"SFM","TORNADO Company"}, {"SFT","Mikroforum Ring 3"}, {"SGC","Spectragraphics Corporation"}, {"SGD","Sigma Designs, Inc."}, {"SGE","Kansai Electric Company Ltd"}, {"SGI","Scan Group Ltd"}, {"SGL","Super Gate Technology Company Ltd"}, {"SGM","SAGEM"}, {"SGO","Logos Design A/S"}, {"SGT","Stargate Technology"}, {"SGW","Shanghai Guowei Science and Technology Co., Ltd."}, {"SGX","Silicon Graphics Inc"}, {"SGZ","Systec Computer GmbH"}, {"SHC","ShibaSoku Co., Ltd."}, {"SHG","Soft & Hardware development Goldammer GmbH"}, {"SHI","Jiangsu Shinco Electronic Group Co., Ltd"}, {"SHP","Sharp Corporation"}, {"SHR","Digital Discovery"}, {"SHT","Shin Ho Tech"}, {"SIA","SIEMENS AG"}, {"SIB","Sanyo Electric Company Ltd"}, {"SIC","Sysmate Corporation"}, {"SID","Seiko Instruments Information Devices Inc"}, {"SIE","Siemens"}, {"SIG","Sigma Designs Inc"}, {"SII","Silicon Image, Inc."}, {"SIL","Silicon Laboratories, Inc"}, {"SIM","S3 Inc"}, {"SIN","Singular Technology Co., Ltd."}, {"SIR","Sirius Technologies Pty Ltd"}, {"SIS","Silicon Integrated Systems Corporation"}, {"SIT","Sitintel"}, {"SIU","Seiko Instruments USA Inc"}, {"SIX","Zuniq Data Corporation"}, {"SJE","Sejin Electron Inc"}, {"SKD","Schneider & Koch"}, {"SKT","Samsung Electro-Mechanics Company Ltd"}, {"SKY","SKYDATA S.P.A."}, {"SLA","Systeme Lauer GmbH&Co KG"}, {"SLB","Shlumberger Ltd"}, {"SLC","Syslogic Datentechnik AG"}, {"SLF","StarLeaf"}, {"SLH","Silicon Library Inc."}, {"SLI","Symbios Logic Inc"}, {"SLK","Silitek Corporation"}, {"SLM","Solomon Technology Corporation"}, {"SLR","Schlumberger Technology Corporate"}, {"SLS","Schnick-Schnack-Systems GmbH"}, {"SLT","Salt Internatioinal Corp."}, {"SLX","Specialix"}, {"SMA","SMART Modular Technologies"}, {"SMB","Schlumberger"}, {"SMC","Standard Microsystems Corporation"}, {"SME","Sysmate Company"}, {"SMI","SpaceLabs Medical Inc"}, {"SMK","SMK CORPORATION"}, {"SML","Sumitomo Metal Industries, Ltd."}, {"SMM","Shark Multimedia Inc"}, {"SMO","STMicroelectronics"}, {"SMP","Simple Computing"}, {"SMR","B.& V. s.r.l."}, {"SMS","Silicom Multimedia Systems Inc"}, {"SMT","Silcom Manufacturing Tech Inc"}, {"SNC","Sentronic International Corp."}, {"SNI","Siemens Microdesign GmbH"}, {"SNK","S&K Electronics"}, {"SNO","SINOSUN TECHNOLOGY CO., LTD"}, {"SNP","Siemens Nixdorf Info Systems"}, {"SNS","Cirtech {UK} Ltd"}, {"SNT","SuperNet Inc"}, {"SNW","Snell & Wilcox"}, {"SNX","Sonix Comm. Ltd"}, {"SNY","Sony"}, {"SOI","Silicon Optix Corporation"}, {"SOL","Solitron Technologies Inc"}, {"SON","Sony"}, {"SOR","Sorcus Computer GmbH"}, {"SOT","Sotec Company Ltd"}, {"SOY","SOYO Group, Inc"}, {"SPC","SpinCore Technologies, Inc"}, {"SPE","SPEA Software AG"}, {"SPH","G&W Instruments GmbH"}, {"SPI","SPACE-I Co., Ltd."}, {"SPK","SpeakerCraft"}, {"SPL","Smart Silicon Systems Pty Ltd"}, {"SPN","Sapience Corporation"}, {"SPR","pmns GmbH"}, {"SPS","Synopsys Inc"}, {"SPT","Sceptre Tech Inc"}, {"SPU","SIM2 Multimedia S.P.A."}, {"SPX","Simplex Time Recorder Co."}, {"SQT","Sequent Computer Systems Inc"}, {"SRC","Integrated Tech Express Inc"}, {"SRD","Setred"}, {"SRF","Surf Communication Solutions Ltd"}, {"SRG","Intuitive Surgical, Inc."}, {"SRS","SR-Systems e.K."}, {"SRT","SeeReal Technologies GmbH"}, {"SSC","Sierra Semiconductor Inc"}, {"SSD","FlightSafety International"}, {"SSE","Samsung Electronic Co."}, {"SSI","S-S Technology Inc"}, {"SSJ","Sankyo Seiki Mfg.co., Ltd"}, {"SSP","Spectrum Signal Proecessing Inc"}, {"SSS","S3 Inc"}, {"SST","SystemSoft Corporation"}, {"STA","ST Electronics Systems Assembly Pte Ltd"}, {"STB","STB Systems Inc"}, {"STC","STAC Electronics"}, {"STD","STD Computer Inc"}, {"STE","SII Ido-Tsushin Inc"}, {"STF","Starflight Electronics"}, {"STG","StereoGraphics Corp."}, {"STH","Semtech Corporation"}, {"STI","Smart Tech Inc"}, {"STK","SANTAK CORP."}, {"STL","SigmaTel Inc"}, {"STM","SGS Thomson Microelectronics"}, {"STN","Samsung Electronics America"}, {"STO","Stollmann E+V GmbH"}, {"STP","StreamPlay Ltd"}, {"STR","Starlight Networks Inc"}, {"STS","SITECSYSTEM CO., LTD."}, {"STT","Star Paging Telecom Tech {Shenzhen} Co. Ltd."}, {"STU","Sentelic Corporation"}, {"STW","Starwin Inc."}, {"STX","ST-Ericsson"}, {"STY","SDS Technologies"}, {"SUB","Subspace Comm. Inc"}, {"SUM","Summagraphics Corporation"}, {"SUN","Sun Electronics Corporation"}, {"SUP","Supra Corporation"}, {"SUR","Surenam Computer Corporation"}, {"SVA","SGEG"}, {"SVC","Intellix Corp."}, {"SVD","SVD Computer"}, {"SVI","Sun Microsystems"}, {"SVS","SVSI"}, {"SVT","SEVIT Co., Ltd."}, {"SWC","Software Café"}, {"SWI","Sierra Wireless Inc."}, {"SWL","Sharedware Ltd"}, {"SWS","Static"}, {"SWT","Software Technologies Group,Inc."}, {"SXB","Syntax-Brillian"}, {"SXD","Silex technology, Inc."}, {"SXG","SELEX GALILEO"}, {"SXL","SolutionInside"}, {"SXT","SHARP TAKAYA ELECTRONIC INDUSTRY CO.,LTD."}, {"SYC","Sysmic"}, {"SYE","SY Electronics Ltd"}, {"SYK","Stryker Communications"}, {"SYL","Sylvania Computer Products"}, {"SYM","Symicron Computer Communications Ltd."}, {"SYN","Synaptics Inc"}, {"SYP","SYPRO Co Ltd"}, {"SYS","Sysgration Ltd"}, {"SYT","Seyeon Tech Company Ltd"}, {"SYV","SYVAX Inc"}, {"SYX","Prime Systems, Inc."}, {"TAA","Tandberg"}, {"TAB","Todos Data System AB"}, {"TAG","Teles AG"}, {"TAI","Toshiba America Info Systems Inc"}, {"TAM","Tamura Seisakusyo Ltd"}, {"TAS","Taskit Rechnertechnik GmbH"}, {"TAT","Teleliaison Inc"}, {"TAX","Taxan {Europe} Ltd"}, {"TBB","Triple S Engineering Inc"}, {"TBC","Turbo Communication, Inc"}, {"TBS","Turtle Beach System"}, {"TCC","Tandon Corporation"}, {"TCD","Taicom Data Systems Co., Ltd."}, {"TCE","Century Corporation"}, {"TCH","Interaction Systems, Inc"}, {"TCI","Tulip Computers Int'l B.V."}, {"TCJ","TEAC America Inc"}, {"TCL","Technical Concepts Ltd"}, {"TCM","3Com Corporation"}, {"TCN","Tecnetics {PTY} Ltd"}, {"TCO","Thomas-Conrad Corporation"}, {"TCR","Thomson Consumer Electronics"}, {"TCS","Tatung Company of America Inc"}, {"TCT","Telecom Technology Centre Co. Ltd."}, {"TCX","FREEMARS Heavy Industries"}, {"TDC","Teradici"}, {"TDD","Tandberg Data Display AS"}, {"TDK","TDK USA Corporation"}, {"TDM","Tandem Computer Europe Inc"}, {"TDP","3D Perception"}, {"TDS","Tri-Data Systems Inc"}, {"TDT","TDT"}, {"TDV","TDVision Systems, Inc."}, {"TDY","Tandy Electronics"}, {"TEA","TEAC System Corporation"}, {"TEC","Tecmar Inc"}, {"TEK","Tektronix Inc"}, {"TEL","Promotion and Display Technology Ltd."}, {"TER","TerraTec Electronic GmbH"}, {"TGC","Toshiba Global Commerce Solutions, Inc."}, {"TGI","TriGem Computer Inc"}, {"TGM","TriGem Computer,Inc."}, {"TGS","Torus Systems Ltd"}, {"TGV","Grass Valley Germany GmbH"}, {"THN","Thundercom Holdings Sdn. Bhd."}, {"TIC","Trigem KinfoComm"}, {"TIP","TIPTEL AG"}, {"TIV","OOO Technoinvest"}, {"TIX","Tixi.Com GmbH"}, {"TKC","Taiko Electric Works.LTD"}, {"TKN","Teknor Microsystem Inc"}, {"TKO","TouchKo, Inc."}, {"TKS","TimeKeeping Systems, Inc."}, {"TLA","Ferrari Electronic GmbH"}, {"TLD","Telindus"}, {"TLF","Teleforce.,co,ltd"}, {"TLI","TOSHIBA TELI CORPORATION"}, {"TLK","Telelink AG"}, {"TLS","Teleste Educational OY"}, {"TLT","Dai Telecom S.p.A."}, {"TLV","S3 Inc"}, {"TLX","Telxon Corporation"}, {"TMC","Techmedia Computer Systems Corporation"}, {"TME","AT&T Microelectronics"}, {"TMI","Texas Microsystem"}, {"TMM","Time Management, Inc."}, {"TMR","Taicom International Inc"}, {"TMS","Trident Microsystems Ltd"}, {"TMT","T-Metrics Inc."}, {"TMX","Thermotrex Corporation"}, {"TNC","TNC Industrial Company Ltd"}, {"TNM","TECNIMAGEN SA"}, {"TNY","Tennyson Tech Pty Ltd"}, {"TOE","TOEI Electronics Co., Ltd."}, {"TOG","The OPEN Group"}, {"TON","TONNA"}, {"TOP","Orion Communications Co., Ltd."}, {"TOS","Toshiba Corporation"}, {"TOU","Touchstone Technology"}, {"TPC","Touch Panel Systems Corporation"}, {"TPE","Technology Power Enterprises Inc"}, {"TPJ","Junnila"}, {"TPK","TOPRE CORPORATION"}, {"TPR","Topro Technology Inc"}, {"TPS","Teleprocessing Systeme GmbH"}, {"TPT","Thruput Ltd"}, {"TPV","Top Victory Electronics { Fujian } Company Ltd"}, {"TPZ","Ypoaz Systems Inc"}, {"TRA","TriTech Microelectronics International"}, {"TRC","Trioc AB"}, {"TRD","Trident Microsystem Inc"}, {"TRE","Tremetrics"}, {"TRI","Tricord Systems"}, {"TRL","Royal Information"}, {"TRM","Tekram Technology Company Ltd"}, {"TRN","Datacommunicatie Tron B.V."}, {"TRS","Torus Systems Ltd"}, {"TRT","Tritec Electronic AG"}, {"TRU","Aashima Technology B.V."}, {"TRV","Trivisio Prototyping GmbH"}, {"TRX","Trex Enterprises"}, {"TSB","Toshiba America Info Systems Inc"}, {"TSC","Sanyo Electric Company Ltd"}, {"TSD","TechniSat Digital GmbH"}, {"TSE","Tottori Sanyo Electric"}, {"TSF","Racal-Airtech Software Forge Ltd"}, {"TSG","The Software Group Ltd"}, {"TSI","TeleVideo Systems"}, {"TSL","Tottori SANYO Electric Co., Ltd."}, {"TSP","U.S. Navy"}, {"TST","Transtream Inc"}, {"TSV","TRANSVIDEO"}, {"TSY","TouchSystems"}, {"TTA","Topson Technology Co., Ltd."}, {"TTB","National Semiconductor Japan Ltd"}, {"TTC","Telecommunications Techniques Corporation"}, {"TTE","TTE, Inc."}, {"TTI","Trenton Terminals Inc"}, {"TTK","Totoku Electric Company Ltd"}, {"TTL","2-Tel B.V."}, {"TTS","TechnoTrend Systemtechnik GmbH"}, {"TTY","TRIDELITY Display Solutions GmbH"}, {"TUA ","T+A elektroakustik GmbH"}, {"TUT","Tut Systems"}, {"TVD","Tecnovision"}, {"TVI","Truevision"}, {"TVM","Taiwan Video & Monitor Corporation"}, {"TVO","TV One Ltd"}, {"TVR","TV Interactive Corporation"}, {"TVS","TVS Electronics Limited"}, {"TVV","TV1 GmbH"}, {"TWA","Tidewater Association"}, {"TWE","Kontron Electronik"}, {"TWH","Twinhead International Corporation"}, {"TWI","Easytel oy"}, {"TWK","TOWITOKO electronics GmbH"}, {"TWX","TEKWorx Limited"}, {"TXL","Trixel Ltd"}, {"TXN","Texas Insturments"}, {"TXT","Textron Defense System"}, {"TYN","Tyan Computer Corporation"}, {"UAS","Ultima Associates Pte Ltd"}, {"UBI","Ungermann-Bass Inc"}, {"UBL","Ubinetics Ltd."}, {"UDN","Uniden Corporation"}, {"UEC","Ultima Electronics Corporation"}, {"UEG","Elitegroup Computer Systems Company Ltd"}, {"UEI","Universal Electronics Inc"}, {"UET","Universal Empowering Technologies"}, {"UFG","UNIGRAF-USA"}, {"UFO","UFO Systems Inc"}, {"UHB","XOCECO"}, {"UIC","Uniform Industrial Corporation"}, {"UJR","Ueda Japan Radio Co., Ltd."}, {"ULT","Ultra Network Tech"}, {"UMC","United Microelectr Corporation"}, {"UMG","Umezawa Giken Co.,Ltd"}, {"UMM","Universal Multimedia"}, {"UNA","Unisys DSD"}, {"UNB","Unisys Corporation"}, {"UNC","Unisys Corporation"}, {"UNI","Uniform Industry Corp."}, {"UNI","Unisys Corporation"}, {"UNK","Unknown"}, {"UNM","Unisys Corporation"}, {"UNO","Unisys Corporation"}, {"UNP","Unitop"}, {"UNS","Unisys Corporation"}, {"UNT","Unisys Corporation"}, {"UNY","Unicate"}, {"UPP","UPPI"}, {"UPS","Systems Enhancement"}, {"URD","Video Computer S.p.A."}, {"USA","Utimaco Safeware AG"}, {"USD","U.S. Digital Corporation"}, {"USI","Universal Scientific Industrial Co., Ltd."}, {"USR","U.S. Robotics Inc"}, {"UTD","Up to Date Tech"}, {"UWC","Uniwill Computer Corp."}, {"VAD","Vaddio, LLC"}, {"VAL","Valence Computing Corporation"}, {"VAR","Varian Australia Pty Ltd"}, {"VBR","VBrick Systems Inc."}, {"VBT","Valley Board Ltda"}, {"VCC","Virtual Computer Corporation"}, {"VCI","VistaCom Inc"}, {"VCJ","Victor Company of Japan, Limited"}, {"VCM","Vector Magnetics, LLC"}, {"VCX","VCONEX"}, {"VDA","Victor Data Systems"}, {"VDC","VDC Display Systems"}, {"VDM","Vadem"}, {"VDO","Video & Display Oriented Corporation"}, {"VDS","Vidisys GmbH & Company"}, {"VDT","Viditec, Inc."}, {"VEC","Vector Informatik GmbH"}, {"VEK","Vektrex"}, {"VES","Vestel Elektronik Sanayi ve Ticaret A. S."}, {"VFI","VeriFone Inc"}, {"VHI","Macrocad Development Inc."}, {"VIA","VIA Tech Inc"}, {"VIB","Tatung UK Ltd"}, {"VIC","Victron B.V."}, {"VID","Ingram Macrotron Germany"}, {"VIK","Viking Connectors"}, {"VIM","Via Mons Ltd."}, {"VIN","Vine Micros Ltd"}, {"VIR","Visual Interface, Inc"}, {"VIS","Visioneer"}, {"VIT","Visitech AS"}, {"VIZ","VIZIO, Inc"}, {"VLB","ValleyBoard Ltda."}, {"VLK","Vislink International Ltd"}, {"VLT","VideoLan Technologies"}, {"VMI","Vermont Microsystems"}, {"VML","Vine Micros Limited"}, {"VMW","VMware Inc.,"}, {"VNC","Vinca Corporation"}, {"VOB","MaxData Computer AG"}, {"VPI","Video Products Inc"}, {"VPR","Best Buy"}, {"VQ@","Vision Quest"}, {"VRC","Virtual Resources Corporation"}, {"VSC","ViewSonic Corporation"}, {"VSD","3M"}, {"VSI","VideoServer"}, {"VSN","Ingram Macrotron"}, {"VSP","Vision Systems GmbH"}, {"VSR","V-Star Electronics Inc."}, {"VTC","VTel Corporation"}, {"VTG","Voice Technologies Group Inc"}, {"VTI","VLSI Tech Inc"}, {"VTK","Viewteck Co., Ltd."}, {"VTL","Vivid Technology Pte Ltd"}, {"VTM","Miltope Corporation"}, {"VTN","VIDEOTRON CORP."}, {"VTS","VTech Computers Ltd"}, {"VTV","VATIV Technologies"}, {"VTX","Vestax Corporation"}, {"VUT","Vutrix {UK} Ltd"}, {"VWB","Vweb Corp."}, {"WAC","Wacom Tech"}, {"WAL","Wave Access"}, {"WAV","Wavephore"}, {"WBN","MicroSoftWare"}, {"WBS","WB Systemtechnik GmbH"}, {"WCI","Wisecom Inc"}, {"WCS","Woodwind Communications Systems Inc"}, {"WDC","Western Digital"}, {"WDE","Westinghouse Digital Electronics"}, {"WEB","WebGear Inc"}, {"WEC","Winbond Electronics Corporation"}, {"WEL ","W-DEV"}, {"WEY","WEY Design AG"}, {"WHI","Whistle Communications"}, {"WII","Innoware Inc"}, {"WIL","WIPRO Information Technology Ltd"}, {"WIN","Wintop Technology Inc"}, {"WIP","Wipro Infotech"}, {"WKH","Uni-Take Int'l Inc."}, {"WLD","Wildfire Communications Inc"}, {"WML","Wolfson Microelectronics Ltd"}, {"WMO","Westermo Teleindustri AB"}, {"WMT","Winmate Communication Inc"}, {"WNI","WillNet Inc."}, {"WNV","Winnov L.P."}, {"WNX","Wincor Nixdorf International GmbH"}, {"WPA","Matsushita Communication Industrial Co., Ltd."}, {"WPI","Wearnes Peripherals International {Pte} Ltd"}, {"WRC","WiNRADiO Communications"}, {"WSC","CIS Technology Inc"}, {"WSP","Wireless And Smart Products Inc."}, {"WST","Wistron Corporation"}, {"WTC","ACC Microelectronics"}, {"WTI","WorkStation Tech"}, {"WTK","Wearnes Thakral Pte"}, {"WTS","Restek Electric Company Ltd"}, {"WVM","Wave Systems Corporation"}, {"WVV","WolfVision GmbH"}, {"WWV","World Wide Video, Inc."}, {"WXT","Woxter Technology Co. Ltd"}, {"WYS","Myse Technology"}, {"WYT","Wooyoung Image & Information Co.,Ltd."}, {"XAC","XAC Automation Corp"}, {"XAD","Alpha Data"}, {"XDM","XDM Ltd."}, {"XFG","Jan Strapko - FOTO"}, {"XFO","EXFO Electro Optical Engineering"}, {"XIN","Xinex Networks Inc"}, {"XIO","Xiotech Corporation"}, {"XIR","Xirocm Inc"}, {"XIT","Xitel Pty ltd"}, {"XLX","Xilinx, Inc."}, {"XMM","C3PO S.L."}, {"XNT","XN Technologies, Inc."}, {"XQU","SHANGHAI SVA-DAV ELECTRONICS CO., LTD"}, {"XRC","Xircom Inc"}, {"XRO","XORO ELECTRONICS {CHENGDU} LIMITED"}, {"XSN","Xscreen AS"}, {"XST","XS Technologies Inc"}, {"XSY","XSYS"}, {"XTD","Icuiti Corporation"}, {"XTE","X2E GmbH"}, {"XTL","Crystal Computer"}, {"XTN","X-10 {USA} Inc"}, {"XYC","Xycotec Computer GmbH"}, {"YED","Y-E Data Inc"}, {"YHQ","Yokogawa Electric Corporation"}, {"YHW","Exacom SA"}, {"YMH","Yamaha Corporation"}, {"YOW","American Biometric Company"}, {"ZAN","Zandar Technologies plc"}, {"ZAX","Zefiro Acoustics"}, {"ZAZ","Zazzle Technologies"}, {"ZBR","Zebra Technologies International, LLC"}, {"ZCT","ZeitControl cardsystems GmbH"}, {"ZDS","Zenith Data Systems"}, {"ZGT","Zenith Data Systems"}, {"ZIC","Nationz Technologies Inc."}, {"ZMT","Zalman Tech Co., Ltd."}, {"ZMZ","Z Microsystems"}, {"ZNI","Zetinet Inc"}, {"ZNX","Znyx Adv. Systems"}, {"ZOW","Zowie Intertainment, Inc"}, {"ZRN","Zoran Corporation"}, {"ZSE","Zenith Data Systems"}, {"ZTC","ZyDAS Technology Corporation"}, {"ZTE","ZTE Corporation"}, {"ZTI","Zoom Telephonics Inc"}, {"ZTM","ZT Group Int'l Inc."}, {"ZTT","Z3 Technology"}, {"ZYD","Zydacron Inc"}, {"ZYP","Zypcom Inc"}, {"ZYT","Zytex Computers"}, {"ZYX","Zyxel"}, {"ZZZ","Boca Research Inc"} }; const int pnp_table_size = sizeof(pnp_id_table) / sizeof(Pnp_Id_Table_Entry); // ARRAY_SIZE(pnp_id_table); static char * pnp_name0(char * id, int first, int last) { bool debug = false; if (debug) printf("(%s) Starting, id=%s, first=%d, last=%d\n", __func__, id, first, last); char * result = "UNK"; if (first <= last && first >= 0 && last < pnp_table_size) { if (debug) printf("(%s) mfg_code[%d] = %s, mfg_code[%d] = %s\n", __func__, first, pnp_id_table[first].mfg_name, last, pnp_id_table[last].mfg_name); int middle = (last-first)/2 + first; int cmprc = strcmp(id,pnp_id_table[middle].mfg_code); if (cmprc == 0) result = pnp_id_table[middle].mfg_name; else if (cmprc < 0) result = pnp_name0(id, first, middle-1); else result = pnp_name0(id, middle+1, last); } if (debug) printf("(%s) Done. Returning: %s\n", __func__, result); return result; } /** Returns the name associated with a 3 character manufacturer id. * * \param id manufacturer id * \param manufacturer name, or "UNK" if not found */ char * pnp_name(char * id) { char * result = NULL; strupper(id); // "inu" is a lower case code result = pnp_name0(id, 0, pnp_table_size-1); return result; } #ifdef TESTS static void one_pnp_test(char * id, char * expected) { printf("(%s) pnp_table_size=%d\n", __func__, pnp_table_size); printf("(%s) Starting id = %s\n", __func__, id); char * name = pnp_name(id); char * expect = (expected) ? expected : "UNK"; printf("(%s) Done Expected: %s, Returning: %s\n", __func__, expect, name); } void pnp_id_tests() { one_pnp_test("123", NULL); one_pnp_test("abc", NULL); one_pnp_test("AAA", "Avolites Ltd"); one_pnp_test("ZZZ", "Boca Research Inc"); one_pnp_test("ZYZ", NULL); // no existant one_pnp_test("ZYX", "Zyxel"); // second last one_pnp_test("AAB", NULL); // not exist one_pnp_test("AAE", "Anatek Electronics Inc."); one_pnp_test("VCX", "VCONEX"); one_pnp_test("UFH", NULL); // does not exist } #endif ddcutil-2.2.0/src/util/regex_util.c0000644000175000001440000001415314754153540012713 /** @file regex_util.c */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include "debug_util.h" #include "report_util.h" #include "regex_util.h" #include "string_util.h" #include "sysfs_util.h" // // Store compiled regular expressions // static GHashTable * regex_hash_table = NULL; static GMutex regex_hash_table_mutex; // GDestroyNotify void (*GDestroyNotify) (gpointer data); void destroy_regex(gpointer data) { // printf("(%s) Destroying compiled regex at %p\n", __func__, data); regfree( (regex_t*) data ); free(data); // ??? } GHashTable* get_regex_hash_table() { // printf("(%s) Starting. regex_hash_table = %p\n", __func__, regex_hash_table); if (!regex_hash_table) regex_hash_table = g_hash_table_new_full( g_str_hash, // GHashFunc hash_func, g_str_equal, // GEqualFunc key_equal_func, g_free, // GDestroyNotify key_destroy_func, destroy_regex); // GDestroyNotify value_destroy_func // printf("(%s) Done. Returning regex_hash_table = %p\n", __func__, regex_hash_table); return regex_hash_table; } void dbgrpt_regex_hash_table() { if (regex_hash_table) { GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, regex_hash_table); while (g_hash_table_iter_next(&iter, &key, &value)) { rpt_vstring(2, " %p->\"%s\" : %p", key, (char *) key, value); } } else rpt_vstring(1, "regex_hash_table not allocated"); } void free_regex_hash_table() { bool debug = false; if (debug) printf("(%s) Starting. regex_hash_table=%p\n", __func__, (void*)regex_hash_table); if (regex_hash_table) { if (debug) { printf("(%s) Hash table contents:\n", __func__); dbgrpt_regex_hash_table(regex_hash_table); } g_hash_table_destroy(regex_hash_table); regex_hash_table = NULL; } if (debug) printf("(%s) Done.\n", __func__); } static void save_compiled_regex(const char * pattern, regex_t * compiled_re) { bool debug = false; if (debug) printf("(%s) Starting. pattern = |%s|, compiled_re=%p\n", __func__, pattern, (void*)compiled_re); GHashTable * regex_hash = get_regex_hash_table(); g_hash_table_replace(regex_hash, g_strdup( pattern), compiled_re); if (debug) printf("(%s) Done.\n", __func__); } static regex_t * get_compiled_regex(const char * pattern) { bool debug = false; if (debug) printf("(%s) Starting. pattern = |%s|\n", __func__, pattern); GHashTable * regex_hash = get_regex_hash_table(); regex_t * result = g_hash_table_lookup(regex_hash, pattern); if (debug) printf("(%s) Returning %p. pattern = |%s|\n", __func__, (void*)result, pattern); return result; } // #ifdef FUTURE // requires testing bool eval_regex_with_matches( regex_t * re, const char * value, size_t max_matches, regmatch_t * pm ) { bool debug = false; if (debug) printf("(%s) Starting. re=%p, value=|%s|\n", __func__, (void*)re, value); int rc = regexec( re, /* the compiled pattern */ value, /* the subject string */ max_matches, pm, 0 ); bool result = (rc == 0) ? true : false; if (debug) printf("(%s) Returning %s. value=|%s|, regexec() returned %d\n", __func__, sbool(result), value, rc); return result; } // #endif static bool eval_regex(regex_t * re, const char * value) { bool debug = false; if (debug) printf("(%s) Starting. re=%p, value=|%s|\n", __func__, (void*)re, value); int rc = regexec( re, /* the compiled pattern */ value, /* the subject string */ 0, NULL, 0 ); bool result = (rc == 0) ? true : false; if (debug) printf("(%s) Returning %s. value=|%s|, regexec() returned %d\n", __func__, sbool(result), value, rc); return result; } bool compile_and_eval_regex(const char * pattern, const char * value) { bool debug = false; if (debug) printf("(%s) Starting. pattern=|%s|, value=|%s|\n", __func__, pattern, value); g_mutex_lock(®ex_hash_table_mutex); regex_t * re = get_compiled_regex(pattern); // printf("(%s) forcing re = NULL\n", __func__); // re = NULL; if (!re) { re = calloc(1, sizeof(regex_t)); if (debug) printf("(%s) Allocated regex %p, compiling...\n", __func__, (void*)re); int rc = regcomp(re, pattern, REG_EXTENDED); if (rc != 0) { printf("(%s) regcomp() returned %d\n", __func__, rc); assert(rc == 0); } save_compiled_regex(pattern, re); } g_mutex_unlock(®ex_hash_table_mutex); bool result = eval_regex(re, value); if (debug) printf("(%s) Done. Returning %s\n", __func__, sbool(result)); return result; } bool compile_and_eval_regex_with_matches( const char * pattern, const char * value, size_t max_matches, regmatch_t * pm) { bool debug = false; if (debug) printf("(%s) Starting. pattern=|%s|, value=|%s|\n", __func__, pattern, value); g_mutex_lock(®ex_hash_table_mutex); regex_t * re = get_compiled_regex(pattern); // printf("(%s) forcing re = NULL\n", __func__); // re = NULL; if (!re) { re = calloc(1, sizeof(regex_t)); if (debug) printf("(%s) Allocated regex %p, compiling...\n", __func__, (void*)re); int rc = regcomp(re, pattern, REG_EXTENDED); if (rc != 0) { printf("(%s) regcomp() returned %d\n", __func__, rc); assert(rc == 0); } save_compiled_regex(pattern, re); } g_mutex_unlock(®ex_hash_table_mutex); bool result = eval_regex_with_matches(re, value, max_matches, pm); if (debug) printf("(%s) Done. Returning %s\n", __func__, sbool(result)); return result; } ddcutil-2.2.0/src/util/report_util.c0000644000175000001440000007154114754153540013120 /** @file report_util.c * * Functions for creating messages in a standardized format, with flexible * indentation. * * The functions in this source file are thread safe. * * TODO: describe * - indentation depth * - indentation stack * - destination stack */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include /** \endcond */ #include "coredefs_base.h" #include "file_util_base.h" #include "msg_util.h" #include "string_util.h" #include "report_util.h" bool redirect_reports_to_syslog = false; bool tag_output = false; static bool default_prefix_report_output = false; /** Sets the initial report ornamentation status. * * Note this does not change the ornamentation status for existing threads. * * @param output_dest default output destination */ void rpt_set_default_ornamentation_enabled(bool onoff) { default_prefix_report_output = onoff; } #define DEFAULT_INDENT_SPACES_PER_DEPTH 3 #define INDENT_SPACES_STACK_SIZE 16 #define OUTPUT_DEST_STACK_SIZE 8 #ifdef OLD static int indent_spaces_stack[INDENT_SPACES_STACK_SIZE]; static int indent_spaces_stack_pos = -1; static FILE* output_dest_stack[OUTPUT_DEST_STACK_SIZE]; static int output_dest_stack_pos = -1; // work around for fact that can't initialize the initial stack entry to stdout static FILE* alt_initial_output_dest = NULL; static bool initial_output_dest_changed = false; #endif static FILE* default_output_dest; /** Sets the initial report output destination for newly created threads. * * Note this does not change the report output destination for existing threads. * * @param output_dest default output destination */ void rpt_set_default_output_dest(FILE* output_dest) { default_output_dest = output_dest; } //* Thread specific state */ typedef struct { uint8_t indent_spaces_stack[INDENT_SPACES_STACK_SIZE]; int indent_spaces_stack_pos; // initial -1; FILE* output_dest_stack[OUTPUT_DEST_STACK_SIZE]; int output_dest_stack_pos; // initial -1; // work around for fact that can't initialize the initial stack entry to stdout FILE* alt_initial_output_dest; // initial NULL; bool initial_output_dest_changed; // initial false; bool prefix_report_output; // initial false // bool temporary_reports_to_syslog; // initial false } Per_Thread_Settings; /** Returns a struct for maintaining thread-specific settings * @return thread-specific struct of global settings */ static Per_Thread_Settings * get_thread_settings() { static GPrivate per_thread_settings_key = G_PRIVATE_INIT(g_free); Per_Thread_Settings* settings = g_private_get(&per_thread_settings_key); // GThread * this_thread = g_thread_self(); // printf("(%s) this_thread=%p, settings=%p\n", __func__, this_thread, settings); if (!settings) { settings = g_new0(Per_Thread_Settings, 1); settings->indent_spaces_stack_pos = -1; settings->output_dest_stack_pos = -1; settings->prefix_report_output = default_prefix_report_output; if (default_output_dest) settings->output_dest_stack[++settings->output_dest_stack_pos] = default_output_dest; g_private_set(&per_thread_settings_key, settings); } // printf("(%s) Returning: %p\n", __func__, settings); return settings; } // // Ornamentation control // bool rpt_get_ornamentation_enabled() { Per_Thread_Settings * settings = get_thread_settings(); return settings->prefix_report_output; } bool rpt_set_ornamentation_enabled(bool enabled) { Per_Thread_Settings * settings = get_thread_settings(); bool old = settings->prefix_report_output; settings->prefix_report_output = enabled; return old; } // // Indentation // // Functions that allow for temporarily changing the number of indentation // spaces per logical indentation depth on the current thread. // 10/16/15: not currently used /** Sets the spaces-per-indentation-depth to be used for report functions. * The current spaces-per-depth is saved on the thread-specific spaces-per-depth stack. * * @param new_dest new output destination */ void rpt_push_indent(int new_spaces_per_depth) { Per_Thread_Settings * settings = get_thread_settings(); assert(settings->indent_spaces_stack_pos < INDENT_SPACES_STACK_SIZE-1); settings->indent_spaces_stack[++settings->indent_spaces_stack_pos] = new_spaces_per_depth; } /** Pops the space-per-indentation-depth stack. * * @remark * No effect if stack is empty. */ void rpt_pop_indent() { Per_Thread_Settings * settings = get_thread_settings(); if (settings->indent_spaces_stack_pos >= 0) settings->indent_spaces_stack_pos--; } /** Empties the space-per-indentation-depth stack. * * The effect is to reset the per-thread spaces-per-indentation-depth * to its default value. */ void rpt_reset_indent_stack() { Per_Thread_Settings * settings = get_thread_settings(); settings->indent_spaces_stack_pos = -1; } /** Given a logical indentation depth, returns the number of spaces * of indentation to be used. * * @param depth logical indentation depth, if < 0 perform no indentation * @return number of indentation spaces */ int rpt_get_indent(int depth) { if (depth < 0) depth = 0; Per_Thread_Settings * settings = get_thread_settings(); int spaces_ct = DEFAULT_INDENT_SPACES_PER_DEPTH; if (settings->indent_spaces_stack_pos >= 0) spaces_ct = settings->indent_spaces_stack[settings->indent_spaces_stack_pos]; return depth * spaces_ct; } // Functions that allow for temporarily changing the output destination // on the current thread. /** Sets the output destination to be used for report functions. * The current output destination is saved on the output destination stack. * * @param new_dest new output destination */ void rpt_push_output_dest(FILE* new_dest) { Per_Thread_Settings * settings = get_thread_settings(); assert(settings->output_dest_stack_pos < OUTPUT_DEST_STACK_SIZE-1); settings->output_dest_stack[++settings->output_dest_stack_pos] = new_dest; } /** Pops the output destination stack, and sets the output destination * to be used for report functions to the new top of the stack. */ void rpt_pop_output_dest() { Per_Thread_Settings * settings = get_thread_settings(); if (settings->output_dest_stack_pos >= 0) settings->output_dest_stack_pos--; } /** Clears the output destination stack. * The output destination to be used for report functions to the default (stdout). */ void rpt_reset_output_dest_stack() { Per_Thread_Settings * settings = get_thread_settings(); settings->output_dest_stack_pos = -1; } /** Gets the current output destination. * * @return current output destination */ FILE * rpt_cur_output_dest() { Per_Thread_Settings * settings = get_thread_settings(); // special handling for unpushed case because can't statically initialize // output_dest_stack[0] to stdout FILE * result = NULL; if (settings->output_dest_stack_pos < 0) result = (settings->initial_output_dest_changed) ? settings->alt_initial_output_dest : stdout; else result = settings->output_dest_stack[settings->output_dest_stack_pos]; return result; } /** Debugging function to show output destination. */ void rpt_debug_output_dest() { Per_Thread_Settings * settings = get_thread_settings(); FILE * dest = rpt_cur_output_dest(); char * addl = (dest == stdout) ? " (stdout)" : ""; printf("(%s) output_dest_stack[%d] = %p %s\n", __func__, settings->output_dest_stack_pos, (void*)dest, addl); } /** Changes the current output destination, without saving * the current output destination on the destination stack. * * @param new_dest new output destination * * @remark Needed for set_fout() in core.c */ void rpt_change_output_dest(FILE* new_dest) { Per_Thread_Settings * settings = get_thread_settings(); if (settings->output_dest_stack_pos >= 0) settings->output_dest_stack[settings->output_dest_stack_pos] = new_dest; else { settings->initial_output_dest_changed = true; settings->alt_initial_output_dest = new_dest; } } #ifdef MAYBE_FUTURE bool rpt_set_reports_to_syslog_override(bool onoff) { Per_Thread_Settings * settings = get_thread_settings(); bool old = settings->temporary_reports_to_syslog; settings->temporary_reports_to_syslog = onoff; return old; } #endif // should not be needed, for diagnosing a problem void rpt_flush() { if (!redirect_reports_to_syslog) fflush(rpt_cur_output_dest()); } /** Writes a newline to the current output destination. */ void rpt_nl() { if (redirect_reports_to_syslog) syslog(LOG_NOTICE, "\n"); else f0printf(rpt_cur_output_dest(), "\n"); } /** Writes a constant string to the current output destination, or adds * the string to a specified GPtrArray. * * A newline is appended to the string specified. * * The output is indented per the specified indentation depth. * * @param title string to write * @param collector if non-NULL, add string to this GPtrArray instead of * writing it to the current output destination * @param depth logical indentation depth. * * @remark This is the core function through which all output is funneled. */ void rpt_title_collect(const char * title, GPtrArray * collector, int depth) { bool debug = false; if (debug) printf("(%s) Writing to %p\n", __func__, (void*)rpt_cur_output_dest()); char prefix[100] = {0}; if (rpt_get_ornamentation_enabled()) get_msg_decoration(prefix, 100, redirect_reports_to_syslog); if (collector) { g_ptr_array_add(collector, g_strdup_printf("%*s%s", rpt_get_indent(depth), "", title)); } else { if (depth >= 0) { if (redirect_reports_to_syslog) syslog(LOG_NOTICE, "%s%*s%s%s", prefix, rpt_get_indent(depth), "", title, (tag_output) ? " (I)" : ""); else f0printf(rpt_cur_output_dest(), "%s%*s%s\n", prefix, rpt_get_indent(depth), "", title); } } } /** Writes a constant string to the current output destination. * * A newline is appended to the string specified. * * The output is indented per the specified indentation depth. * * @param title string to write * @param depth logical indentation depth. */ void rpt_title(const char * title, int depth) { rpt_title_collect(title, NULL, depth); } /** Writes a constant string to the current output destination, or * adds it to a GPtrArray if one is given. * * A newline is appended to the string specified. * * The output is indented per the specified indentation depth. * * @param depth logical indentation depth. * @param collector if non-NULL, append string to this GPtrArray * instead of writing it to the current output device * @param title string to write */ void rpt_label_collect(int depth, GPtrArray * collector, const char * text) { rpt_title_collect(text, collector, depth); } /** Writes a constant string to the current output destination. * * A newline is appended to the string specified. * * The output is indented per the specified indentation depth. * * @param depth logical indentation depth. * @param title string to write * * @remark * This function is logically equivalent to #rpt_title(), except that * the **depth** parameter is first, not last. * Experience wih the API has shown that #rpt_title() tends not to be * used along with #rpt_vstring() because the different position of the * **depth** parameter makes the code harder to read. */ void rpt_label(int depth, const char * text) { rpt_title(text, depth); } /** Writes a formatted string to the current output destination. * * A newline is appended to the string specified * * @param depth logical indentation depth * @param format format string (normal printf) * @param ... arguments * * @remark Note that the depth parm is first on this function because of variable args */ void rpt_vstring(int depth, char * format, ...) { int buffer_size = 200; char buffer[buffer_size]; char * buf = buffer; va_list(args); va_start(args, format); int reqd_size = vsnprintf(buffer, buffer_size, format, args); // if buffer wasn't sufficiently large, allocate a temporary buffer if (reqd_size >= buffer_size) { // printf("(%s) Allocating temp buffer, reqd_size=%d\n", __func__, reqd_size); buf = malloc(reqd_size+1); va_start(args, format); vsnprintf(buf, reqd_size+1, format, args); } va_end(args); rpt_title(buf, depth); if (buf != buffer) free(buf); } /** Writes a formatted string to the current output destination, or * adds the string to a collector array. * * A newline is appended to the string specified * * @param depth logical indentation depth * @param collector if non-NULL, add string to GPtrArray instead of * writing to current output destination * @param format format string (normal printf argument) * @param ap va_list array of arguments * * @remark Note that the depth parm is first on this function because of variable args */ void vrpt_vstring_collect(int depth, GPtrArray * collector, char * format, va_list ap) { char * s = g_strdup_vprintf(format, ap); rpt_title_collect(s, collector, depth); free(s); } /** Writes a formatted string to the current output destination. * * A newline is appended to the string specified * * @param depth logical indentation depth * @param collector if non-NULL, add string to GPtrArray instead of * writing to current output destination * @param format format string (normal printf argument) * @param ... arguments * * @remark Note that the depth parm is first on this function because of variable args */ void rpt_vstring_collect(int depth, GPtrArray* collector, char * format, ...) { va_list(args); va_start(args, format); vrpt_vstring_collect(depth, collector, format, args); va_end(args); } /** Convenience function that writes multiple constant strings. * * @param depth logical indentation depth * @param ... pointers to constant strings, * last pointer is NULL to terminate list */ void rpt_multiline(int depth, ...) { va_list args; va_start(args, depth); char * s = NULL; while( (s = va_arg(args, char *)) != NULL) { rpt_title(s, depth); } va_end(args); } /** Writes all strings in a GPtrArray to the current report destination * * @param depth logical indentation depth * @param strings pointer to GPtrArray of strings */ void rpt_g_ptr_array(int depth, GPtrArray * strings) { for (int ndx = 0; ndx < strings->len; ndx++) { char * s = g_ptr_array_index(strings, ndx); rpt_title(s, depth); } } /** Writes a hex dump with indentation. * Output is written to the current report destination * * @param data start of bytes to dump * @param size number of bytes to dump * @param depth logical indentation depth */ void rpt_hex_dump(const Byte * data, int size, int depth) { if (redirect_reports_to_syslog) { GPtrArray * collector = g_ptr_array_new_with_free_func(g_free); hex_dump_indented_collect(collector, data, size, rpt_get_indent(depth)); for (int ndx = 0; ndx < collector->len; collector++) { syslog(LOG_NOTICE, "%s", (char*) g_ptr_array_index(collector, ndx)); } g_ptr_array_free(collector, true); } else fhex_dump_indented(rpt_cur_output_dest(), data, size, rpt_get_indent(depth)); } /** Writes a Null_Terminated_String_Array with indentation. * Output is written to the current report destination. * * @param ntsa array to report * @param depth logical indentation depth */ void rpt_ntsa(Null_Terminated_String_Array ntsa, int depth) { assert(ntsa); for (int ndx=0; ntsa[ndx]; ndx++) { rpt_vstring(depth, "%s", ntsa[ndx]); } } /** Writes a string to the current output destination, describing a pointer * to a named data structure. * * The output is indented per the specified indentation depth. * * @param name struct name * @param ptr pointer to struc * @param depth logical indentation depth */ void rpt_structure_loc(const char * name, const void * ptr, int depth) { // fprintf(rpt_cur_output_dest(), "%*s%s at: %p\n", rpt_indent(depth), "", name, ptr); rpt_vstring(depth, "%s at: %p", name, ptr); } /** Writes a pair of strings to the current output destination. * * If offset_absolute is true, then the s2 value will start in the same column, * irrespective of the line indentation. This may make some reports easier to read. * * @param s1 first string * @param s2 second string * @param col2offset offset from start of line where s2 starts * @param offset_absolute if true, col2offset is relative to the start of the line, before indentation * if false, col2offset is relative to the indented start of s1 * @param depth logical indentation depth */ void rpt_2col(char * s1, char * s2, int col2offset, bool offset_absolute, int depth) { int col1sz = col2offset; int indentct = rpt_get_indent(depth); if (offset_absolute) col1sz = col1sz - indentct; rpt_vstring(depth, "%-*s%s", col1sz, s1, s2 ); } /** Reports the contents of a file. * * @param fn name of file * @param verbose if true, emit message if error reading file * @param depth logical indentation depth * @retval >=0 number of lines read * @retval <0 -errno from fopen() or getline() */ int rpt_file_contents(const char * fn, bool verbose, int depth) { GPtrArray * line_array = g_ptr_array_new(); g_ptr_array_set_free_func(line_array, g_free); int rc = file_getlines(fn, line_array, false); if (rc < 0) { if (verbose) rpt_vstring(depth, "Error reading file %s: %s", fn, strerror(-rc)); } else if (rc == 0) { if (verbose) rpt_vstring(depth, "Empty file: %s", fn); } else if (rc > 0) { int ndx = 0; for (; ndx < line_array->len; ndx++) { char * curline = g_ptr_array_index(line_array, ndx); // trim_in_place(curline); // strip trailing newline - now done in file_getlines() rpt_title(curline, depth); } } g_ptr_array_free(line_array, true); return rc; } /* The remaining rpt_ functions various data types share a common formatting so that they can * be use together. All channel their output through rpt_str(). * * Depending on whether the info parm is null, output takes one of the following forms: * name (info) : value * name : value */ /** Writes a string to the current output destination describing a named character string value. * * The output is indented per the specified indentation depth. * * Optionally, a description string can be specified along with the name. * The description string will be surrounded by parentheses. * * The string value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val string value * @param depth logical indentation depth */ void rpt_str(const char * name, char * info, const char * val, int depth) { bool debug = false; if (debug) printf("(%s) Writing to %p\n", __func__, (void*)rpt_cur_output_dest()); char infobuf[100]; if (info) snprintf(infobuf, 99, "(%s)", info); else infobuf[0] = '\0'; rpt_vstring(depth, "%-25s %30s : %s", name, infobuf, val); } /** Writes a string to the current output destination describing a boolean value. * * The value is displayed as "true" or "false". * * The output is indented per the specified indentation depth. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val value to show * @param depth logical indentation depth * * The value is formatted as "true" or "false". */ void rpt_bool(char * name, char * info, bool val, int depth) { char * valName = (val) ? "true" : "false"; rpt_str(name, info, valName, depth); } /** Writes a string to the current output destination, describing a named integer value. * * The output is indented per the specified indentation depth. * * Optionally, a description string can be specified along with the name. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val integer value * @param depth logical indentation depth */ void rpt_int(char * name, char * info, int val, int depth) { char buf[10]; snprintf(buf, 9, "%d", val); rpt_str(name, info, buf, depth); } /** Writes a string to the current output destination, describing a named unsigned integer value. * * The output is indented per the specified indentation depth. * * Optionally, a description string can be specified along with the name. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val unsigned integer value * @param depth logical indentation depth */ void rpt_unsigned(char * name, char * info, int val, int depth) { char buf[10]; snprintf(buf, 9, "%u", val); rpt_str(name, info, buf, depth); } /** Writes a string to the current output destination describing a 4 byte integer value, * indented per the specified indentation depth. * * The integer value is formatted as printable hex. * * Optionally, a description string can be specified along with the name. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val integer value * @param depth logical indentation depth */ void rpt_int_as_hex(char * name, char * info, int val, int depth) { char buf[16]; snprintf(buf, 15, "0x%08x", val); rpt_str(name, info, buf, depth); } /** Writes a string to the current output destination describing a single byte value, * indented per the specified indentation depth. * * The value is formatted as printable hex. * * Optionally, a description string can be specified along with the name. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val value * @param depth logical indentation depth */ void rpt_uint8_as_hex(char * name, char * info, unsigned char val, int depth) { char buf[16]; snprintf(buf, 15, "0x%02x", val); rpt_str(name, info, buf, depth); } /** Writes a string to the current output destination describing a named integer * value having a symbolic string representation. * * The output is indented per the specified indentation depth. * * The integer value is converted to a string using the specified function. * * Optionally, a description string can be specified along with the name. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val integer value * @param func interpretation function * @param depth logical indentation depth */ void rpt_mapped_int(char * name, char * info, int val, Value_To_Name_Function func, int depth) { char * valueName = func(val); char buf[100]; snprintf(buf, 100, "%d - %s", val, valueName); rpt_str(name, info, buf, depth); } /** Writes a string to the current output destination describing a sequence of bytes, * indented per the specified indentation depth. * * The value is formatted as printable hex. * * Optionally, a description string can be specified along with the name. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param bytes pointer to start of bytes to show * @param ct number of bytes to show * @param hex_prefix_flag if true, the printable hex value will begin with "0x" * @param depth logical indentation depth */ void rpt_bytes_as_hex( const char * name, char * info, Byte * bytes, int ct, bool hex_prefix_flag, int depth) { // printf("(%s) bytes=%p, ct=%d\n", __func__, bytes, ct); int bufsz = 2*ct + 1; bufsz++; // hack if (hex_prefix_flag) bufsz += 2; char * buf = malloc(bufsz); char * hex_prefix = (hex_prefix_flag) ? "0x" : ""; char * hs = hexstring(bytes, ct); snprintf(buf, bufsz-1, "%s%s", hex_prefix, hs); rpt_str(name, info, buf, depth); free(buf); free(hs); } // Functions for reporting integers that are collections of named bits #ifdef DEBUG static void report_flag_info( Flag_Info* pflag_info, int depth) { assert(pflag_info); rpt_structure_loc("FlagInfo", pflag_info, depth); int d1 = depth+1; rpt_str( "flag_name", NULL, pflag_info->flag_name, d1); rpt_str( "flag_info", NULL, pflag_info->flag_info, d1); rpt_int_as_hex("flag_val", NULL, pflag_info->flag_val, d1); } /* Function for debugging findFlagInfoDictionary. * * Reports the contents of a FlagDictionay record. */ static void report_flag_info_dictionary(Flag_Dictionary* pDict, int depth) { assert(pDict); rpt_structure_loc("Flag_Dictionary", pDict, depth); int d1 = depth+1; rpt_int("flag_info_ct", NULL, pDict->flag_info_ct, d1); int ndx=0; for(;ndx < pDict->flag_info_ct; ndx++) { report_flag_info(&pDict->flag_info_recs[ndx], d1); } } #endif static Flag_Info * find_flag_info_in_dictionary(char * flag_name, Flag_Dictionary * pdict) { Flag_Info * result = NULL; // printf("(%s) Starting. flag_name=%s, pdict=%p \n", __func__, flagName, pdict ); // printf("(%s) pdict->flag_info_ct=%d \n", __func__, pdict->flag_info_ct ); // report_flag_info_dictionary(pdict, 2); int ndx; for (ndx=0; ndx < pdict->flag_info_ct; ndx++) { // printf("(%s) ndx=%d \n", __func__, ndx ); // Flag_Info pcur_info = &(pdict->flag_info_recs[ndx]); // printf("(%s) pdict->flag_info_recs[ndx].flag_name=%s \n", __func__, pdict->flag_info_recs[ndx].flag_name ); if ( streq(flag_name, pdict->flag_info_recs[ndx].flag_name)) { // printf("(%s) Match \n", __func__ ); result = &pdict->flag_info_recs[ndx]; break; } } // printf("(%s) Returning: %p \n", __func__, result ); return result; } static void char_buf_append(char * buffer, int bufsize, char * val_to_append) { assert(strlen(buffer) + strlen(val_to_append) < bufsize); strcat(buffer, val_to_append); } static void flag_val_to_string_using_dictionary( int flags_val, Flag_Name_Set * pflag_name_set, Flag_Dictionary * pdict, char * buffer, int bufsize ) { // printf("(%s) flagsVal=0x%02x, pflagNameSet=%p, pDict=%p \n", __func__, flagsVal, pflagNameSet, pDict ); // printf("(%s) pflagNameSet->flagNameCt=%d \n", __func__, pflagNameSet->flagNameCt ); // printf("(%s) pDict->flagInfoCt=%d \n", __func__, pDict->flagInfoCt ); assert(buffer && bufsize > 1); buffer[0] = '\0'; int ndx; bool first = true; for (ndx=0; ndx < pflag_name_set->flag_name_ct; ndx++) { Flag_Info * pflag_info = find_flag_info_in_dictionary(pflag_name_set->flag_names[ndx], pdict); // printf("(%s) ndx=%d, pFlagInfp=%p \n", __func__, ndx, pFlagInfo ); if (flags_val & pflag_info->flag_val) { if (first) first = false; else char_buf_append(buffer, bufsize, ", "); char_buf_append(buffer, bufsize, pflag_info->flag_name); } } // printf("(%s) Returning |%s|\n", __func__, buffer ); } /** Writes a string to the current output destination describing an integer * that is to be interpreted as a named collection of named bits. * * Output is indented per the specified indentation depth. * The description string will be surrounded by parentheses. * * The value is prefixed with a colon. * * @param name name of value * @param info if non-null, description of value * @param val value to interpret * @param p_flag_name_set * @param p_dict * @param depth logical indentation depth */ void rpt_ifval2(char* name, char* info, int val, Flag_Name_Set* p_flag_name_set, Flag_Dictionary* p_dict, int depth) { char buf[1000]; buf[0] = '\0'; snprintf(buf, 7, "0x%04x", val); char_buf_append(buf, sizeof(buf), " - "); flag_val_to_string_using_dictionary(val, p_flag_name_set, p_dict, buf, sizeof(buf)); rpt_str(name, info, buf, depth); } ddcutil-2.2.0/src/util/simple_ini_file.c0000644000175000001440000002576514754153540013706 /** @file simple_ini_file.c * * Reads an INI style configuration file */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include #include "debug_util.h" #include "error_info.h" #include "file_util_base.h" #include "string_util.h" #include "xdg_util.h" #include "simple_ini_file.h" static bool is_comment(char * s) { bool debug = false; bool result = false; if (strlen(s) == 0) result = true; else { char ch = s[0]; // DBGMSF(debug, "ch=%c=%d, 0x%02x", ch, (int)ch, ch); // DBGMSF(debug, " %c=%d 0x%02x", ';', (int)';', ';'); if (ch == ';' || ch == '*' || ch == '#') { result = true; } } DBGF(debug, "s: %s, Returning %s", s, SBOOL(result)); return result; } static bool is_segment(char * s, char ** seg_name_loc) { bool debug = false; bool result = false; if (strlen(s) > 0 && *s == '[' && s[strlen(s)-1] == ']') { char * untrimmed = substr(s, 1, strlen(s)-2); // DBGMSF(debug, "untrimmed=|%s|", untrimmed); char * seg_name = strtrim(untrimmed); for (char * p = seg_name; *p; p++) {*p = tolower(*p);} // DBGMSF(debug, "seg_name=|%s|", seg_name); if (strlen(seg_name) > 0) { *seg_name_loc = seg_name; result = true; } else free(seg_name); free(untrimmed); } DBGF(debug, "s: %s, Returning %s", s, SBOOL(result)); return result; } static bool is_kv(char * s, char ** key_loc, char ** value_loc) { bool debug = false; DBGF(debug, "Starting. s->|%s|\n", s); bool result = false; char * colon = strchr(s,':'); if (!colon) colon = strchr(s,'='); if (colon) { char * untrimmed_key = substr(s, 0, colon-s); // allocates untrimmed_key char * key = strtrim( untrimmed_key ); // allocates key for (char *p = key; *p; p++) {*p=tolower(*p);} // DBGMSF(debug, "untrimmed_key = |%s|, key = |%s|", untrimmed_key, key); char * s_end = s + strlen(s); char * v_start = colon+1; char * untrimmed_value = substr(v_start, 0, s_end-v_start); // allocates untrimmed_value char * value = strtrim( untrimmed_value); // allocates value // DBGMSF(debug, "untrimmed_value = |%s|, value = |%s|", untrimmed_value, value); // DBGMSF(debug, "key=|%s|, value=|%s|", key, value); if (strlen(key) > 0) { *key_loc = key; *value_loc = value; result = true; } else { free(key); free(value); } free(untrimmed_key); free(untrimmed_value); } DBGF(debug, "s: |%s|, Returning %s", s, SBOOL(result)); return result; } static void emit_error_msg(GPtrArray * errmsgs, bool debug, char * format, ...) { char buffer[200]; va_list(args); va_start(args, format); vsnprintf(buffer, 100, format, args); va_end(args); if (errmsgs) g_ptr_array_add(errmsgs, g_strdup(buffer)); if (!errmsgs) fprintf(stderr, "%s\n", buffer); } /** Loads an INI style configuration file into a newly allocated #Parsed_Ini_File. * Keys of the hash table in the struct have the form /. * * @param ini_file_name file name * @param errmsgs if non-null, collects per-line error messages * @param parsed_ini_loc where to return newly allocated parsed ini file * @retval 0 success * @retval -ENOENT configuration file not found * @retval -EBADMSG errors parsing configuration file * @retval < 0 errors reading configuration file * * If the configuration file is not found (-ENOENT), or there are errors reading * or parsing the configuration file, *parsed_ini_loc is NULL. * * If errors occur reading or interpreting the file, messages will be added * to **errmsgs**. * * \remark * There's really no appropriate errno value for errors parsing the file, * which is a form of bad data. EBADMSG has been hijacked for this purpose. */ int ini_file_load( const char * ini_file_name, GPtrArray * errmsgs, Parsed_Ini_File** parsed_ini_loc) { bool debug = false; assert(ini_file_name); int result = 0; *parsed_ini_loc = NULL; char * cur_segment = NULL; GHashTable * ini_file_hash = NULL; GPtrArray * config_lines = g_ptr_array_new_with_free_func(g_free); int getlines_rc = file_getlines(ini_file_name, config_lines, debug); DBGF(debug, "file_getlines() returned %d", getlines_rc); if (getlines_rc < 0) { result = getlines_rc; if (getlines_rc != -ENOENT) { emit_error_msg(errmsgs, debug, "Error reading configuration file %s: %s", ini_file_name, strerror(-getlines_rc)); result = -getlines_rc; } } // error reading lines else { //process the lines ini_file_hash = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); int error_ct = 0; DBGF(debug, "config_lines->len = %d", config_lines->len); for (guint ndx = 0; ndx < config_lines->len; ndx++) { char * line = g_ptr_array_index(config_lines, ndx); DBGF(debug, "Processing line %d: |%s|", ndx+1, line); char * trimmed = trim_in_place(line); char * ptr = strchr(trimmed, '#'); if (ptr) { *ptr = '\0'; rtrim_in_place(trimmed); } DBGF(debug, "line=%d. trimmed=|%s|", ndx+1, trimmed); char * seg_name; char * key; char * value; if (is_comment(trimmed)) { } else if (is_segment(trimmed, &seg_name)) { if (cur_segment) free(cur_segment); cur_segment = seg_name; } else if ( is_kv(trimmed, &key, &value) ) { // allocates key, value if (cur_segment) { char * full_key = g_strdup_printf("%s/%s", cur_segment, key); // allocates full_key char * old_value = g_hash_table_lookup(ini_file_hash, full_key); if (old_value) { DBGF(debug, "old value = %p -> %s", old_value, old_value); char * new_value = g_strdup_printf("%s %s", old_value, value); // free's old_value free(value); DBGF(debug, "Replacing %s -> %p = %s", full_key, new_value, new_value); g_hash_table_replace(ini_file_hash, full_key, new_value); if (debug) { char * updated_value = g_hash_table_lookup(ini_file_hash, full_key); DBGF(debug, "updated value = %p = %s", updated_value, updated_value); } } else { DBGF(debug, "Inserting %s -> %s", full_key, value); g_hash_table_insert(ini_file_hash, full_key, value); } } else { DBGF(debug, "trimmed: |%s|", trimmed); emit_error_msg(errmsgs, debug, "Line %d: Invalid before section header: %s", ndx+1, trimmed); error_ct++; free(value); } free(key); } else { char * msg = (cur_segment) ? g_strdup_printf("Line %d: invalid: %s", ndx+1, trimmed) : g_strdup_printf("Line %d: invalid before section header: %s", ndx+1, trimmed); emit_error_msg(errmsgs, debug, msg); free(msg); error_ct++; } } // for loop DBGF(debug, "Freeing config_lines"); g_ptr_array_free(config_lines, true); if (cur_segment) free(cur_segment); if ( error_ct > 0 ) { #ifdef NO if (errinfo_accum) { Error_Info * master_err = errinfo_new(-EBADMSG, __func__, "Errors processing configuration file %s", ini_file_name); for (int ndx = 0; ndx < errmsgs->len; ndx++) { errinfo_add_cause(master_err, errinfo_new(-EBADMSG, __func__, g_ptr_array_index(errmsgs, ndx))); } g_ptr_array_add(errinfo_accum, master_err); } #endif result = -EBADMSG; g_hash_table_destroy(ini_file_hash); ini_file_hash = NULL; } } // process the lines // DBGF(true, "(ini_file_load) done"); if (debug) { if (errmsgs && errmsgs->len > 0) { for (guint ndx = 0; ndx < errmsgs->len; ndx++) printf(" %s\n", (char *) g_ptr_array_index(errmsgs, ndx)); } } ASSERT_IFF(result==0, ini_file_hash); if (result == 0) { Parsed_Ini_File * ini_file = calloc(1, sizeof(Parsed_Ini_File)); memcpy(ini_file->marker, PARSED_INI_FILE_MARKER, 4); ini_file->config_fn = g_strdup(ini_file_name); ini_file->hash_table = ini_file_hash; *parsed_ini_loc = ini_file; } if (debug) { printf("(%s) Done.*parsed_ini_loc=%p, returning %d\n", __func__, (void*)*parsed_ini_loc, result); fflush(stdout); } ASSERT_IFF(result==0, *parsed_ini_loc); return result; } /** Debugging function that reports the contents of a #Parsed_Ini_File. * * @param parsed_ini_file */ void ini_file_dump(Parsed_Ini_File * parsed_ini_file) { printf("(%s) Parsed_Ini_File at %p:\n", __func__, (void*)parsed_ini_file); if (parsed_ini_file) { assert(memcmp(parsed_ini_file->marker, PARSED_INI_FILE_MARKER, 4) == 0); printf("(%s) File name: %s\n", __func__, parsed_ini_file->config_fn); if (parsed_ini_file->hash_table) { GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, parsed_ini_file->hash_table); while (g_hash_table_iter_next(&iter, &key, &value)) { printf(" %s -> %s\n", (char *) key, (char *) value); } } } } char * ini_file_get_value( Parsed_Ini_File * parsed_ini_file, const char * segment, const char * id) { bool debug = false; assert(parsed_ini_file); assert(memcmp(parsed_ini_file->marker, PARSED_INI_FILE_MARKER, 4) == 0); assert(segment); assert(id); char * result = NULL; if (parsed_ini_file->hash_table) { char * full_key = g_strdup_printf("%s/%s", segment, id); strlower(full_key); result = g_hash_table_lookup(parsed_ini_file->hash_table, full_key); free(full_key); } DBGF(debug, "segment=%s, id=%s, returning: %s", segment, id, result); return result; } void ini_file_free(Parsed_Ini_File * parsed_ini_file) { if (parsed_ini_file) { assert(memcmp(parsed_ini_file->marker, PARSED_INI_FILE_MARKER, 4) == 0); if (parsed_ini_file->config_fn) free(parsed_ini_file->config_fn); if (parsed_ini_file->hash_table) g_hash_table_destroy(parsed_ini_file->hash_table); parsed_ini_file->marker[3] = 'x'; free(parsed_ini_file); } } ddcutil-2.2.0/src/util/string_util.c0000644000175000001440000015215714754153540013116 /** @file string_util.c * * String utility functions */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "glib_util.h" #include "debug_util.h" // temp #include "string_util.h" // Direct writes to stdout/stderr: // debug messages // stderr: hhs_to_byte() before terminating execution because of bad value // // General // #ifdef NOT_INLINE /** Returns a character string representation of an integer as a boolean value. * * @param value value to represent * @return "true" or "false" */ char * sbool(int value) { return (value) ? "true" : "false"; } #endif // // String functions (other than hex) // /** Compares 2 strings for equality, handling nulls * * @param s1 first string * @param s2 second string * @return true if the strings match, false if not */ bool streq(const char * s1, const char * s2) { bool result = false; if ( (s1 == NULL && s2 == NULL) || (s1 != NULL && s2 != NULL && (strcmp(s1, s2) == 0) ) ) result = true; return result; } /** Tests if one string is a valid abbreviation of another. * * @param value is this string an abbreviation? * @param longname unabbreviated value * @param minchars minimum number of characters that must match * @return true/false */ bool is_abbrev(const char * value, const char * longname, size_t minchars) { bool result = false; if (value && longname) { size_t vlen = strlen(value); if ( vlen >= minchars && vlen <= strlen(longname) && memcmp(value, longname, vlen) == 0 // n. returns 0 if vlen == 0 ) { result = true; } } // printf("(%s) value=|%s|, longname=|%s| returning %d\n", __func__, value, longname, result); return result; } /** Tests if string starts with a string. * * @param value_to_test value to examine * @param prefix prefix to check for * @return true/false * * @remark Consider using lib function g_str_prefix() ?? instead * * @remark * Returns **false** if either **value_to_test** or **prefix** are null */ bool str_starts_with(const char * value_to_test, const char * prefix) { return value_to_test && prefix && is_abbrev(prefix, value_to_test, strlen(prefix)); } /** Tests if string ends with a string. * * @param value_to_test value to examine * @param suffix substring to check for * @return true/false * * @remark Consider using lib function g_str_suffix() ?? instead */ bool str_ends_with(const char * value_to_test, const char * suffix) { bool debug = false; if (debug) printf("(%s) value_to_test=|%s|, end_part=|%s|\n", __func__, value_to_test, suffix); int value_len = strlen(value_to_test); int end_part_len = strlen(suffix); bool result = false; if (end_part_len <=value_len) { int startpos = value_len-end_part_len; result = streq(value_to_test+startpos, suffix); } if (debug) printf("(%s) returning: %d\n", __func__, result); return result; } /** Tests if a string contains a substring. * @param value to test string to examine * @param segment substring to look for * @return starting position of substring, -1 if not found */ int str_contains(const char * value_to_test, const char * segment) { bool debug = false; if (debug) printf("(%s) value_to_test=|%s|, segment=|%s|\n", __func__, value_to_test, segment); int result = -1; if (value_to_test && segment) { int seglen = strlen(segment); int laststart = strlen(value_to_test) - seglen; for (int ndx = 0; ndx < laststart; ndx++) { if (str_starts_with(value_to_test+ndx, segment)) { result = ndx; break; } } } if (debug) printf("(%s) Returning: %d\n", __func__, result); return result; } /** Are all characters in the string printable? * * @param s string to test * @return true/false (true if s==NULL) */ bool str_all_printable(const char * s) { bool result = true; if (s) { for (size_t ndx = 0; ndx < strlen(s); ndx++) { if (!isprint(s[ndx])) { result = false; break; } } } return result; } /** Compares a string to a null-terminated array of strings, using a specified * comparison function. * * @param s string to test * @param match_list null terminated array of strings to test against * @param comp_func comparison function * * @retval >= 0 index of first entry in list for which the comparison function succeeds * @retval -1 no match */ int matches_by_func(const char * s, const char ** match_list, String_Comp_Func comp_func) { int result = -1; int ndx = 0; for (ndx=0; match_list[ndx] != NULL; ndx++) { if ( (*comp_func)(s, match_list[ndx])) { result = ndx; break; } } return result; } /** Tests if a string exactly matches any string in a null-terminated * array of strings. (Null_Terminated_String_Array). * * @param s string to test for * @param match_list null terminated array of pointers to strings * * @retval >= 0 index of matching array entry * @retval -1 no match */ int exactly_matches_any(const char * s, const char ** match_list) { return matches_by_func(s, match_list, streq); } /** Finds the first entry in a null terminated array of strings * that is the initial portion of a specified string. * * @param s string to test against * @param match_list array of prefix strings (null-terminated) * * @retval >= 0 index of matching prefix * @retval -1 not found */ int starts_with_any(const char * s, const char ** match_list) { return matches_by_func(s, match_list, str_starts_with); } /** Trims leading and trailing whitespace from a string and * returns the result in a buffer provided by the caller. * If the buffer is insufficiently large, the result string * is truncated. * * The result is always null terminated. * * @param s string to trim (not modified) * @param buffer where to return result * @param bufsz buffer size * * @return pointer to truncated string (i.e. buffer) */ char * strtrim_r(const char * s, char * buffer, int bufsz) { bool debug = false; if (debug) printf("(%s) s=|%s|\n", __func__, s); int slen = strlen(s); int startpos = 0; int lastpos = slen-1; // n. -1 for 1 length string while ( startpos < slen && isspace(s[startpos]) ) startpos++; if (startpos < slen) { while ( lastpos >= startpos && isspace(s[lastpos])) lastpos--; } int tlen = 1 + lastpos - startpos; if (debug) printf("(%s) startpos=%d, lastpos=%d, tlen=%d\n", __func__, startpos, lastpos, tlen); if (tlen > (bufsz-1)) tlen = bufsz-1; memcpy(buffer, s+startpos, tlen); buffer[tlen] = '\0'; if (debug) printf("(%s) returning |%s|\n", __func__, buffer); return buffer; } /** Returns a pointer to the first non-whitespace character in a string. * * @param string to trim * @return pointer to first non-whitespace character, * to the ending \0 if all characters are whitespace */ char * ltrim_in_place(char * s) { char * p = s; while (*p && isspace(*p)) p++; return p; } /** Trims trailing whitespace from a string. * * @param s string to trim * @return s * * @remark * Particularly useful for stripping trailing newlines. */ char * rtrim_in_place(char * s) { int len = strlen(s); while(len > 0 && isspace(s[len-1])) { len--; s[len] = '\0'; } return s; } /** Trims leading and trailing whitespace from a string. * Trailing whitespace characters are replaced by \0. * * @param s string to trim * @return pointer to first non-whitespcace character */ char * trim_in_place(char * s) { char * p = s; while (*p && isspace(*p)) p++; int len = strlen(p); while (len > 0 && isspace(p[len-1])) s[--len] = '\0'; return p; } /** Trims leading and trailing whitespace from a string and * returns the result in newly allocated memory. * It is the caller's responsibility to free this memory. * The result string is null terminated. * * @param s string to trim (not modified) * @return truncated string in newly allocated memory */ char * strtrim(const char * s) { int bufsz = strlen(s)+1; char * buffer = calloc(1,bufsz); strtrim_r(s, buffer, bufsz); return buffer; } /** Extracts a substring from a string * * @param s string to process * @param startpos starting position (0 based) * @param ct number of characters; if ct + startpos is greater than * the string length, ct is reduced accordingly * @return extracted substring, in newly allocated memory */ char * substr(const char * s, size_t startpos, size_t ct) { if (startpos + ct > strlen(s)) ct = strlen(s) - startpos; char * result = calloc(ct+1, sizeof(char)); strncpy(result, s+startpos, ct); result[ct] = '\0'; return result; } /** Returns the initial portion of a string * * @param s string to process * @param ct number of characters; if ct is greater than * the string length, ct is reduced accordingly * @return extracted substring, in newly allocated memory */ char * lsub(const char * s, size_t ct) { return substr(s, 0, ct); } /** Joins an array of strings into a single string, using a separator string. * * @param pieces array of strings * @param ct0 number of strings, if < 0 the array is null terminated * @param sepstr separator string, if NULL then no separator string * * @return joined string (null terminated) * * The returned string has been malloc'd. It is the responsibility of * the caller to free it. * * @remark * If ct < 0, i.e. pieces is null terminated, at most the first 9999 strings in * the pieces array are joined. */ char * strjoin( const char ** pieces, const int ct0, const char * sepstr) { // printf("(%s) ct0=%d, sepstr=|%s|\n", __func__, ct0, sepstr); int total_length = 0; int ndx; int seplen = (sepstr) ? strlen(sepstr) : 0; // sepstr may be null int max_ct = (ct0 < 0) ? 9999 : ct0; for (ndx=0; ndx < max_ct && pieces[ndx]; ndx++) { total_length += strlen(pieces[ndx]); if (ndx > 0) total_length += seplen; } total_length += 1; // for terminating null int ct = ndx; // printf("(%s) ct=%d, total_length=%d\n", __func__, ct, total_length); char * result = malloc(total_length); result[0] = '\0'; char * end = result; for (ndx=0; ndx 0 && seplen > 0) { strcpy(end, sepstr); end += strlen(sepstr); } strcpy(end, pieces[ndx]); end += strlen(pieces[ndx]); } // printf("(%s) result=%p, end=%p\n", __func__, result, end); assert(end == result + total_length -1); return result; } // TO DO: generalize char * int_array_to_string(uint16_t * start, int ct) { int bufsz = ct*10; char * buf = calloc(1, bufsz); int next = 0; for (int ctr =0; ctr < ct && next < bufsz; ctr++) { g_snprintf(buf+next, bufsz-next,"%s%d", (next > 0) ? ", " : "", *(start+ctr) ); next = strlen(buf); } // DBGMSG("start=%p, ct=%d, returning %s", start, ct, buf); return buf; } #ifdef FUTURE // YAGNI: String_Array typedef struct { int max_ct; int cur_ct; char** s; } String_Array; String_Array* new_string_array(int size) { String_Array * result = calloc(1, sizeof(String_Array)); result->max_ct = size; result->cur_ct = 0; result->s = calloc(sizeof(char*), size); return result; } #endif /** Splits a string based on a list of delimiter characters. * * @param str_to_split string to be split * @param delims string of delimiter characters * @return null terminated array of pieces * * Note: Each character in delims is used as an individual test. * The full string is NOT a delimiter string. * * If str_to_split is NULL, a null terminated array of 0 pieces is returned. * If delims is NULL (and str_to_split is not NULL), a null terminated array * containing 1 piece (containing the value of str_to_split) is returned. */ Null_Terminated_String_Array strsplit(const char * str_to_split, const char * delims) { bool debug = false; size_t max_pieces = (str_to_split) ? (strlen(str_to_split)+1) : 1; if (debug) printf("(%s) str_to_split=|%s|, delims=|%s|, max_pieces=%zu\n", __func__, str_to_split, delims, max_pieces); char** workstruct = calloc(sizeof(char *), max_pieces+1); int piecect = 0; if (str_to_split) { char * str_to_split_dup = g_strdup(str_to_split); char * rest = str_to_split_dup; char * token; // originally token assignment was in while() clause, but valgrind // complaining about uninitialized variable, trying to figure out why token = strsep(&rest, delims); // n. overwrites character found while (token) { if (debug) printf("(%s) token: |%s|\n", __func__, token); if (strlen(token) > 0) workstruct[piecect++] = g_strdup(token); token = strsep(&rest, delims); } free(str_to_split_dup); } if (debug) printf("(%s) piecect=%d\n", __func__, piecect); char ** result = calloc(sizeof(char *), piecect+1); // n. workstruct[piecect] == NULL because we used calloc() memcpy(result, workstruct, (piecect+1)*sizeof(char*) ); if (debug) { int ndx = 0; char * curpiece = result[ndx]; while (curpiece != NULL) { printf("(%s) curpiece=%p |%s|\n", __func__, curpiece, curpiece); ndx++; curpiece = result[ndx]; } } free(workstruct); return result; } /** Splits a string into segments, each of which is no longer * that a specified number of characters. If delimiters are * specified, then they are used to split the string into segments. * Otherwise all segments, except possibly the last, are * **max_piece_length** in length. * * @param str_to_split string to be split * @param max_piece_length maximum length of each segment * @param delims string of delimiter characters * @return null terminated array of pieces * * @remark * Each character in **delims** is used as an individual test. * The full string is NOT a delimiter string. */ Null_Terminated_String_Array strsplit_maxlength( const char * str_to_split, uint16_t max_piece_length, const char * delims) { bool debug = false; if (debug) printf("(%s) max_piece_length=%u, delims=|%s|, str_to_split=|%s|\n", __func__, max_piece_length, delims, str_to_split); GPtrArray * pieces = g_ptr_array_sized_new(20); char * str_to_split2 = g_strdup(str_to_split); // work around constness char * start = str_to_split2; char * str_to_split2_end = str_to_split2 + strlen(str_to_split); if (debug) printf("(%s)x start=%p, str_to_split2_end=%p\n", __func__, (void*)start, (void*)str_to_split2_end); while (start < str_to_split2_end) { if (debug) printf("(%s) start=%p, str_to_split2_end=%p\n", __func__, (void*)start, (void*)str_to_split2_end); char * end = start + max_piece_length; if (end > str_to_split2_end) end = str_to_split2_end; // int cursize = end-start; // printf("(%s) end=%p, start=%p, cursize=%d, max_piece_length=%d\n", // __func__, end, start, cursize, max_piece_length); if ( end < str_to_split2_end) { // printf("(%s) Need to split. \n", __func__); if (delims) { char * last = end-1; while(last >= start) { // printf("(%s) last = %p\n", __func__, last); if (strchr(delims, *last)) { end = last+1; break; } last--; } } } char * piece = strndup(start, end-start); g_ptr_array_add(pieces, piece); start = start + strlen(piece); } // for some reason, if g_ptr_array_to_ntsa() is called with duplicate=false and // g_ptr_array(pieces, false) is called, valgrind complains about memory leak Null_Terminated_String_Array result = g_ptr_array_to_ntsa(pieces, /*duplicate=*/ true); g_ptr_array_set_free_func(pieces, g_free); g_ptr_array_free(pieces, true); free(str_to_split2); if (debug) ntsa_show(result); return result; } /** Frees a null terminated array of strings. * * @param string_array null terminated array of pointers to strings * @param free_strings if set, each string in the array is freed as well * * @remark * g_strfreev(string_array) equivalent to ntsa_free(string_array, true) */ void ntsa_free(Null_Terminated_String_Array string_array, bool free_strings) { bool debug = false; if (debug) printf("(%s) Freeing NTSA %p, free_strings=%s\n", __func__, (void*) string_array, sbool(free_strings) ); if (string_array) { if (free_strings) { int ndx = 0; while (string_array[ndx] != NULL) { if (debug) printf("(%s) Freeing string %d, %p->%s\n", __func__, ndx, string_array[ndx], string_array[ndx]); free(string_array[ndx++]); } } if (debug) printf("(%s) Freeing string_array=%p\n", __func__, (void*) string_array); free(string_array); } } /** Returns the number of strings in a null terminated array of strings. * * @param string_array null terminated array of pointers to strings * @return number of strings in the array * * @remark * Equivalent to g_strv_length() */ int ntsa_length(Null_Terminated_String_Array string_array) { assert(string_array); int ndx = 0; while (string_array[ndx] != NULL) { ndx++; } return ndx; } /** Creates a new #Null_Terminated_String_Array from 2 existing instances. * The result contains all the strings of the first array, followed by all * the strings of the second. * * @param a1 first instance * @param a2 second instance * @param dup if true, the pointers in the output array point to newly * allocated strings * if false, the pointers in the output array point to the * original strings. * * @return newly allocated #Null_Terminated_String_Array */ Null_Terminated_String_Array ntsa_join( Null_Terminated_String_Array a1, Null_Terminated_String_Array a2, bool dup) { assert(a1); assert(a2); int ct = ntsa_length(a1) + ntsa_length(a2); Null_Terminated_String_Array result = calloc((ct+1), sizeof(char *)); char ** to = result; char ** from = a1; while (*from) { if (dup) *to = g_strdup(*from); else *to = *from; to++; from++; } from = a2; while (*from) { if (dup) *to = g_strdup(*from); else *to = *from; to++; from++; } return result; } /** Creates copy of a #Null_Terminated_String_Array. * * The pointers in the new array point to newly allocated copies of the * original array. * * @param a1 instance to copy * @param dup if true, copy the strings as well as pointer array * @return newly allocated #Null_Terminated_String_Array */ Null_Terminated_String_Array ntsa_copy(Null_Terminated_String_Array a1, bool dup) { assert(a1); int ct = ntsa_length(a1); Null_Terminated_String_Array result = calloc((ct+1), sizeof(char *)); char ** to = result; char ** from = a1; while (*from) { if (dup) *to = g_strdup(*from); else *to = *from; to++; from++; } return result; } Null_Terminated_String_Array ntsa_prepend( char * value, Null_Terminated_String_Array old_array, bool dup) { int old_ct = ntsa_length(old_array); int new_ct = old_ct + 1; Null_Terminated_String_Array new_array = calloc((new_ct+1), sizeof(char *)); char ** to = new_array; *to++ = (dup) ? g_strdup(value) : value; char ** from = old_array; while (*from) { *to++ = (dup) ? g_strdup(*from) : *from; from++; } *to = NULL; // ntsa_show(argv); return new_array; } Null_Terminated_String_Array ntsa_create_empty_array() { Null_Terminated_String_Array new_array = calloc(1, sizeof(char *)); *new_array = NULL; return new_array; } /** Searches a #Null_Terminated_String_Array for an entry that matches a given * value using a match function provided. * * @param string_array null-terminated string array * @param value value to look for * @param func comparison function * @return index of first matching entry, -1 if not found */ int ntsa_findx( Null_Terminated_String_Array string_array, const char * value, String_Comp_Func func) { assert(string_array); int result = -1; int ndx = 0; char * s = NULL; while ( (s=string_array[ndx]) ) { // printf("(%s) checking ndx=%d |%s|\n", __func__, ndx, s); if (func(s,value)) { result = ndx; break; } ndx++; } // printf("(%s) Returning: %d\n", __func__, result); return result; } /** Searches a #Null_Terminated_String_Array for an entry equal to a * specified value. * * @param string_array null-terminated string array * @param value value to look for * @return index of first matching entry, -1 if not found */ int ntsa_find( Null_Terminated_String_Array string_array, const char * value) { return ntsa_findx(string_array, value, streq); } /* Reports the contents of a #Null_Terminated_String_Array. * * @param string_array null-terminated string array * * @remark This is not a **report** function as that would make string_util * depend on report_util, creating a circular dependency within util */ void ntsa_show(Null_Terminated_String_Array string_array) { assert(string_array); printf("Null_Terminated_String_Array at %p:\n", (void*) string_array); int ndx = 0; while (string_array[ndx]) { printf(" %p: |%s|\n", string_array[ndx], string_array[ndx]); ndx++; } printf("Total entries: %d\n", ndx); } /** Converts a #Null_Terminated_String_Array to a GPtrArray of pointers to strings. * The underlying strings are referenced, not duplicated. * * @param ntsa null-terminated array of strings * @return newly allocate GPtrArray */ GPtrArray * ntsa_to_g_ptr_array(Null_Terminated_String_Array ntsa) { int len = ntsa_length(ntsa); GPtrArray * garray = g_ptr_array_sized_new(len); int ndx; for (ndx=0; ndxlen+1, sizeof(char *)); for (guint ndx=0; ndx < gparray->len; ndx++) { if (duplicate) ntsa[ndx] = g_strdup(g_ptr_array_index(gparray,ndx)); else ntsa[ndx] = g_ptr_array_index(gparray,ndx); } return ntsa; } /** Converts an ASCII string to upper case. The original string is converted in place. * * @param s string to force to upper case */ void strupper(char * s) { if (s) { // check s not a null pointer char * p = s; while(*p) { *p = toupper(*p); p++; } } } /** Converts an ASCII string to lower case. The original string is converted in place. * * @param s string to force to lower case */ void strlower(char * s) { if (s) { // check s not a null pointer char * p = s; while(*p) { *p = tolower(*p); p++; } } } /** Creates an upper case copy of an ASCII string * * @param s string to copy * @return newly allocated string, NULL if s is NULL */ char * strdup_uc(const char* s) { if (!s) return NULL; char * us = g_strdup( s ); char * p = us; while (*p) {*p=toupper(*p); p++; } return us; } /* Replaces all instances of a character in a string with a different character. * The original string is converted in place. * * @param s string to modify * @param old_char character to replace * @param new_char replacement character * @return **s** */ char * str_replace_char(char * s, char old_char, char new_char) { if (s) { char * p = s; while (*p) { if (*p == old_char) *p = new_char; p++; } } return s; } /** Concatenates 2 strings into a newly allocated buffer. * * @param s1 first string * @param s2 second string * @return newly allocated string */ char * strcat_new(char * s1, char * s2) { assert(s1); assert(s2); char * result = malloc(strlen(s1) + strlen(s2) + 1); strcpy(result, s1); strcpy(result+strlen(s1), s2); return result; } /** Converts a sequence of characters into a (null-terminated) string. * * @param start pointer to first character * @param len number of characters * @return newly allocated string, * NULL if start was NULL (is this the most useful behavior?) */ char * chars_to_string(const char * start, int len) { assert(len >= 0); char * strbuf = NULL; if (start) { strbuf = malloc(len+1); memcpy(strbuf, start, len); *(strbuf + len) = '\0'; } return strbuf; } /** qsort() style string comparison function * * @param a pointer to a pointer to a string * @param b pointer to a pointer to a string * @return -1 if the first string sorts before the second * 0 if the strings are identical * 1 if the first string sorts after the second * * @remark * Satisfies GCompareFunc */ int indirect_strcmp(const void * a, const void * b) { char * alpha = *(char **) a; char * beta = *(char **) b; return strcmp(alpha, beta); } /** Appends a value to a string in a buffer. * * @param buf pointer to character buffer * @param bufsz buffer size * @param sepstr if non-null, separator string to insert * @param nextval value to append * * @retval true string was truncated * @retval false normal append * * @remark * Consider allowing the truncation maker, currently "..." to be * specified as a parameter. */ bool sbuf_append(char * buf, int bufsz, char * sepstr, char * nextval) { assert(buf && (bufsz > 4) ); //avoid handling pathological case bool truncated = false; size_t seplen = (sepstr) ? strlen(sepstr) : 0; size_t maxchars = bufsz-1; size_t newlen = ( strlen(buf) == 0 ) ? strlen(nextval) : ( strlen(buf) + seplen + strlen(nextval)); if (newlen <= maxchars) { if (strlen(buf) > 0 && sepstr) strcat(buf, sepstr); strcat(buf, nextval); } else { if ( strlen(buf) < (maxchars-3) ) strcat(buf, "..."); else strcpy(buf+(maxchars-3), "..."); truncated = true; } return truncated; } // // Numeric conversion // /** Converts a decimal or hexadecimal string to a long integer value. * * @param sval string representing an integer * @param p_ival address at which to store long integer value * @param base 10, 16, or 0 (see below) * @return true if conversion succeeded, false if it failed * * @remark * If base=10, this a normal integer conversion. * If base=16, **sval** contains a hex value, optionally * beginning with "x" or "0x". * If base=0, then either a decimal or hexadecimal conversion is performed. * If the value begins with "x" or "0x", it is treated as a hex value. * Otherwise it is treated as a decimal value. * \remark * If conversion fails, the value pointed to by **p_ival** is unchanged. * @remark * This function wraps system function strtol(), hiding the ugly details. */ bool str_to_long(const char * sval, long * p_ival, int base) { assert (base == 0 || base == 10 || base == 16); bool debug = false; if (debug) printf("(%s) sval->|%s|\n", __func__, sval); char * endptr; bool ok = false; if (sval) { if ( *sval != '\0') { char * work = NULL; bool has_digits = false; if (sval[0] == 'x' || sval[0] == 'X') { work = g_strdup_printf("0%s", sval); has_digits = strlen(work) > 2; } else { work = strdup(sval); has_digits = strlen(work) > 0; } if (debug) printf("(%s) work = %s\n", __func__, work); if (has_digits) { long result = strtol(work, &endptr, base); // allow hex // printf("(%s) sval=%p, endptr=%p, *endptr=|%c| (0x%02x), result=%ld\n", // __func__, sval, endptr, *endptr, *endptr, result); if (*endptr == '\0') { *p_ival = result; ok = true; } } free(work); } } if (debug) { if (ok) printf("(%s) sval=%s, Returning: %s, *ival = %ld\n", __func__, sval, sbool(ok), *p_ival); else printf("(%s) sval=%s, Returning: %s\n", __func__, sval, sbool(ok)); } return ok; } /** Converts a decimal or hexadecimal string to an integer value. * * @param sval string representing an integer * @param p_ival address at which to store integer value * @param base 10, 16, or 0 (see below) * @return true if conversion succeeded, false if it failed * * @remark * This function is implemented using #str_to_long(). See the documentation * of that function for details. * This function returns false if the value returned by #str_to_long() does * fit in an int. */ bool str_to_int(const char * sval, int * p_ival, int base) { long lval; bool result = str_to_long(sval, &lval, base); if (result) { *p_ival = lval; if (*p_ival!= lval) // ensure that lval fits in an int result = false; } return result; } /** Converts a string to a float value. * * @param sval string representing an integer * @param p_fval address at which to store float value * @return true if conversion succeeded, false if it failed * * @remark * \remark * If conversion fails, the value pointed to by **p_fval** is unchanged. * @remark * This function wraps system function strtof(), hiding the ugly details. */ bool str_to_float(const char * sval, float * p_fval) { bool debug = false; if (debug) printf("(%s) sval->|%s|\n", __func__, sval); bool ok = false; if ( *sval != '\0') { char * tailptr; float result = strtof(sval, &tailptr); if (*tailptr == '\0') { *p_fval = result; ok = true; } } if (debug) { if (ok) printf("(%s) sval=%s, Returning: %s, *p_fval = %16.7f\n", __func__, sval, sbool(ok), *p_fval); else printf("(%s) sval=%s, Returning: %s\n", __func__, sval, sbool(ok)); } return ok; } // // Hex value conversion. // /** Converts a (null terminated) string of 2 hex characters to * its byte value. * * @param s pointer to hex string * @param result pointer to byte in which converted value will be returned * @retval **true** successful conversion, * @retval **false** string does not consist of hex characters, * or is not 2 characters in length. */ bool hhs_to_byte_in_buf(const char * s, Byte * result) { // printf("(%s) Starting s=%s, strlen(s)=%zd\n", __func__, s, strlen(s) ); // consider changing to fail if len != 2, or perhaps len != 1,2 //assert(strlen(s) == 2); bool ok = true; if (strlen(s) != 2) ok = false; else { char * endptr = NULL; errno = 0; long longtemp = strtol(s, &endptr, 16 ); int errsv = errno; // printf("(%s) After strtol, longtemp=%ld \n", __func__, longtemp ); // printf("errno=%d, s=|%s|, s=0x%02x &s=%p, longtemp = %ld, endptr=%p, *endptr=0x%02x\n", // errsv, s, s, &s, longtemp, endptr,*endptr); // if (*endptr != '\0' || errsv != 0) { if (endptr != s+2 || errsv != 0) { ok = false; } else *result = (Byte) longtemp; } // printf("(%s) Returning ok=%s, *result=0x%02x\n", __func__, sbool(ok), *result); return ok; } /** Converts a hex string representing a single byte into its byte value. * This is a more lenient version of hhs_to_byte_in_buf(), allowing * the value to begin with "0x" or "x", or end with "h". The allowed * prefix or suffix is case-insensitive. * * Note that if the string need not be prefixed with "0X" or suffixed with "h" * to be regarded as a hex value. * * @param s pointer to hex string * @param result pointer to byte in which result will be returned * @retval **true** successful conversion, * @retval **false** conversion unsuccessful */ bool any_one_byte_hex_string_to_byte_in_buf(const char * s, Byte * result) { // printf("(%s) s = |%s|\n", __func__, s); char * suc = strdup_uc(s); char * suc0 = suc; if (str_starts_with(suc, "0X")) suc = suc + 2; else if (*suc == 'X') suc = suc + 1; else if (str_ends_with(suc, "H")) *(suc+strlen(suc)-1) = '\0'; bool ok = hhs_to_byte_in_buf(suc, result); free(suc0); // printf("(%s) returning %d, *result=0x%02x\n", __func__, ok, *result); return ok; } /** Converts 2 hex characters to their corresponding byte value. * The characters need not be null terminated. * * @param p_hh pointer to hex characters. * @param converted pointer to byte in which converted value will be returned * @retval **true** successful conversion * @retval **false** **s** does not point to hex characters */ bool hhc_to_byte_in_buf(const char * p_hh, Byte * converted) { // printf("(%s) Starting p_hh=%.2s \n", __func__, hh ); char hhs[3]; hhs[0] = p_hh[0]; // hhs[1] = cc[1]; // why does compiler complain? hhs[1] = *(p_hh+1); hhs[2] = '\0'; return hhs_to_byte_in_buf(hhs, converted); } /** Converts a string of hex characters (null terminated) to an array of bytes. * * @param hhs string of hex characters * @param ba_loc address at which to return pointer to byte array * @retval >= 0 number of bytes in array, * @retval -1 string could not be converted * * If successful, the byte array whose address is returned in ba_loc has * been malloc'd. It is the responsibility of the caller to free it. */ int hhs_to_byte_array(const char * hhs, Byte** ba_loc) { bool debug = false; if (debug) printf("(%s) strlen(hhs) = %zu, ba_loc=%p\n", __func__, strlen(hhs), ba_loc); if ( strlen(hhs) % 2) // if odd number of characters return -1; char xlate[] = "0123456789ABCDEF"; int bytect = strlen(hhs)/2; Byte * ba = malloc(bytect); bool ok = true; const char * h = hhs; Byte * b = ba; for (; *h && ok; b++) { char ch0 = toupper(*h++); char ch1 = toupper(*h++); char * pos0 = strchr(xlate, ch0); char * pos1 = strchr(xlate, ch1); if (pos0 && pos1) { *b = (pos0-xlate) * 16 + (pos1-xlate); } else { ok = false; } } if (!ok) { free(ba); bytect = -1; } else { *ba_loc = ba; } if (debug) { printf("(%s) Returning: %d. *ba_loc = %p\n", __func__, bytect, *ba_loc); if (bytect > 0) { printf(" 0x"); for (int ndx = 0; ndx< bytect; ndx++) { printf("%02x", ba[ndx]); } printf("\n"); } } return bytect; } bool hhs4_to_uint16(char * hhs4, uint16_t* result_loc) { // printf("(%s) Starting. hhs4 = |%s|\n", __func__, hhs4); bool ok = false; *result_loc = 0; if (strlen(hhs4) == 4) { uint8_t hi_byte; uint8_t lo_byte; if (hhc_to_byte_in_buf(&hhs4[0], &hi_byte) && hhc_to_byte_in_buf(&hhs4[2], &lo_byte) ) *result_loc = hi_byte << 8 | lo_byte; ok = true; } // printf("(%s) Returning %s, *result_loc = 0x%04x\n", __func__, sbool(ok), *result_loc); return ok; } /** Converts a single byte to a 2 byte hex string. * * @param ch byte to convert * @param out buffer to write to, must be at least 3 bytes * @param uppercase if true, use uppercase letters */ static void byte_to_hs(const unsigned char ch, char * out, bool uppercase) { bool debug = false; if (debug) printf("(%s) out=%p\n", __func__, out); assert(out); unsigned int hi = ch >> 4; unsigned int lo = ch & 0x0f; assert (hi < 16); assert (lo < 16); char uptable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B','C','D', 'E', 'F'}; char lotable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a','b','c','d', 'e', 'f'}; if (uppercase) { out[0] = uptable[hi]; out[1] = uptable[lo]; } else { out[0] = lotable[hi]; out[1] = lotable[lo]; } out[2] = '\0'; } /** Converts a sequence of bytes to its representation as a string of hex characters. * * @param bytes pointer to bytes * @param len number of bytes * @return pointer to newly allocated hex string * * The value returned by this function has been malloc'd. It is the * responsibility of the caller to free the memory. */ char * hexstring(const unsigned char * bytes, int len) { int alloc_size = 3*len + 1; char* str_buf = malloc(alloc_size); int i; for (i = 0; i < len; i++) { // printf("(%s) 3*i = %d, alloc_size-3*i = %d\n", __func__, 3*i, alloc_size-3*i); snprintf(str_buf+3*i, alloc_size-3*i, "%02x ", bytes[i]); } // printf ("(%s) Final null offset: %d\n", __func__, 3*len-1); str_buf[3*len-1] = 0x00; // printf("(%s) Returning: |%s|\n", __func__, str_buf); return str_buf; } /** Converts a sequence of bytes to its representation as a string of hex characters. * * @param bytes pointer to bytes * @param len number of bytes * @param sepstr string to separate each 2 hex character pairs representing a byte, * if NULL then no separators will be inserted * @param uppercase if true, use uppercase hex characters, * if false, use lower case hex characters * @param buffer pointer to buffer in which hex string will be returned, * if NULL, then a buffer will be allocated * @param bufsz size of buffer * if 0, then a buffer will be allocated * @return pointer to hex string * * If this function allocates a buffer, it is the responsibility of the caller * to free the memory. */ char * hexstring2( const unsigned char * bytes, int len, const char * sepstr, bool uppercase, char * buffer, size_t bufsz) { // if (len > 1) // printf("(%s) bytes=%p, len=%d, sepstr=|%s|, uppercase=%s, buffer=%p, bufsz=%d\n", __func__, // bytes, len, sepstr, sbool(uppercase), buffer, bufsz); int sepsize = 0; if (sepstr) { sepsize = strlen(sepstr); } size_t required_size = 2*len // hex rep of bytes + (len-1)*sepsize // for separators + 1; // terminating null // if (len > 1) // printf("(%s) required_size=%d\n", __func__, required_size); // special case: if (len == 0) required_size = 1; if (!buffer) bufsz = 0; assert (bufsz == 0 || bufsz >= required_size); if (bufsz == 0) { buffer = malloc(required_size); // printf("(%s) allocate buffer at %p, length=%d\n", __func__, buffer, required_size); } char * pattern = (uppercase) ? "%02X" : "%02x"; int incr1 = 2 + sepsize; int i; if (len == 0) *buffer = '\0'; for (i=0; i < len; i++) { // printf("(%s) i=%d, buffer+i*incr1=%p\n", __func__, i, buffer+i*incr1); sprintf(buffer+i*incr1, pattern, bytes[i]); if (i < (len-1) && sepstr) strcat(buffer, sepstr); } // printf("(%s) strlen(buffer) = %ld, required_size=%d \n", __func__, strlen(buffer), required_size ); // printf("(%s) buffer=|%s|\n", __func__, buffer ); assert(strlen(buffer) == required_size-1); return buffer; } /** Thread safe version of #hexstring2(). * * This function allocates a thread specific buffer in which the hex string is built. * The buffer is valid until the next call of this function in the same thread. * * @param bytes pointer to bytes * @param len number of bytes * @param sepstr string to separate each segment of 2 hex character pairs representing bytes * if NULL then no separators will be inserted * @param hunk_size separator string frequency * @param uppercase if true, use uppercase hex characters, * if false, use lower case hex characters * @return pointer to hex string * * Note that if the returned pointer is referenced after another call to * this function, the results are unpredictable. * * This function is intended to simplify formatting of diagnostic messages. * The caller needn't be concerned with buffer size and allocation. */ char * hexstring3_t( const unsigned char * bytes, // bytes to convert int len, // number of bytes const char * sepstr, // separator string between hex digits uint8_t hunk_size, // separator string frequency bool uppercase) // use upper case hex characters { bool debug = false; static GPrivate hexstring3_key = G_PRIVATE_INIT(g_free); static GPrivate hexstring3_len_key = G_PRIVATE_INIT(g_free); if (debug) printf("(%s) bytes=%p, len=%d, sepstr=|%s|, uppercase=%s\n", __func__, bytes, len, sepstr, sbool(uppercase)); if (hunk_size == 0) sepstr = NULL; else if (sepstr == NULL) hunk_size = 0; int sepsize = 0; if (sepstr) { sepsize = strlen(sepstr); } size_t required_size = 1; // special case if len == 0 // excessive if hunk_size > 1, but not worth the effort to be accurate if (len > 0) required_size = 2*len // hex rep of bytes + (len-1)*sepsize // for separators + 1; // terminating null if (debug) printf("(%s) sepstr=|%s|, hunk_size=%d, required_size=%zu\n", __func__, sepstr, hunk_size, required_size); char * buf = get_thread_dynamic_buffer(&hexstring3_key, &hexstring3_len_key, required_size); // char * buf = get_thread_private_buffer(&hexstring3_key, NULL, required_size); // char * pattern = (uppercase) ? "%02X" : "%02x"; // if (debug) // printf("(%s) pattern=%s, buf=%p\n", __func__, pattern, buf); // int incr1 = 2 + sepsize; *buf = '\0'; for (int i=0; i < len; i++) { if (debug) printf("(%s) i=%d, buf=%p, strlen(buf)=%ld\n", __func__, i, buf, strlen(buf)); // sprintf(buf+strlen(buf), pattern, bytes[i]); byte_to_hs(bytes[i], buf+strlen(buf), uppercase); bool insert_sepstr = (hunk_size == 0) ? (i < (len-1) && sepstr) : (i < (len-1) && sepstr && (i+1)%hunk_size == 0); if (insert_sepstr) strcat(buf, sepstr); } if (debug) { printf("(%s) strlen(buf) = %zu, required_size=%zu\n", __func__, strlen(buf), required_size ); printf("(%s) buf=|%s|\n", __func__, buf ); } assert(strlen(buf) <= required_size-1); if (debug) printf("(%s) Returning: %p -> |%s|\n", __func__, buf, buf); return buf; } /** Thread safe version of #hexstring(). * * This function allocates a thread specific buffer in which the hex string is built. * The buffer is valid until the next call of this function in the same thread. * * @param bytes pointer to bytes * @param len number of bytes * @return pointer to hex string * * Note that if the returned pointer is referenced after another call to * this function, the results are unpredictable. * * This function is intended to simplify formatting of diagnostic messages, since * the caller needn't be concerned with buffer size and allocation. */ char * hexstring_t( const unsigned char * bytes, int len) { return hexstring3_t(bytes, len, " ", 1, false); } /** Dump a region of memory as hex characters and their ASCII values. * The output is indented by the specified number of spaces, and * collected in a GPtrArray. * * @param collector line of output are added to this array * @param data start of region to show * @param size length of region * @param indents number of spaces to indent the output */ void hex_dump_indented_collect(GPtrArray * collector, const Byte* data, int size, int indents) { bool debug = false; DBGF(debug, "Starting. indents=%d", indents); assert(collector); if (debug) { show_backtrace(0); backtrace_to_syslog(LOG_NOTICE, 0); } int i; // index in data... int j; // index in line... char temp[10]; // was 8, compiler complains that too small char buffer[128]; char *ascii; char indentation[100]; g_snprintf(indentation, 100, "%.*s", indents, ""); memset(buffer, 0, 128); // Printing the ruler... char * line = g_strdup_printf( "%s +0 +4 +8 +c 0 4 8 c ", indentation); g_ptr_array_add(collector, line); ascii = buffer + 58; memset(buffer, ' ', 58 + 16); buffer[58 + 16] = '\0'; buffer[0] = '+'; buffer[1] = '0'; buffer[2] = '0'; buffer[3] = '0'; buffer[4] = '0'; for (i = 0, j = 0; i < size; i++, j++) { if (j == 16) { char * line = g_strdup_printf("%s%s", indentation, buffer); g_ptr_array_add(collector, line); memset(buffer, ' ', 58 + 16); sprintf(temp, "+%04x", i); memcpy(buffer, temp, 5); j = 0; } sprintf(temp, "%02x", 0xff & data[i]); memcpy(buffer + 8 + (j * 3), temp, 2); if ((data[i] > 31) && (data[i] < 127)) ascii[j] = data[i]; else ascii[j] = '.'; } if (j != 0) { char * line = g_strdup_printf("%s%s", indentation, buffer); g_ptr_array_add(collector, line); } DBGF(debug, "Done"); } /** Dump a region of memory as hex characters and their ASCII values. * The output is indented by the specified number of spaces. * * @param fh where to write output, if NULL, write nothing * @param data start of region to show * @param size length of region * @param indents number of spaces to indent the output */ void fhex_dump_indented(FILE * fh, const Byte* data, int size, int indents) { GPtrArray * collector = g_ptr_array_new_with_free_func(g_free); hex_dump_indented_collect(collector, data, size, indents); for (int ndx = 0; ndx < collector->len; ndx++) { fprintf(fh, "%s\n", (char*) g_ptr_array_index(collector, ndx)); } g_ptr_array_free(collector, true); } /** Dump a region of memory as hex characters and their ASCII values. * Output is written to the location specified by parameter fh. * * @param fh where to write output * @param data start of region to show * @param size length of region */ void fhex_dump(FILE * fh, const Byte* data, int size) { fhex_dump_indented(fh, data, size, 0); } /** Dump a region of memory as hex characters and their ASCII values. * Output is written to stdout. * * @param data start of region to show * @param size length of region */ void hex_dump(const Byte* data, int size) { fhex_dump(stdout, data, size); } /** Extension of fputc() that allows a NULL stream argument, * in which case no output is written. * * @param c character to write * @param stream if null do nothing * * @return result of underlying fputs(), or 0 if stream is NULL */ int f0putc(int c, FILE * stream) { int rc = 0; if (stream) rc = fputc(c, stream); return rc; } /** Extension of fputs() that allows a NULL stream argument, * in which case no output is written. * * @param msg text to write * @param stream if null do nothing * * @return result of underlying fputs(), or 0 if stream is NULL */ int f0puts(const char * msg, FILE * stream) { int rc = 0; if (stream) rc = fputs(msg, stream); return rc; } /** Extension of fprintf() that allows a NULL stream argument, * in which case no output is written. * * @param stream if null do nothing * @param format format string * * @return result of underlying vfprintf(), or 0 if stream is NULL */ int f0printf(FILE * stream, const char * format, ...) { int rc = 0; // printf("(%s) stream=%p\n", __func__, stream); if (stream) { va_list(args); va_start(args, format); rc = vfprintf(stream, format, args); va_end(args); } return rc; } /** Extension of vfprintf() that allows a NULL stream argument, * in which case no output is written. * * @param stream if null do nothing * @param format format string * @param ap pointer to variable argument list * * @return result of underlying vfprintf(), or 0 if stream is NULL */ int vf0printf(FILE * stream, const char * format, va_list ap) { int rc = 0; if (stream) rc = vfprintf(stream, format, ap); return rc; } // // Miscellaneous // /** Tests if a range of bytes is entirely 0 * * @param bytes pointer to first byte * @param bytect number of bytes * @return **true** if all bytes are zero, **false** if not */ bool all_bytes_zero(Byte * bytes, int bytect) { Byte sum = 0; for (int ndx=0; ndx < bytect; ndx++) { sum |= bytes[ndx]; } return !sum; } // Private version of strcasestr(), avoids needing to set _GNU_SOURCE char * ascii_strcasestr(const char * haystack, const char * needle) { char * result = NULL; if (haystack && needle) { char * uhaystack = g_ascii_strup(haystack, /*len=*/ -1); // -1: null-terminated char * uneedle = g_ascii_strup(needle, /*len=*/ -1); // -1: null-terminated char * ustart = strstr(uhaystack, uneedle); if (ustart) { int offset = ustart-uhaystack; char * h2 = (char *) haystack; // cast to avoid warning re discarding const qualifier result = h2+offset; } free(uhaystack); free(uneedle); } return result; } /** Tests if any of a set of strings is a substring of a given string * * @param test string to check, must not be NULL * @param terms pointer to array of substring to check * @param ignore_case if true, test is case-insensitive * @return true if a substring is found * * @remark * If **terms** is NULL, returns **false** * @remark * Consider converting ignore_case to a flags byte of options */ bool apply_filter_terms(const char * text, char ** terms, bool ignore_case) { assert(text); bool debug = false; bool result = true; char ** term = NULL; if (terms) { // printf("(%s) filter_terms:\n", __func__); // ntsa_show(terms); result = false; term = terms; while (*term) { // printf("(%s) Comparing |%s|\n", __func__, *term); if (ignore_case) { // if (strcasestr(text,*term)) { if (ascii_strcasestr(text,*term)) { result = true; break; } } else { if (strstr(text, *term)) { result = true; break; } } term++; } } if (debug) { if (result) { printf("(%s) text=|%s|, term=|%s|, Returning: true\n", __func__, text, *term); } else { printf("(%s) text=|%s|, Returning: false\n", __func__, text); } } return result; } /** Converts a string containing a (possible) hex value to canonical form. * * If the value starts with "x" or "X", or ends with "h" or "H", or starts * with "0X", it is modified to start with "0x". * Otherwise, the returned value is identical to the input value. * * @param string_value value to convert * @return canonicalized value (caller is responsible for freeing) * * @remark * Consider converting to a function that uses a thread-specific buffer, making * the returned value valid until the next call to this function on the current * thread. Would relieve the caller of responsibility for freeing the value. */ char * canonicalize_possible_hex_value(char * string_value) { assert(string_value); int bufsz = strlen(string_value) + 1 + 1; // 1 for possible increased length, 1 for terminating null char * buf = calloc(1, bufsz); if (*string_value == 'X' || *string_value == 'x' ) { // increases string size by 1 snprintf(buf, bufsz, "0x%s", string_value+1); } else if (*(string_value + strlen(string_value)-1) == 'H' || *(string_value + strlen(string_value)-1) == 'h' ) { // increases string size by 1 int newlen = strlen(string_value)-1; snprintf(buf, bufsz, "0x%.*s", newlen, string_value); } else if (str_starts_with(string_value, "0X")) { snprintf(buf, bufsz, "0x%s", string_value+2); } else strcpy(buf, string_value); // DBGMSG("string_value=|%s|, returning |%s|", string_value, buf); return buf; } ddcutil-2.2.0/src/util/sysfs_util.c0000644000175000001440000005251114754153540012750 /** @file sysfs_util.c * * Functions for reading /sys file system */ // Copyright (C) 2016-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later //* \cond */ #include #include #include #include #include #include #include #include #include /** \endcond */ #include "coredefs_base.h" #include "debug_util.h" #include "file_util.h" #include "report_util.h" #include "string_util.h" #include "sysfs_util.h" // -Wstringop-trunction is brain dead // compile will fail if -Werror set // #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Wstringop-truncation" /** Reads a /sys attribute file, which is 1 line of text * * \param dirname directory name * \param attrname attribute name, i.e. file name * \param verbose if true, write message to stderr if unable to open file * \return pointer to attribute value string, caller is responsible for freeing */ char * read_sysfs_attr( const char * dirname, const char * attrname, bool verbose) { char fn[PATH_MAX]; sprintf(fn, "%s/%s", dirname, attrname); return file_get_first_line(fn, verbose); } /** Reads a /sys attribute file, which is 1 line of text. * If the attribute is not found, returns a default value * * \param dirname directory name * \param attrname attribute name, i.e. file name * \param default_value default value, duplicated * \param verbose if true, write message to stderr if unable to open file * \return pointer to attribute value string, caller is responsible for freeing */ char * read_sysfs_attr_w_default( const char * dirname, const char * attrname, const char * default_value, bool verbose) { char fn[PATH_MAX]; sprintf(fn, "%s/%s", dirname, attrname); char * result = file_get_first_line(fn, verbose); if (!result) result = g_strdup(default_value); // g_strdup() so caller can free any result return result; } /** Reads a /sys attribute file, which is 1 line of text, into a buffer * provided by the caller. * If the attribute is not found, returns a default value * * \param dirname directory name * \param attrname attribute name, i.e. file name * \param default_value default value, duplicated * \param buf pointer to buffer * \param bufsz size of buffer * \param verbose if true, write message to stderr if unable to open file * \return buf * * If the string to be returned is too large for the buffer, it is truncated * to fit with a trailing '\0'. */ char * read_sysfs_attr_w_default_r( const char * dirname, const char * attrname, const char * default_value, char * buf, unsigned bufsz, bool verbose) { assert(strlen(default_value) < bufsz); char fn[PATH_MAX]; sprintf(fn, "%s/%s", dirname, attrname); char * result = file_get_first_line(fn, verbose); if (result) { STRLCPY(buf, result, bufsz); free(result); } else { STRLCPY(buf, default_value, bufsz); } return buf; } /** Reads a binary /sys attribute file * * \param dirname directory name * \param attrname attribute name, i.e. file name * \param est_size estimated size * \param verbose if open fails, write message to stderr * \return if successful, a **GByteArray** of bytes, caller is responsible for freeing * if failure, then NULL */ GByteArray * read_binary_sysfs_attr( const char * dirname, const char * attrname, int est_size, bool verbose) { assert(dirname); assert(attrname); char fn[PATH_MAX]; sprintf(fn, "%s/%s", dirname, attrname); return read_binary_file(fn, est_size, verbose); } /** For a given directory path, returns the last component of the * resolved absolute path. * * \param path path to resolve * \return base name of resolved path, caller is responsible for freeing */ char * get_rpath_basename( const char * path) { char * result = NULL; char resolved_path[PATH_MAX]; char * rpath = realpath(path, resolved_path); // printf("(%s) rpath=|%s|\n", __func__, rpath); if (rpath) { result = g_path_get_basename(rpath); } // printf("(%s) busno=%d, returning %s\n", __func__, busno, driver_name); return result; } // // Functions for probing /sys // /* The rpt_attr...() functions share a common set of behaviors. 1) They write the value read to the fout() device, typically sysout. 2) A message is not actually written if either global setting set_rpt_sysfs_attr_silent(true) or the logical indentation depth (depth parm) is less than 0. 3) If the value_loc parm is non-null, it is the address at which the function returns the address of newly allocated memory containing the value. NULL is returned if the attribute is not found. 4) The depth and value_loc arguments are followed by 1 or more parts of a file name. The parts are assembled to create the fully qualified name of the attribute. */ static bool rpt2_silent = false; /** Globally controls whether values read are actually written to the terminal. * * \param onoff * \return prior value */ bool set_rpt_sysfs_attr_silent( bool onoff) { bool old = rpt2_silent; rpt2_silent = onoff; return old; } /** This is the core function for writing attribute values to the terminal. * * \param depth logical indentation depth * \param node fully qualified attribute name (i.e. file name) * \param op "=" or ":" * \param value attribute value if op is "=", * a string like "found" if op is ":" * realpath or basename if op is "->" * * The attribute name is padded on the right tp be at least 70 characters wide. */ void rpt_attr_output( int depth, const char * node, const char * op, const char * value) { if (!rpt2_silent) { int offset = 70; if (depth >= 0) rpt_vstring(depth, "%-*s%-2s %s", offset, node, op, value); } } /** Reads a normal, single line attribute value from a file. * * \param fq_attrname fully qualified attribute name (i.e. file name) * \param verbose if true, write message to stderr if unable to open file * \retval non-NULL pointer to line read (caller responsible for freeing) * \retval NULL if error or no lines in file */ static inline char * read_sysfs_attr0( const char * fq_attrname, bool verbose) { return file_get_first_line(fq_attrname, verbose); } /** Returns the name of the first subdirectory of a specified directory * whose name satisfies the filter function. * \param dirname name of directory to search * \param filter pointer to filter function * \param val comparison value passed to filter function * \retval simple name of first subdirectory that satisfies the filter function * (caller responsible for freeing) * \retval NULL if not found */ static char * get_single_subdir_name( const char * dirname, Fn_Filter filter, const char * val) { bool debug = false; int d1 = 1; DIR* dir2 = opendir(dirname); char * result = NULL; if (!dir2) { rpt_vstring(d1, "Unexpected error. Unable to open sysfs directory %s: %s", dirname, strerror(errno)); } else { struct dirent *dent2; while ((dent2 = readdir(dir2)) != NULL) { DBGF(debug, "%s", dent2->d_name); if (!str_starts_with(dent2->d_name, ".")) { if (!filter || filter(dent2->d_name, val)) { result = g_strdup(dent2->d_name); break; } } } closedir(dir2); } DBGF(debug, "directory: %s, first subdir: %s", dirname, result); return result; } /** Assembles a file (sysfs attribute) name from one or more segments. * \param buffer buffer in which to return the assembled name * \param bufsz size of buffer * \param fn_segment first segment of name * \param ap remaining segments * \return assembled attribute name (buffer) * * The assembled value will be silently truncated if necessary to fit in buffer */ char * assemble_sysfs_path2( char * buffer, int bufsz, const char * fn_segment, va_list ap) { assert(buffer && bufsz > 0); bool debug = false; DBGF(debug, "Starting. bufsz=%d, fn_segment=|%s|", bufsz, fn_segment); STRLCPY(buffer, fn_segment, bufsz-1); int segment_ct = 1; while(true) { char * segment = va_arg(ap, char*); if (!segment) break; segment_ct++; DBGF(debug, "segment_ct: %d, segment=%p", segment_ct, segment); // hex_dump((const Byte*)segment,32); DBGF(debug, "segment |%s|", segment); STRLCAT(buffer, "/", bufsz); STRLCAT(buffer, segment, bufsz); } DBGF(debug,"Returning: %s", buffer); return buffer; } /** Reports the value of a simple text attribute (the most common case) * to the sysout device. * * If the attribute is not found, reports "Not found". * * \param depth logical indentation depth, if < 0, output nothing * \param value_loc if non-NULL, the address at which to return a copy of * the attribute value (caller is responsible for freeing). * or NULL if the attribute cannot be read * \param fn_segment first segment of attribute name * \param ... remaining segments of name * \return true if attribute found, false if not * * \remark * *value_loc is set iff result is true */ bool rpt_attr_text( int depth, char ** value_loc, const char * fn_segment, ...) { bool debug = false; if (debug) printf("(%s) Starting. fn_segment=%s\n", __func__, fn_segment); bool found = false; if (value_loc) *value_loc = NULL; char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); if (debug) printf("(%s) pb1=%s\n", __func__, pb1); char * val = read_sysfs_attr0(pb1, false); if (val) { found = true; rpt_attr_output(depth, pb1, "=", val); if (value_loc) *value_loc = val; else free(val); } else { rpt_attr_output(depth, pb1, ": ", "Not Found"); } if (debug) printf("(%s) Done.\n", __func__); if (value_loc) ASSERT_IFF(found, *value_loc); return found; } bool rpt_attr_int( int depth, int * value_loc, const char * fn_segment, ...) { bool debug = false; char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); if (debug) printf("(%s) pb1=%s\n", __func__, pb1); bool found = false; if (value_loc) *value_loc = -1; int ival = -1; char * sval = read_sysfs_attr0(pb1, false); if (sval) { found = str_to_int(sval, &ival, 10); if (!found) { char buf[40]; g_strdup_printf(buf, 40, "Not an integer: %s", sval); rpt_attr_output(depth, pb1, ": ", buf); } else { rpt_attr_output(depth, pb1, "=", sval); if (value_loc) *value_loc = ival; } free(sval); } else { rpt_attr_output(depth, pb1, ": ", "Not Found"); } if (debug) printf("(%s) Done.\n", __func__); return found; } /** Reads a binary attribute and reports "Found" or "Not found". * * \param depth logical indentation depth, if < 0, output nothing * \param value_loc if non-NULL, the address at which to return a pointer to * a GByteArray containing the value. (caller is responsible for freeing). * If the attribute cannot be read, or is 0 length, NULL is returned. * \param fn_segment first segment of attribute name * \param ap remaining segments of name * \return true if attribute found, false if not * * \remark * *value_loc is set iff result is true */ bool rpt_attr_binary( int depth, GByteArray ** value_loc, const char * fn_segment, ...) { bool debug = false; if (debug) { printf("(%s) Starting. depth=%d, value_loc=%p\n", __func__, depth, value_loc); if (debug && depth < 0) depth=1; } char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); bool found = false; if (value_loc) *value_loc = NULL; GByteArray * bytes = read_binary_file(pb1, /*estimated size=*/ 256, true); if (bytes) { if (bytes->len > 0) { found = true; rpt_attr_output(depth, pb1, ":", "Found"); // rpt_vstring(depth, "%-*s = %s", offset, pb1, val); if (value_loc) *value_loc = bytes; } else { g_byte_array_free(bytes, true); rpt_attr_output(depth, pb1, ": ", "0 length"); } } else rpt_attr_output(depth, pb1, ": ", "Not Found"); if (debug) { if (value_loc) printf("(%s) Returning: %s. *value_loc=%p\n", __func__, SBOOL(found), (void*)*value_loc); else printf("(%s) Returning: %s\n", __func__, SBOOL(found)); } return found; } /** Reports a binary attribute that represents an EDID. * * \param depth logical indentation depth, if < 0, output nothing * \param value_loc if non-NULL, the address at which to return a pointer to * a GByteArray containing the value. (caller is responsible for freeing). * If the attribute cannot be read NULL is set. * \param fn_segment first segment of attribute name * \param ... remaining segments of name * \return true if attribute found, false if not * * \remark * if result == true, *value_loc will be set iff non-null */ bool rpt_attr_edid( int depth, GByteArray ** value_loc, const char * fn_segment, ...) { bool debug = false; DBGF(debug, "Starting. depth=%d, value_loc=%p, fn_segment=|%s|", depth, value_loc, fn_segment); if (debug) { show_backtrace(0); if (redirect_reports_to_syslog) backtrace_to_syslog(LOG_NOTICE, 0); } if (debug && depth < 0) depth=1; char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); // DBGMSG("pb1=%s", pb1); bool found = false; if (value_loc) *value_loc = NULL; GByteArray * edid = NULL; found = rpt_attr_binary(depth, &edid, pb1, NULL); ASSERT_IFF(found, edid); if (edid) { if (!rpt2_silent && depth >= 0) { if (redirect_reports_to_syslog) { GPtrArray * collector = g_ptr_array_new_with_free_func(g_free); hex_dump_indented_collect(collector, edid->data, edid->len, depth+4); for (int ndx = 0; ndx < collector->len; ndx++) { syslog(LOG_NOTICE, "%s", (char*) g_ptr_array_index(collector, ndx)); } } else rpt_hex_dump(edid->data, edid->len, depth+4); } if (value_loc) *value_loc = edid; else { g_byte_array_free(edid, true); } } if (debug) { DBG("Returning %s.", SBOOL(found)); if (value_loc && *value_loc) { GByteArray * gba = *value_loc; DBG(" data=%p, len=%d\n", (void*) gba->data, gba->len); } } if (value_loc) ASSERT_IFF(found, *value_loc); return found; } /** Reports the realpath of a file name, or "Invalid path" if the file name * is invalid. * * \param depth logical indentation depth, if < 0, output nothing * \param value_loc if non-NULL, the address at which to return a pointer to * the path name (caller is responsible for freeing). * If the path is invalid, NULL is returned. * \param fn_segment first segment of attribute name * \param ... remaining segments of name * \return true if attribute found, false if not * * \remark * *value_loc is set iff result is true */ bool rpt_attr_realpath( int depth, char ** value_loc, const char * fn_segment, ...) { bool debug = false; DBGF(debug, "fn_segment=|%s|", fn_segment); if (value_loc) *value_loc = NULL; char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); char * result = realpath(pb1, NULL); bool found = (result); if (result) { rpt_attr_output(depth, pb1, "->", result); if (value_loc) *value_loc = result; else free(result); } else { rpt_attr_output(depth, pb1, "->", "Invalid path"); } if (value_loc) ASSERT_IFF(found, *value_loc); return found; } /** Reports the base name of a file name's realpath, or "Invalid path" if the file name * is invalid. * * \param depth logical indentation depth, if < 0, output nothing * \param value_loc if non-NULL, the address at which to return a pointer to * the name (caller is responsible for freeing). * If the path is invalid, NULL is returned. * \param fn_segment first segment of attribute name * \param ... remaining segments of name * \return true if attribute found, false if not * * \remark * *value_loc is set iff result is true */ bool rpt_attr_realpath_basename( int depth, char ** value_loc, const char * fn_segment, ...) { char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); bool found = false; if (value_loc) *value_loc = NULL; char pb2[PATH_MAX]; char * rpath = realpath(pb1, pb2); // without assignment, get warning that return value unused if (rpath) { char * bpath = basename(rpath); if (bpath) { found = true; rpt_attr_output(depth, pb1, "->", bpath); if (value_loc) *value_loc = g_strdup(bpath); } } if (!found) { rpt_attr_output(depth, pb1, "->", "Invalid path"); } if (value_loc) ASSERT_IFF(found, *value_loc); return found; } /** Checks for the first subdirectory of a given directory whose name satisfies * some predicate, and reports whether it is found and if so its name. * * \param depth logical indentation depth, if < 0, output nothing * \param value_loc if non-NULL, the address at which to return a pointer to * the name (caller is responsible for freeing). * If the path is invalid, NULL is returned. * \param predicate_function pointer to test function * \param predicate_value comparison argument passed to test function * \param fn_segment first segment of attribute name * \param ... remaining segments of name * \return true if subdirectory found, false if not * * \remark * *value_loc is set iff result is true */ bool rpt_attr_single_subdir( int depth, char ** value_loc, Fn_Filter predicate_function, const char * predicate_value, const char * fn_segment, ...) { bool debug = false; if (debug) printf("(%s) Starting. depth=%d, value_loc=%p\n", __func__, depth, (void*)value_loc); char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); if (debug) printf("(%s) pb1=|%s|\n", __func__, pb1); if (value_loc) *value_loc = NULL; char * subdir_name = get_single_subdir_name(pb1, predicate_function, predicate_value); bool found = false; if (subdir_name) { char buf[PATH_MAX+100]; g_snprintf(buf, PATH_MAX+100, "Found subdirectory = %s", subdir_name); rpt_attr_output(depth, pb1, ":", buf); if (value_loc) *value_loc = subdir_name; else free(subdir_name); found = true; } else { char buf[PATH_MAX+100]; g_snprintf(buf, PATH_MAX+100, "No %s subdirectory found", predicate_value); rpt_attr_output(depth, pb1, ":", buf); } if (debug) printf("(%s) Done. Returning %s\n", __func__, SBOOL(found)); if (value_loc) ASSERT_IFF(found, *value_loc); return found; } /** Reports whether a subdirectory exists. * * \param depth logical indentation depth, if < 0, output nothing * \param value_loc if non-NULL, *value_loc is always set = NULL * \param fn_segment first segment of directory name * \param ... remaining segments of name (requires at least 1) * \return true if subdirectory found, false if not */ bool rpt_attr_note_subdir( int depth, char ** value_loc, const char * fn_segment, ...) { bool debug = false; DBGF(debug, "fn_segment=|%s|", fn_segment); char pb1[PATH_MAX]; va_list ap; va_start(ap, fn_segment); assemble_sysfs_path2(pb1, PATH_MAX, fn_segment, ap); va_end(ap); DBGF(debug, "pb1: %s", pb1); if (value_loc) *value_loc = NULL; bool found = directory_exists(pb1); if (found) rpt_attr_output(depth, pb1, ":", "Subdirectory"); else rpt_attr_output(depth, pb1, ":", "No such subdirectory"); return found; } ddcutil-2.2.0/src/util/subprocess_util.c0000644000175000001440000002255714754153540014000 /** @file subprocess_util.c * * Functions to execute shell commands */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include /** \endcond */ #include "config.h" #include "file_util.h" #include "glib_util.h" #include "report_util.h" #include "string_util.h" #include "subprocess_util.h" /** Executes a shell command and writes the output to the current report destination * or to stdout. * * @param shell_cmd command to execute * @param depth logical report indentation depth, * if < 0, write to stdout * * @return true command succeeded * false failed, e.g. command not found */ bool execute_shell_cmd_rpt(const char * shell_cmd, int depth) { bool debug = false; if (debug) printf("(%s) Starting. shell_cmd = |%s|\n", __func__, shell_cmd); bool ok = true; FILE * fp; int bufsz = strlen(shell_cmd) + 50; char * cmdbuf = calloc(1, bufsz); snprintf(cmdbuf, bufsz, "(%s) 2>&1", shell_cmd); // printf("(%s) cmdbuf=|%s|\n", __func__, cmdbuf); fp = popen(cmdbuf, "r"); if (!fp) { printf("Unable to execute command \"%s\": %s\n", shell_cmd, strerror(errno)); ok = false; } else { char * a_line = NULL; size_t len = 0; bool first_line = true; while ( getline(&a_line, &len, fp) >= 0) { if (strlen(a_line) > 0) { // printf("(%s) a_line: |%s|\n", __func__, a_line); int ch = a_line[strlen(a_line)-1]; if (debug) { if (ch != '\n') printf("(%s) Truncating character '%c' (0x%02x)\n", __func__, ch, ch); // else // printf("(%s) Truncating expected NL (0x%02x)\n", __func__, ch); } a_line[strlen(a_line)-1] = '\0'; } else printf("(%s) Zero length line\n", __func__); if (first_line) { if (str_ends_with(a_line, "not found")) { // printf("(%s) found \"not found\"\n", __func__); ok = false; break; } first_line = false; } if (debug && !str_all_printable(a_line)) { printf("(%s) String contains non-printable character!\n", __func__); } // printf("%s", "\n"); // solves the missing line problem, but why? if (depth < 0) { fputs(a_line, stdout); fputs("\n", stdout); } else { // n. output will be sent to current rpt_ dest ! rpt_title(a_line, depth); } free(a_line); // 1/2018 was commented out, why? a_line = NULL; len = 0; } // per getline() doc, buffer is allocated even if getline() fails free(a_line); int pclose_rc = pclose(fp); int errsv = errno; if (debug) printf("(%s) pclose() rc=%d, error=%d - %s\n", __func__, pclose_rc, errsv, strerror(errsv)); } free(cmdbuf); return ok; } /** Executes a shell command and writes the output to stdout. * * @param shell_cmd command to execute * * @return true command succeeded * false failed, e.g. command not found */ bool execute_shell_cmd(const char * shell_cmd) { return execute_shell_cmd_rpt(shell_cmd, -1); } /** Executes a shell command and returns the output as an array of strings. * * @param shell_cmd command to execute * * @return :GPtrArray of response lines if command succeeded * NULL if command failed, e.g. command not found * * @remark * **g_free** is set as the free function on the returned array */ GPtrArray * execute_shell_cmd_collect(const char * shell_cmd) { bool debug = false; GPtrArray * result = g_ptr_array_new_with_free_func(g_free); if (debug) printf("(%s) Starting. shell_cmd = |%s|\n", __func__, shell_cmd); bool ok = true; FILE * fp; int bufsz = strlen(shell_cmd) + 50; char * cmdbuf = calloc(1, bufsz); snprintf(cmdbuf, bufsz, "(%s) 2>&1", shell_cmd); // printf("(%s) cmdbuf=|%s|\n", __func__, cmdbuf); fp = popen(cmdbuf, "r"); // printf("(%s) open. errno=%d\n", __func__, errno); if (!fp) { // int errsv = errno; fprintf(stderr, "Unable to execute command \"%s\": %s\n", shell_cmd, strerror(errno)); ok = false; } else { char * a_line = NULL; size_t len = 0; bool first_line = true; while ( getline(&a_line, &len, fp) >= 0) { if (strlen(a_line) > 0) a_line[strlen(a_line)-1] = '\0'; if (debug) printf("(%s) a_line = |%s|\n", __func__, a_line); if (first_line) { if (str_ends_with(a_line, "not found")) { // printf("(%s) found \"not found\"\n", __func__); ok = false; break; } first_line = false; } g_ptr_array_add(result, g_strdup(a_line)); free(a_line); a_line = NULL; len = 0; } free(a_line); int pclose_rc = pclose(fp); if (debug) printf("(%s) plose() rc = %d\n", __func__, pclose_rc); } if (!ok) { g_ptr_array_free(result, true); result = NULL; } free(cmdbuf); return result; } /** Execute a shell command and return the contents in a newly allocated * #GPtrArray of lines. Optionally, keep only those lines containing at least * one in a list of terms. After filtering, the set of returned lines may * be further reduced to either the first or last n number of lines. * * \param cmd command to execute * \param fn file name * \param filter_terms #Null_Terminated_String_Array of filter terms * \param ignore_case ignore case when testing filter terms * \param limit if 0, return all lines that pass filter terms * if > 0, return at most the first #limit lines that satisfy the filter terms * if < 0, return at most the last #limit lines that satisfy the filter terms * \param result_loc address at which to return a pointer to the newly allocate #GPtrArray * \return if >= 0, number of lines before filtering and limit applied * if < 0, -errno */ int execute_cmd_collect_with_filter( const char * shell_cmd, char ** filter_terms, bool ignore_case, int limit, GPtrArray ** result_loc) { bool debug = false; if (debug) printf("(%s) cmd|%s|, ct(filter_terms)=%d, ignore_case=%s, limit=%d\n", __func__, shell_cmd, ntsa_length(filter_terms), sbool(ignore_case), limit); int rc = 0; GPtrArray *line_array = execute_shell_cmd_collect(shell_cmd); if (!line_array) { rc = -1; } else { rc = line_array->len; if (rc > 0) { filter_and_limit_g_ptr_array( line_array, filter_terms, ignore_case, limit, false); // line_array has free function set } } *result_loc = line_array; if (debug) printf("(%s) Returning: %d\n", __func__, rc); return rc; } /** Executes a shell command that always outputs a single line and returns the * output as a newly allocated character string * * @param shell_cmd command to execute * * @return :response if command succeeded * NULL if command failed, e.g. command not found * * @remark * Caller is responsible for freeing the returned string. */ char * execute_shell_cmd_one_line_result(const char * shell_cmd) { char * result = NULL; GPtrArray * response = execute_shell_cmd_collect(shell_cmd); if (response) { result = g_strdup(g_ptr_array_index(response, 0)); g_ptr_array_free(response, true); } return result; } /** Tests if a command is found in path * * @param cmd command name * * @return true/false * * TODO: Check that actually executable, * e.g. could be in /sbin and not running privileged */ bool is_command_in_path(const char * cmd) { bool result = false; char shell_cmd[100]; snprintf(shell_cmd, sizeof(shell_cmd), "which %s", cmd); GPtrArray * resp = execute_shell_cmd_collect(shell_cmd); if (resp) { if (resp->len > 0) result = true; g_ptr_array_free(resp, true); } return result; } /** Tests if a command is executable. * * \param cmd command to test execute * \retval 0 ok * \retval 127 command not found * \retval 2 command requires sudo * \retval 1 command executed, but with some error */ int test_command_executability(const char * cmd) { assert(cmd); char * full_cmd = calloc(1, strlen(cmd) + 20); strcpy(full_cmd, cmd); strcat(full_cmd, ">/dev/null 2>&1"); // printf("(%s) cmd: |%s|, full_cmd: |%s|\n", __func__, cmd, full_cmd); int rc = system(full_cmd); // printf("(%s) system(%s) returned: %d, %d, %d\n", __func__, full_cmd, rc, WIFEXITED(rc), WEXITSTATUS(rc)); free(full_cmd); // 0 ok // 127 command not found // 2 on dmidecode - not running sudo // 2 on i2cdetect - not sudo // 1 on i2cdetect - sudo, but some error #ifdef TARGET_BSD return (rc & 0xff00) >> 8; #else return WEXITSTATUS(rc); #endif } ddcutil-2.2.0/src/util/timestamp.c0000644000175000001440000001606514754153540012553 /** @file timestamp.c * * Timestamp management */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include /** \endcond */ #include "glib_util.h" #include "string_util.h" #include "timestamp.h" // // Timestamp Generation // /** For debugging timestamp generation, maintain a timestamp history. */ bool tracking_timestamps = false; // set true to enable timestamp history #define MAX_TIMESTAMPS 1000 // static long timestamp[MAX_TIMESTAMPS]; static int timestamp_ct = 0; static uint64_t * timestamp_history = NULL; /** Returns the current value of the realtime clock in nanoseconds. * * @return timestamp, in nanoseconds * * @remark * If debugging timestamp generation, the timestamp is remembered. */ uint64_t cur_realtime_nanosec() { // on Pi, __time_t resolves to long int struct timespec tvNow; clock_gettime(CLOCK_REALTIME, &tvNow); // long result = (tvNow.tv_sec * 1000) + (tvNow.tv_nsec / (1000 * 1000) ); // milliseconds // long result = (tvNow.tv_sec * 1000 * 1000) + (tvNow.tv_nsec / 1000); // microseconds // wrong on 32 // uint64_t result0 = tvNow.tv_sec * (1000 * 1000 * 1000) + tvNow.tv_nsec; // NANOSEC // printf("(%s) result0=%"PRIu64"\n", __func__, result0); // wrong on 32 // uint64_t result1 = tvNow.tv_sec * (1000 * 1000 * 1000); // printf("(%s) result1=%"PRIu64"\n", __func__, result1); // ok uint64_t result = tvNow.tv_sec * (uint64_t)(1000*1000*1000); // printf("(%s) result=%"PRIu64"\n", __func__, result); // ok // uint64_t result3 = tvNow.tv_sec * (uint64_t)1000000000; // printf("(%s) result3=%"PRIu64"\n", __func__, result3); // wrong value on 32 bit // uint64_t result4 = tvNow.tv_sec * (uint64_t)1000000000 + tvNow.tv_sec; // printf("(%s) result4=%"PRIu64"\n", __func__, result4); // wrong value on 32 bit // uint64_t result6 = (tvNow.tv_sec * (uint64_t)1000000000) + (uint64_t)tvNow.tv_sec; // printf("(%s) result6=%"PRIu64"\n", __func__, result6); // uint64_t result2 = tvNow.tv_sec; // printf("(%s) result2=%"PRIu64"\n", __func__, result2); // result2 *= (1000*1000*1000); // printf("(%s) result2=%"PRIu64"\n", __func__, result2); // must do addition separately on 32 bit, ow. get bad value result += tvNow.tv_nsec; // printf("(%s) result=%"PRIu64"\n", __func__, result); if (tracking_timestamps && timestamp_ct < MAX_TIMESTAMPS) { if (!timestamp_history) { timestamp_ct = 0; timestamp_history = calloc(MAX_TIMESTAMPS, sizeof(uint64_t)); } timestamp_history[timestamp_ct++] = result; } // printf("(%s) tv_sec=%ld, tv_nsec=%10ld, Returning: %"PRIu64"\n", // __func__, tvNow.tv_sec, tvNow.tv_nsec, result); return result; } /** Reports history of generated timestamps * * @remark * This is a debugging function. */ void show_timestamp_history() { if (tracking_timestamps && timestamp_history) { // n. DBGMSG writes to FOUT printf("Total timestamps: %d\n", timestamp_ct); bool monotonic = true; int ctr = 0; for (; ctr < timestamp_ct; ctr++) { printf(" timestamp[%d] = %15" PRIu64 "\n", ctr, timestamp_history[ctr] ); if (ctr > 0 && timestamp_history[ctr] <= timestamp_history[ctr-1]) { printf(" !!! NOT STRICTLY MONOTONIC !!!\n"); monotonic = false; } } printf("Timestamps are%s strictly monotonic\n", (monotonic) ? "" : " NOT"); } else printf("Not tracking timestamps\n"); } static uint64_t initial_timestamp_nanos = 0; /** Returns the elapsed time in nanoseconds since the start of * program execution. * * The first call to this function marks the start of program * execution and returns 0. * * @return nanoseconds since start of program execution */ uint64_t elapsed_time_nanosec() { // printf("(%s) initial_timestamp_nanos=%"PRIu64"\n", __func__, initial_timestamp_nanos); uint64_t cur_nanos = cur_realtime_nanosec(); if (initial_timestamp_nanos == 0) initial_timestamp_nanos = cur_nanos; uint64_t result = cur_nanos - initial_timestamp_nanos; // printf("(%s) Returning: %"PRIu64"\n", __func__, result); return result; } static uint64_t ipow(const uint64_t base, guint n) { int p = base; if (n == 0) return 1; for (int i = 1; i < n; ++i) p *= base; return p; } /** Returns the elapsed time in seconds since start of program execution * as a formatted, printable string. * * The string is built in a thread specific private buffer. The returned * string is valid until the next call of this function in the same thread. * * @param precision number of digits after the decimal point * @return formatted elapsed time */ char * formatted_elapsed_time_t(guint precision) { static GPrivate formatted_elapsed_time_key = G_PRIVATE_INIT(g_free); char * elapsed_buf = get_thread_fixed_buffer(&formatted_elapsed_time_key, 40); uint64_t et_nanos = elapsed_time_nanosec(); uint64_t isecs = et_nanos/ (1000 * 1000 * 1000); uint64_t adjusted_isecs = isecs * ipow(10,precision); uint64_t fractional_units = et_nanos / ipow(10, (9-precision)); // printf("(%s) et_nanos=%"PRIu64", isecs=%"PRIu64", fractional_units=%"PRIu64", adjusted_isecs=%"PRIu64"\n", // __func__, et_nanos, isecs, fractional_units, adjusted_isecs); snprintf(elapsed_buf, 40, "%3"PRIu64".%0*"PRIu64"", isecs, precision, (fractional_units-adjusted_isecs) ); // printf("(%s) |%s|\n", __func__, elapsed_buf); return elapsed_buf; } /** Returns returns a time in nanoseconds as a formatted, printable string * in the form SECONDS.MILLISECONDS. * * The string is built in a thread specific private buffer. The returned * string is valid until the next call of this function in the same thread. * * @param start start time, in nanoseconds * @param end end time, in nanoseconds * @return formatted time difference */ char * formatted_time_t(uint64_t nanos) { static GPrivate formatted_time_key = G_PRIVATE_INIT(g_free); char * elapsed_buf = get_thread_fixed_buffer(&formatted_time_key, 40); uint64_t isecs = nanos/ (1000 * 1000 * 1000); uint64_t imillis = nanos/ (1000 * 1000); snprintf(elapsed_buf, 40, "%3"PRIu64".%03"PRIu64"", isecs, imillis - (isecs*1000) ); return elapsed_buf; } /** Thread safe function that returns a string representation of an epoch * time value. The returned value is valid until the next call to this * function on the current thread. * * \param epoch_time * \return string representation */ char * formatted_epoch_time_t(time_t epoch_seconds) { static GPrivate formatted_epoch_time_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_fixed_buffer(&formatted_epoch_time_key, 40); struct tm broken_down_time; localtime_r(&epoch_seconds, &broken_down_time); strftime(buf, 40, "%b %d %T", &broken_down_time); return buf; } ddcutil-2.2.0/src/util/traced_function_stack.c0000644000175000001440000004115314754153540015100 /** @file traced_function_stack.c */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include "backtrace.h" #include "common_inlines.h" #include "common_printf_formats.h" #include "debug_util.h" #include "glib_util.h" #include "string_util.h" #include "traced_function_stack.h" bool traced_function_stack_enabled = false; bool traced_function_stack_errors_fatal = false; __thread bool traced_function_stack_suspended = false; __thread bool debug_tfs = false; __thread GQueue * traced_function_stack; static GPtrArray * all_traced_function_stacks = NULL; static GMutex all_traced_function_stacks_mutex; static __thread bool traced_function_stack_invalid = false; static void list_traced_function_stacks(); bool set_debug_thread_tfs(bool newval) { bool old = debug_tfs; debug_tfs = newval; // printf("(%s) debug_tfs\n", sbool(debug_tfs)); return old; } /** Delete all entries in the traced function stack for the current thread, * and reset the traced_function_stack flag. */ void reset_current_traced_function_stack() { if (traced_function_stack) { int ct = g_queue_get_length(traced_function_stack); for (int ctr = 0; ctr 0) { // printf(PRItid"traced function stack (addr=%p, len=%d:\n", TID(), stack, queue_len ); if (reverse) { for (int ndx = g_queue_get_length(stack)-1; ndx >=0 ; ndx--) { printf(" %s\n", (char*) g_queue_peek_nth(stack, ndx)); } } else { for (int ndx = 0; ndx < g_queue_get_length(stack); ndx++) { printf(" %s\n", (char*) g_queue_peek_nth(stack, ndx)); } } } else { printf(" EMPTY\n"); } } } void collect_traced_function_stack(GPtrArray* collector, GQueue* stack, bool reverse, int stack_adjust) { if (stack && collector) { // printf(PRItid" Traced function stack %p:\n", TID(), stack); int queue_len = g_queue_get_length(stack) - stack_adjust; if (queue_len > 0) { // printf(PRItid"traced function stack (addr=%p, len=%d:\n", TID(), stack, queue_len ); if (reverse) { for (int ndx = g_queue_get_length(stack)-stack_adjust; ndx >=0 ; ndx--) { g_ptr_array_add(collector, strdup(g_queue_peek_nth(stack, ndx))); } } else { for (int ndx = 0; ndx < g_queue_get_length(stack); ndx++) { g_ptr_array_add(collector, strdup(g_queue_peek_nth(stack, ndx))); } } } } } void traced_function_stack_to_syslog(GQueue* callstack, int syslog_priority, bool reverse) { if (!callstack) { syslog(LOG_PERROR|LOG_ERR, "traced_function_stack unavailable"); } else { GPtrArray * collector = g_ptr_array_new_with_free_func(g_free); collect_traced_function_stack(collector, callstack, reverse, 2); // was 2 // syslog(syslog_priority, "Traced function stack %p:", callstack); if (collector->len == 0) syslog(syslog_priority, " EMPTY"); else { for (int ndx = 0; ndx < collector->len; ndx++) { syslog(syslog_priority, " %s", (char *) g_ptr_array_index(collector, ndx)); } } g_ptr_array_free(collector, true); } } void current_traced_function_stack_to_syslog(int syslog_priority, bool reverse) { bool debug = false; if (debug) list_traced_function_stacks(); if (!traced_function_stack) syslog(LOG_PERROR|LOG_ERR, "No traced function stack for current thread"); else { syslog(syslog_priority, "Traced function stack %p for current thread "PRItid, traced_function_stack, TID()); traced_function_stack_to_syslog(traced_function_stack, syslog_priority, reverse); } } /** Reports the contents of the specified traced function stack for the * current thread. * * @param reverse order of entries */ void debug_current_traced_function_stack(bool reverse) { bool debug = false; if (debug) list_traced_function_stacks(); if (traced_function_stack) { debug_traced_function_stack(traced_function_stack, reverse); } else { printf(PRItid" no traced function stack\n", TID()); } } /** Returns the contents of the traced function stack for the current thread * as a GPtrArray of function names. * * @param most_recent_last specifies order * @return GPtrArray containing copies of the function names on the stack. */ GPtrArray * get_current_traced_function_stack_contents(bool most_recent_last) { GPtrArray* callstack = g_ptr_array_new_with_free_func(g_free); int qsize = g_queue_get_length(traced_function_stack); if (most_recent_last) { for (int ndx = 0; ndx < qsize; ndx++) { g_ptr_array_add(callstack, strdup((char*) g_queue_peek_nth(traced_function_stack, ndx))); } } else { for (int ndx = qsize-1; ndx >= 0; ndx--) { g_ptr_array_add(callstack, strdup((char*) g_queue_peek_nth(traced_function_stack, ndx))); } } return callstack; } typedef struct { GQueue * traced_function_stack; pid_t thread_id; char * initial_function; } All_Traced_Function_Stacks_Entry; void free_traced_function_stacks_entry(All_Traced_Function_Stacks_Entry* entry) { free(entry->initial_function); free(entry); } /** Lists all the traced function stacks. */ static void list_traced_function_stacks() { g_mutex_lock(&all_traced_function_stacks_mutex); if (!all_traced_function_stacks) { printf("No traced function stacks found.\n"); } else { printf("Traced function stacks:\n"); for (int ndx = 0; ndx < all_traced_function_stacks->len; ndx++) { All_Traced_Function_Stacks_Entry* entry = g_ptr_array_index(all_traced_function_stacks, ndx); printf(" thread: "PRItid" stack: %p initial function: %s\n", (intmax_t)entry->thread_id, entry->traced_function_stack, entry->initial_function); } } g_mutex_unlock(&all_traced_function_stacks_mutex); } /** Creates a traced function stack on the current thread * and adds it to the list of traced function stacks * on all threads. */ static GQueue * new_traced_function_stack(const char * funcname) { bool debug = false; debug = debug | debug_tfs; if (debug) { printf(PRItid"(%s) Starting. initial function: %s\n", TID(), __func__, funcname); list_traced_function_stacks(); } GQueue* result = g_queue_new(); g_mutex_lock(&all_traced_function_stacks_mutex); if (!all_traced_function_stacks) all_traced_function_stacks = g_ptr_array_new_with_free_func( (GDestroyNotify) free_traced_function_stacks_entry); All_Traced_Function_Stacks_Entry * entry = calloc(1, sizeof(All_Traced_Function_Stacks_Entry)); entry->traced_function_stack = result; entry->thread_id = tid(); entry->initial_function = strdup(funcname); // printf("entry=%p\n", entry); g_ptr_array_add(all_traced_function_stacks, entry); g_mutex_unlock(&all_traced_function_stacks_mutex); if (debug) printf(PRItid"(%s) Done. Returning %p\n", TID(), __func__, result); return result; } /** Pushes a copy of a function name onto the traced function stack for the * current thread. * * @param funcname function name */ void push_traced_function(const char * funcname) { // printf("(%s) debug_tfs = %s\n", __func__, sbool(debug_tfs)); bool debug = false; debug = debug | debug_tfs; if (debug) { printf(PRItid"(push_traced_function) funcname = %s, traced_function_stack_enabled=%d\n", TID(), funcname, traced_function_stack_enabled); syslog(LOG_DEBUG, PRItid"(push_traced_function) funcname = %s, traced_function_stack_enabled=%d\n", TID(), funcname, traced_function_stack_enabled); } if (traced_function_stack_enabled && !traced_function_stack_suspended) { if (!traced_function_stack) { traced_function_stack = new_traced_function_stack(funcname); if (debug) printf(PRItid"(push_traced_function) allocated new traced_function_stack %p, starting with %s\n", TID(), traced_function_stack, funcname); } g_queue_push_head(traced_function_stack, g_strdup(funcname)); } else { if (debug) fprintf(stderr, "traced_function_stack is disabled\n"); } // if (debug) { printf(PRItid" (%s) Done\n", TID(), __func__); show_backtrace(0); debug_current_traced_function_stack(false); } } /** Returns the function name on the top of the stack for the current thread. * * @return function name, null if the stack is empty. Caller should not free. */ char * peek_traced_function() { bool debug = false; if (debug) printf(PRItid"(%s) Starting.\n", TID(), __func__); char * result = NULL; if (traced_function_stack && !traced_function_stack_invalid) { result = g_queue_peek_head(traced_function_stack); // or g_strdup() ??? } if (debug) printf(PRItid"(%s), returning %s\n", TID(), __func__, result); return result; } static void tfs_error_msg(char * format, ...) { char msgbuf[300]; va_list(args); va_start(args, format); g_vsnprintf(msgbuf, 300, format, args); va_end(args); fprintf(stderr, "%s\n", msgbuf); syslog(LOG_ERR, "%s", msgbuf); } /** Removes the function name on the top of the stack. * * If the popped function name does not match the expected name, * the traced function stack is corrupt. In that case, diagnostics * are written to both the terminal and the system log. If flag * #traced_function_stack_errors_fatal is set, program execution * terminates with an assert() failure. If not, thread global * variable #traced_function_stack_invalid is set, marking the * stack unusable until the stack is emptied. * * @param funcname expected function name */ void pop_traced_function(const char * funcname) { bool debug = false; debug = debug | debug_tfs; if (traced_function_stack_enabled && !traced_function_stack_suspended && !traced_function_stack_invalid) { if (!traced_function_stack) { fprintf(stderr, PRItid"(%s) funcname=%s. No traced function stack\n", TID(), __func__, funcname); list_traced_function_stacks(); } else { char * popped_func = g_queue_pop_head(traced_function_stack); if (!popped_func) { tfs_error_msg(PRItid" traced_function_stack=%p, expected %s, traced_function_stack is empty", TID(), traced_function_stack, funcname); tfs_error_msg(PRItid" Function %s likely did not call push_traced_function() at start", TID(), funcname); show_backtrace(1); backtrace_to_syslog(1,true); traced_function_stack_invalid = true; if (traced_function_stack_errors_fatal) ASSERT_WITH_BACKTRACE(0); } else { if (!streq(popped_func, funcname)) { tfs_error_msg(PRItid" traced_function_stack=%p, !!! popped traced function %s, expected %s", TID(), traced_function_stack, popped_func, funcname); char * look_ahead = peek_traced_function(); if (streq(look_ahead, funcname)) { tfs_error_msg(PRItid" Function %s does not call pop_traced_function() at end", TID(), funcname); } else { tfs_error_msg(PRItid" Function %s likely did not call push_traced_function() at start", TID(), funcname); } debug_current_traced_function_stack(/*reverse=*/ false); show_backtrace(1); backtrace_to_syslog(LOG_ERR, /* stack_adjust */ 1); current_traced_function_stack_to_syslog(LOG_ERR, /*reverse*/ false); traced_function_stack_invalid = true; if (traced_function_stack_errors_fatal) ASSERT_WITH_BACKTRACE(0); } else { if (debug) { fprintf(stdout, PRItid"(%s) Popped %s\n", TID(), __func__, popped_func); syslog(LOG_DEBUG, PRItid"(%s) Popped %s", TID(), __func__, popped_func); } } free(popped_func); } } } } /** Frees the specified traced function stack * * @param stack pointer to stack * * @remark * Must be called with #all_traced_function_stacks_mutex locked. */ static void free_traced_function_stack(GQueue * stack) { bool debug = false; if (debug) { printf(PRItid"(%s) Starting. stack=%p\n", TID(), __func__, traced_function_stack); if (stack) { printf(PRItid"(free_traced_function_stack) Final contents of traced_function_stack:\n", TID()); debug_traced_function_stack(stack, true); } } if (stack) { g_queue_free_full(stack, g_free); g_ptr_array_remove(all_traced_function_stacks, stack); } if (debug) printf(PRItid"(%s) Done.\n", TID(), __func__); } /** Frees the traced function stack on the current thread. * * Must be called WITHOUT all_traced_function_stacks_mutex locked */ void free_current_traced_function_stack() { bool debug = false; if (traced_function_stack) { if (debug) { printf(PRItid"(free_current_traced_function_stack) traced_function_stack=%p. Executing.\n", TID(), traced_function_stack); } g_mutex_lock(&all_traced_function_stacks_mutex); free_traced_function_stack(traced_function_stack); g_mutex_unlock(&all_traced_function_stacks_mutex); } } /** Frees all traced function stacks. * * Must be called without #all_traced_function_stacks_mutex locked. */ void free_all_traced_function_stacks() { bool debug = true; if (debug) { printf(PRItid"(%s) Starting.\n", TID(), __func__); } g_mutex_lock(&all_traced_function_stacks_mutex); // g_queue_set_free_func(all_traced_function_stacks, g_free); if (all_traced_function_stacks) { printf("Found %d traced function stack(s)\n", all_traced_function_stacks->len); for (int ndx = all_traced_function_stacks->len-1; ndx >= 0; ndx--) { All_Traced_Function_Stacks_Entry * entry = g_ptr_array_index(all_traced_function_stacks, ndx); // printf("entry=%p\n", entry); if (debug) printf("Freeing traced function stack for thread %d\n", entry->thread_id); free_traced_function_stack(entry->traced_function_stack); g_ptr_array_remove_index(all_traced_function_stacks, ndx); free(entry); } g_ptr_array_free(all_traced_function_stacks, true); all_traced_function_stacks = NULL; } else { printf(PRItid"(%s) traced_function_stacks not set\n", TID(), __func__); } g_mutex_unlock(&all_traced_function_stacks_mutex); if (debug) printf(PRItid"(%s) Done.\n", TID(), __func__); }; #ifdef INCLUDE_ONLY_IF_NEEDED_FOR_DEBUGGING /** UNSAFE - FOR DEBUGGING USE ONLY */ void dbgrpt_all_traced_function_stacks() { bool debug = true; if (all_traced_function_stacks) { for (int ndx = all_traced_function_stacks->len-1; ndx >= 0; ndx--) { All_Traced_Function_Stacks_Entry * entry = g_ptr_array_index(all_traced_function_stacks, ndx); // printf("entry=%p\n", entry); if (debug) printf("Reporting traced function stack %p for thread %d\n", entry->traced_function_stack, entry->thread_id); debug_traced_function_stack(entry->traced_function_stack, false); } } else { printf(PRItid"(%s) traced_function_stacks not set\n", TID(),__func__); } } #endif ddcutil-2.2.0/src/util/utilrpt.c0000666000175000001440000000327613230570533012250 /* utilrpt.c * * * Copyright (C) 2014-2017 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ /** \f * Report functions for other utility modules. * Avoids complex dependencies between report_util.c and other * util files. */ #include "data_structures.h" #include "report_util.h" #include "utilrpt.h" /** Displays all fields of a #Buffer. * This is a debugging function. * * @param buffer pointer to Buffer instance * @param depth logical indentation depth * * @remark * Output is written to the current report destination. */ void dbgrpt_buffer(Buffer * buffer, int depth) { rpt_vstring(depth, "Buffer at %p, bytes addr=%p, len=%d, max_size=%d", buffer, buffer->bytes, buffer->len, buffer->buffer_size); // printf(" bytes end addr=%p\n", buffer->bytes+buffer->buffer_size); if (buffer->bytes) rpt_hex_dump(buffer->bytes, buffer->len, depth); } ddcutil-2.2.0/src/util/xdg_util.c0000644000175000001440000003465614754153540012375 /** \file xdg_util.c * * Implement XDG Base Directory Specification * * See https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html */ // Copyright (C) 2020-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include #include "xdg_util.h" /** Checks if a regular file exists. * * @param fqfn fully qualified file name * @return true/false * @remark Returns false if **fqfn** is NULL * Trivial function copied from file_util.c to avoid dependency. */ static bool regular_file_exists(const char * fqfn) { bool result = false; if (fqfn) { struct stat stat_buf; int rc = stat(fqfn, &stat_buf); if (rc == 0) { result = S_ISREG(stat_buf.st_mode); } } return result; } /** Returns the name of the base data, configuration, or cache directory. * First the specified environment variable is checked. * If no value is found the name is constructed from $HOME and * the specified sub-directory. * * The returned value is guaranteed to end in '/'. * * Caller is responsible for freeing the returned memory. * * @param envvar_name * @param home_subdir_name * @return directory name, or NULL if undetermined */ static char * xdg_home_dir( const char * envvar_name, const char * home_subdir_name) { bool debug = false; char * xdg_home = getenv(envvar_name); // do not free if (xdg_home && strlen(xdg_home) > 0) { xdg_home = (xdg_home[strlen(xdg_home)-1] == '/') ? g_strdup(xdg_home) : g_strdup_printf("%s/", xdg_home); } else { char * home = getenv("HOME"); if (home && strlen(home) > 0) xdg_home = g_strdup_printf("%s/%s/", home, home_subdir_name); else xdg_home = NULL; } if (debug) printf("(%s) envvar_name=|%s|, home_subdir_name=|%s|, returning: %s\n", __func__, envvar_name, home_subdir_name, xdg_home); return xdg_home; } /** Returns the name of the xdg base directory for data files, or * NULL if not set. * * Caller is responsible for freeing the returned memory. */ char * xdg_data_home_dir() { bool debug = false; char * result = xdg_home_dir("XDG_DATA_HOME", ".local/share"); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the name of the xdg base directory for configuration files, * or NULL if not set. * * Caller is responsible for freeing the returned memory. */ char * xdg_config_home_dir() { bool debug = false; char * result = xdg_home_dir("XDG_CONFIG_HOME", ".config"); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the name of the xdg base directory for cached files, * or NULL if not set * * Caller is responsible for freeing the returned memory. */ char * xdg_cache_home_dir() { bool debug = false; char * result = xdg_home_dir("XDG_CACHE_HOME", ".cache"); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the name of the xdg base directory for state files, * or NULL if not set * * Caller is responsible for freeing the returned memory. */ char * xdg_state_home_dir() { bool debug = false; char * result = xdg_home_dir("XDG_STATE_HOME", ".local/state"); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the value of the specified environment variable, * If the value is blank, return default_dirs. * * Caller is responsible for freeing the returned memory. */ static char * xdg_dirs( const char * envvar_name, const char * default_dirs) { bool debug = false; char * xdg_dirs = getenv(envvar_name); // do not free if (xdg_dirs && strlen(xdg_dirs) > 0) xdg_dirs = g_strdup(xdg_dirs); else { xdg_dirs = g_strdup(default_dirs); } if (debug) printf("(%s) Returning: %s\n", __func__, xdg_dirs); assert(xdg_dirs); return xdg_dirs; } /** Returns the value of $XDG_DATA_DIRS or the default "/usr/local/share:/usr/share" * * Caller is responsible for freeing the returned memory. */ char * xdg_data_dirs() { return xdg_dirs("XDG_DATA_DIRS", "/usr/local/share/:/usr/share"); } /** Returns the value of $XDG_CONFIG_DIRS, or the default "/etc/xdg" * * Caller is responsible for freeing the returned memory. */ char * xdg_config_dirs() { return xdg_dirs("XDG_CONFIG_DIRS", "/etc/xdg"); } /** Returns a path string containing value of the XDG data home directory, * followed by the XDG data dirs string. * * Caller is responsible for freeing the returned memory. */ char * xdg_data_path() { bool debug = false; char * result = NULL; char * home_dir = xdg_data_home_dir(); char * dirs = xdg_data_dirs(); assert(dirs); if (home_dir) { result = g_strdup_printf("%s:%s", home_dir, dirs); free(home_dir); free(dirs); } else result = dirs; if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns a path string containing value of the XDG configuration home directory, * followed by the XDG config dirs string. * * Caller is responsible for freeing the returned memory. */ char * xdg_config_path() { bool debug = false; char * result = NULL; char * home_dir = xdg_config_home_dir(); char * dirs = xdg_config_dirs(); assert(dirs); if (home_dir) { result = g_strdup_printf("%s:%s", home_dir, dirs); free(home_dir); free(dirs); } else result = dirs; if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the fully qualified name of a file in the application * sub-directory of $XDG_DATA_HOME. * Does not check for the file's existence * * Caller is responsible for freeing the returned memory. */ char * xdg_data_home_file(const char * application, const char * simple_fn) { bool debug = false; char * result = NULL; char * dir = xdg_data_home_dir(); if (dir && strlen(dir) > 0) result = g_strdup_printf("%s%s/%s", dir, application, simple_fn); free(dir); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the fully qualified name of a file in the application * sub-directory of $XDG_CONFIG_HOME. * Does not check for the file's existence * * Caller is responsible for freeing the returned memory. */ char * xdg_config_home_file(const char * application, const char * simple_fn) { bool debug = false; char * result = NULL; char * dir = xdg_config_home_dir(); if (dir && strlen(dir) > 0) result = g_strdup_printf("%s%s/%s", dir, application, simple_fn); free(dir); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the fully qualified name of a file in the application * sub-directory of $XDG_CACHE_HOME. * Does not check for the file's existence * * Caller is responsible for freeing the returned memory. */ char * xdg_cache_home_file(const char * application, const char * simple_fn) { bool debug = false; char * result = NULL; char * dir = xdg_cache_home_dir(); if (dir && strlen(dir) > 0) result = g_strdup_printf("%s%s/%s", dir, application, simple_fn); free(dir); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } /** Returns the fully qualified name of a file in the application * sub-directory of $XDG_STATE_HOME. * Does not check for the file's existence * * Caller is responsible for freeing the returned memory. */ char * xdg_state_home_file(const char * application, const char * simple_fn) { bool debug = false; char * result = NULL; char * dir = xdg_state_home_dir(); if (dir && strlen(dir) > 0) result = g_strdup_printf("%s%s/%s", dir, application, simple_fn); free(dir); if (debug) printf("(%s) Returning: %s\n", __func__, result); return result; } typedef struct { char * iter_start; char * iter_end; } Iter_State; static void xdg_dirs_iter_init(char * dir_list, Iter_State * state) { state->iter_start = dir_list; // to avoid const warnings state->iter_end = state->iter_start + strlen(dir_list); } static char * xdg_dirs_iter_next(Iter_State * state) { bool debug = false; if (state->iter_start >= state->iter_end) return NULL; char * p = state->iter_start; while (p < state->iter_end && *p != ':') p++; int len = p - state->iter_start; char * buf = calloc(len + 1, 1); memcpy(buf, state->iter_start, len); state->iter_start = p + 1; if (debug) printf("(%s) Returning: %s\n", __func__, buf); return buf; } /* Caller is responsible for freeing the returned memory. */ static char * find_xdg_path_file( const char * path, const char * application, const char * simple_fn) { bool debug = false; if (debug) { printf("(%s) Starting. application = %s, simple_fn=%s\n", __func__, application, simple_fn); printf("(%s) Starting. path=%s\n", __func__, path); } if (!path) return NULL; Iter_State iter_state; char * next_dir = NULL; char * fqfn = NULL; char *path2 = g_strdup(path); xdg_dirs_iter_init(path2, &iter_state); while ( !fqfn && (next_dir = xdg_dirs_iter_next(&iter_state)) ) { int lastndx = strlen(next_dir) - 1; if (next_dir[lastndx] == '/') next_dir[lastndx] = '\0'; fqfn = g_strdup_printf("%s/%s/%s", next_dir, application, simple_fn); free(next_dir); if (debug) printf("(%s) Checking: %s\n", __func__, fqfn); // if (access(fqfn, R_OK)) { if (regular_file_exists(fqfn)) { continue; } free(fqfn); fqfn = NULL; } free(path2); if (debug) printf("(%s) Done. Returning: %s\n", __func__, fqfn); return fqfn; } /** Looks for a file first in the $XDG_DATA_HOME directory, * then in the $XDG_DATA_DIRS directories. * * \param application subdirectory name * \param simple_fn file name within subdirectory * \return fully qualified file name, or NULL if not found. * * Caller is responsible for freeing the returned memory. */ char * find_xdg_data_file( const char * application, const char * simple_fn) { bool debug = false; if (debug) printf("(%s) Starting. application=%s, simple_fn=%s\n", __func__, application, simple_fn); char * result = NULL; char * path = xdg_data_path(); if (path) { result = find_xdg_path_file(path, application, simple_fn); free(path); } if (debug) printf("(%s) Done. Returning: %s\n", __func__, result); return result; } /** Searches $XDG_CONFIG_HOME and then $XDG_CONFIG_DIRS for * a specified file in a particular application sub-directory. * * \param application subdirectory name * \param simple_fn file name within subdirectory * \return fully qualified file name, or NULL if not found. * * Caller is responsible for freeing the returned string. */ char * find_xdg_config_file( const char * application, const char * simple_fn) { bool debug = false; char * result = NULL; char * path = xdg_config_path(); result = find_xdg_path_file( path, application, simple_fn); free(path); if (debug) printf("(%s) application=%s, simple_fn=%s, returning: %s\n", __func__, application, simple_fn, result); return result; } /** Looks for a file in the specified subdirectory of $XDG_CACHE_HOME * * \param application subdirectory name * \param simple_fn file name within subdirectory * \return fully qualified file name, or NULL if not found. * * Caller is responsible for freeing the returned string. */ char * find_xdg_cache_file( const char * application, const char * simple_fn) { bool debug = false; char * result = NULL;; char * path = xdg_cache_home_dir(); assert(path); // will be null if $HOME not set, how to handle? result = find_xdg_path_file( path, application, simple_fn); free(path); if (debug) printf("(%s) application=%s, simple_fn=%s, returning: %s\n", __func__, application, simple_fn, result); return result; } /** Looks for a file in the specified subdirectory of $XDG_STATE_HOME * * \param application subdirectory name * \param simple_fn file name within subdirectory * \return fully qualified file name, or NULL if not found. * * Caller is responsible for freeing the returned string. */ char * find_xdg_state_file( const char * application, const char * simple_fn) { bool debug = false; char * result = NULL;; char * path = xdg_state_home_dir(); assert(path); // will be null if $HOME not set, how to handle? result = find_xdg_path_file( path, application, simple_fn); free(path); if (debug) printf("(%s) application=%s, simple_fn=%s, returning: %s\n", __func__, application, simple_fn, result); return result; } #ifdef TESTS void xdg_tests() { printf( "xdg_data_home_dir(): %s\n", xdg_data_home_dir() ); printf( "xdg_data_config_dir(): %s\n", xdg_config_home_dir() ); printf( "xdg_data_cache_dir(): %s\n", xdg_cache_home_dir() ); printf( "xdg_data_dirs(): %s\n", xdg_data_dirs() ); printf( "xdg_config_dirs(): %s\n", xdg_config_dirs() ); printf( "xdg_data_path(): %s\n", xdg_data_path() ); printf( "xdg_config_path(): %s\n", xdg_config_path() ); printf( "xdg_data_home_file(\"ddcutil\", \"something.mccs\"): %s", xdg_data_home_file("ddcutil", "something.mccs")); printf( "xdg_config_home_file(\"ddcutil\", \"ddcutilrc\" ): %s", xdg_config_home_file("ddcutil", "ddcutilrc")); printf( "xdg_cache_home_file(\"ddcutil\", \"capabilities\" ): %s", xdg_cache_home_file("ddcutil", "capabilities")); printf( "find xdg_data_file(\"ddcutil\", \"something.mccs\"): %s", find_xdg_data_file("ddcutil", "something.mccs")); printf( "find_xdg_config_file(\"ddcutil\", \"ddcutilrc\"): %s", find_xdg_config_file("ddcutil", "ddcutilrc")); printf( "find_xdg_cache_file(\"ddcutil\", \"capabilities\"): %s", find_xdg_cache_file("ddcutil", "capabilities")); } #endif ddcutil-2.2.0/src/util/sysfs_filter_functions.c0000644000175000001440000002273714754153540015357 /** @file sysfs_filter_functions.c */ // Copyright (C) 2021-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include "debug_util.h" #include "report_util.h" #include "regex_util.h" #include "string_util.h" #include "sysfs_util.h" #include "sysfs_filter_functions.h" static const char * cardN_connector_pattern = "^card[0-9]+[-]"; static const char * cardN_pattern = "^card[0-9]+$"; static const char * D_00hh_pattern = "^[0-9]+-00[0-9a-fA-F]{2}$"; static const char * i2c_N_pattern = "^i2c-([0-9]+)$"; // // Predicate functions for filenames and attribute values, of // typedef Filname_Filter_Func // /** Tests if a value is a drm card identifier, e.g. "card1" * * @param value value to test * @result true/false */ bool predicate_cardN(const char * value) { bool debug = false; if (debug) printf("(%s) Starting. value = |%s|\n", __func__, value); bool result = compile_and_eval_regex(cardN_pattern, value); // bool b1 = str_starts_with(value, "card") && strlen(value) == 5; // if (debug) // printf("(%s) str_starts_with() && strlen() returned %s\n", __func__, sbool(b1)); // assert(b2 == b1); if (debug) printf("(%s) Returning: %s. value=|%s|\n", __func__, sbool(result), value); return result; } /** Tests if a value appears to be a DRM connector, e.g "card2-DP-1" * Only the initial part of the value being tested is actually checked. * * @param value value to test * @result true/false */ bool predicate_cardN_connector(const char * value) { bool debug = false; if (debug) printf("(%s) Starting. value=|%s|\n", __func__, value); bool b1 = compile_and_eval_regex(cardN_connector_pattern, value); if (debug) printf("(%s) Returning %s, value=|%s|\n", __func__, sbool( b1), value); return b1; } /** Tests if a value is an I2C bus identifier, e.g. "i2c-13" * * @param value value to test * @result true/false */ bool predicate_i2c_N(const char * value) { bool debug = false; bool b1 = compile_and_eval_regex(i2c_N_pattern, value); if (debug) printf("(%s) value=|%s|, returning %s\n", __func__, value, sbool( b1)); return b1; } #ifdef FUTURE // untested int match_i2c_N(const char * value) { bool debug = false; regmatch_t matchpos; int result = -1; if (compile_and_eval_regex(i2c_N_pattern, value, &matchpos)) { // pattern match ensures that the character after the end of the match is NULL, // and that atoi always succeeds result = atoi(value + matchpos.rm_so); } if (debug) printf("(%s) value=|%s|, returning %d\n", __func__, value, result); return result; } int match_dev_i2c_N(const char * value) { bool debug = false; int result = -1; if (str_starts_with(value, "/dev/")) { result = match_i2c_N(value+5); } if (debug) printf("(%s) value=|%s|, returning %d\n", __func__, value, result); return result; } #endif /** Tests if a value looks like "3-00a7", found in /sys/bus/i2c/devices * * @param value value to test * @result true/false */ bool predicate_any_D_00hh(const char * value) { bool debug = false; bool b1 = compile_and_eval_regex(D_00hh_pattern, value); if (debug) printf("(%s) value=|%s|, Returning %s\n", __func__, value, sbool( b1)); return b1; } /** Tests if a value (for a class attribute) indicates a display device, * e.g. the value starts with "0x03" * * @param value value to test * @result true/false */ bool class_display_device_predicate(const char * value) { return str_starts_with(value, "0x03"); } // // Predicate functions for filenames and attribute values, of // typedef Filname_Filter_Func_With_Arg // /** Tests if a filename has a specific value * * @param filename value to test * @param val value to test against * @return true/false */ bool fn_equal(const char * filename, const char * val) { return streq(filename, val); } /** Tests if a filename starts with a specific value * * @param filename value to test * @param val value to test against * @return true/false */ bool fn_starts_with(const char * filename, const char * val) { return str_starts_with(filename, val); } /** Tests if a value looks like "N-00HH", found in /sys/bus/i2c/devices * where HH is a specific hex value representing a bus number * * @param value value to test * @param sbusno I2c Bus number, as hex string * @result true/false */ // e.g. "3-00hh" where hh is bus number bool predicate_exact_D_00hh(const char * value, const char * sbusno) { bool debug = false; if (debug) printf("(%s) Starting. value=|%s|, sbusno=|%s|\n", __func__, value, sbusno); bool b1 = compile_and_eval_regex(D_00hh_pattern, value); if (b1) { // our utilities don't support extracting match groups char * hypos = strchr(value, '-'); // must succeed because of regex match char * s = substr(value, 0, (hypos-value)); b1 = streq(s, sbusno); free(s); } if (debug) printf("(%s) Returning %s\n", __func__, sbool( b1)); return b1; } // // Predicate functions for dirname/filename pairs, // i.e. functions of typedef Dir_Filter_Func // #ifdef MAYBE_FUTURE bool dirname_starts_with(const char * dirname, const char * val) { bool debug = false; DBGMSF(debug, "dirname=%s, val_fn=%s", dirname, val); bool result = str_starts_with(dirname, val); DBGMSF(debug, "Returning %s", sbool(result)); return result; #endif // for e.g. dirname = "i2c-3" bool is_i2cN_dir(const char * dirname, const char * fn_ignored) { bool debug = false; bool result = predicate_i2c_N(dirname); if (debug) printf("(%s) dirname=%s, fn_ignored=%s, returning %s\n", __func__, dirname, fn_ignored, sbool(result)); return result; } // test dirname starts with "drm_dp_aux" bool is_drm_dp_aux_subdir(const char * dirname, const char * fn_ignored) { bool debug = false; bool result = str_starts_with(dirname, "drm_dp_aux"); if (debug) printf("(%s) dirname=%s, fn_ignored=%s, returning %s\n", __func__, dirname, fn_ignored, sbool(result)); return result; } // for simple_fn e.g. card0-DP-1, dirname ignored bool is_card_connector_dir(const char * dirname, const char * simple_fn) { bool debug = false; DBGF(debug, "Starting. dirname=|%s|, simple_fn=|%s|", dirname, simple_fn); bool result = false; if (simple_fn) result = predicate_cardN_connector(simple_fn); DBGF(debug, "Done. Returning: %s", sbool(result)); return result; } // for e.g. card0 bool is_cardN_dir(const char * dirname, const char * simple_fn) { bool result = predicate_cardN(simple_fn); // bool result = str_starts_with(simple_fn, "card"); return result; } bool is_drm_dir(const char * dirname, const char * simple_fn) { bool result = streq(simple_fn, "drm"); return result; } /** Does dirname/simple_fn have attribute class with value * display controller or docking station? * * @param dirname directory name * @param simple_fn sugdirectory * @return true/false */ bool has_class_display_or_docking_station( const char * dirname, const char * simple_fn) { bool debug = false; bool result = false; if (debug) printf("(%s) Starting. dirname=%s, simple_fn=%s\n", __func__, dirname, simple_fn); char * class_val = NULL; int iclass = 0; int top_byte = 0; if ( GET_ATTR_TEXT(&class_val, dirname, simple_fn, "class") ) { if (str_to_int(class_val, &iclass, 16) ) { top_byte = iclass >> 16; if (top_byte == 0x03 || top_byte == 0x0a) // display controller or docking station result = true; } } if (debug) printf("(%s) class_val = %s, top_byte = 0x%02x, result=%s\n", __func__, class_val, top_byte, sbool(result) ); free(class_val); return result; } /** Does dirname/simple_fn have attribute class with value display controller? * i.e. has value x03hh * * @param dirname directory name * @param simple_fn subdirectory * @return true/false */ bool has_class_display( const char * dirname, const char * simple_fn) { bool debug = false; bool result = false; if (debug) printf("(%s) Starting. dirname=%s, simple_fn=%s\n", __func__, dirname, simple_fn); char * class_val = NULL; int iclass = 0; int top_byte = 0; if ( GET_ATTR_TEXT(&class_val, dirname, simple_fn, "class") ) { if (str_to_int(class_val, &iclass, 16) ) { top_byte = iclass >> 16; if (top_byte == 0x03 ) // display controller result = true; } } if (debug) printf("(%s) class_val = %s, top_byte = 0x%02x, result=%s\n", __func__, class_val, top_byte, sbool(result) ); free(class_val); return result; } /** Tests whether the filename of a dirname/filename pair * has the form card-.... * * @param dirname directory name (ignored) * @param simple_fn value to test * @return true/false */ bool is_drm_connector(const char * dirname, const char * simple_fn) { bool debug = false; DBGF(debug, "Starting. dirname=%s, simple_fn=%s", dirname, simple_fn); bool result = false; if (str_starts_with(simple_fn, "card")) { char * s0 = g_strdup( simple_fn + 4); // work around const char * char * s = s0; while (isdigit(*s)) s++; if (*s == '-') result = true; free(s0); } DBGF(debug, "Done. Returning %s", SBOOL(result)); return result; } ddcutil-2.2.0/src/util/sysfs_i2c_util.c0000644000175000001440000001513614754153540013507 /** @file sysfs_i2c_util.c * i2c specific /sys functions */ // Copyright (C) 2018-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include #include #include "coredefs_base.h" #include "debug_util.h" #include "file_util.h" #include "i2c_util.h" #include "report_util.h" #include "string_util.h" #include "subprocess_util.h" #include "sysfs_util.h" #include "sysfs_filter_functions.h" #include "timestamp.h" #include "sysfs_i2c_util.h" /** Looks in the /sys file system to check if a module is loaded. * Note that only loadable kernel modules will be found. Those * built into the kernel will not. * * \param module_name module name * \return true if the module is loaded, false if not */ bool is_module_loaded_using_sysfs( const char * module_name) { bool debug = false; struct stat statbuf; char module_fn[100]; bool found = true; snprintf(module_fn, sizeof(module_fn), "/sys/module/%s", module_name); int rc = stat(module_fn, &statbuf); if (rc < 0) { // will be ENOENT (2) if file not found str_replace_char(module_fn, '-', '_'); rc = stat(module_fn, &statbuf); if (rc < 0) found = false; } if (debug) printf("(%s) module_name = %s, returning %s\n", __func__, module_name, SBOOL(found)); return found; } // Beginning of get_video_devices2() segment // Use C code instead of bash command to find all subdirectories // of /sys/devices having class x03 #ifdef UNUSED bool not_ata(const char * simple_fn) { return !str_starts_with(simple_fn, "ata"); } #endif bool is_pci_dir(const char * simple_fn) { bool debug = false; bool result = str_starts_with(simple_fn, "pci0"); DBGF(debug, "simple_fn = %s, returning %s", simple_fn, sbool(result)); return result; } bool predicate_starts_with_0(const char * simple_fn) { bool debug = false; bool result = str_starts_with(simple_fn, "0"); DBGF(debug, "simple_fn = %s, returning %s", simple_fn, sbool(result)); return result; } void find_class_dirs(const char * dirname, const char * simple_fn, void * accumulator, int depth) { bool debug = false; DBGF(debug, "Starting. dirname=%s, simple_fn=%s, accumulator=%p, depth=%d", dirname, simple_fn, accumulator, depth); char * subdir = g_strdup_printf("%s/%s", dirname, simple_fn); GPtrArray* accum = accumulator; char * result = NULL; bool found = RPT_ATTR_TEXT(-1, &result, dirname, simple_fn, "class"); if (found) { DBGF(debug, "subdir=%s has attribute class = %s. Adding.", subdir, result); free(result); g_ptr_array_add(accum, g_strdup(subdir)); } else { DBGF(debug, "subdir=%s does not have attribute class", subdir); DBGF(debug, "Examining subdirs of %s", subdir); dir_foreach(subdir, predicate_starts_with_0, find_class_dirs, accumulator, depth+1); } free(subdir); } void find_class03_dirs(const char * dirname, const char * simple_fn, void * accumulator, int depth) { bool debug = false; DBGF(debug, "Starting. dirname=%s, simple_fn=%s, accumulator=%p, depth=%d", dirname, simple_fn, accumulator, depth); char * subdir = g_strdup_printf("%s/%s", dirname, simple_fn); GPtrArray* accum = accumulator; char * result = NULL; bool found = RPT_ATTR_TEXT(-1, &result, dirname, simple_fn, "class"); if (found) { DBGF(debug, "subdir=%s has attribute class = %s.", subdir, result); if (str_starts_with(result, "0x03")) g_ptr_array_add(accum, g_strdup(subdir)); free(result); } else { DBGF(debug, "subdir=%s does not have attribute class", subdir); } DBGF(debug, "Examining subdirs of %s", subdir); dir_foreach(subdir, predicate_starts_with_0, find_class03_dirs, accumulator, depth+1); free(subdir); } /** Returns the paths to all video devices in /sys/devices, i.e. those * subdirectories (direct or indirect) having class = 0x03 * * @return array of directory names, caller must free */ GPtrArray * get_video_adapter_devices() { bool debug = false; DBGF(debug, "Starting."); GPtrArray * class03_dirs = g_ptr_array_new_with_free_func(g_free); dir_foreach("/sys/devices", is_pci_dir, find_class03_dirs, class03_dirs, 0); if (debug) { DBG("Returning %d directories:", class03_dirs->len); for (int ndx = 0; ndx < class03_dirs->len; ndx++) rpt_vstring(2, "%s", (char*) g_ptr_array_index(class03_dirs, ndx)); } return class03_dirs; } #ifdef OLD /** Returns the paths to all video devices in /sys/devices, i.e. those * subdirectories (direct or indirect) having class = 0x03 * * @return array of directory names, caller must free * * @remark * This function exists as a shell for testing alternative algorithms */ GPtrArray * get_video_adapter_devices() { bool debug = false; // int64_t t0; #ifdef SLOW_DO_NOT_USE t0 = cur_realtime_nanosec(); // 41 millisec char * cmd = "find /sys/devices -name class | xargs grep x03 -l | sed 's|class||'"; GPtrArray * result = execute_shell_cmd_collect(cmd); DBGF(debug, "find command tool %jd microsec", NANOS2MICROS( cur_realtime_nanosec() - t0)); // g_ptr_array_set_free_func(result, g_free); // redundant #endif uint64_t t0 = cur_realtime_nanosec(); GPtrArray* devices = NULL; devices = get_video_adapter_devices3(); if (debug) { DBG("get_video_adapter_devices3() took %jd microsec", NANOS2MICROS( cur_realtime_nanosec() - t0)); DBG("get_video_adapter_devices3() returned %d directories:", devices->len); for (int ndx = 0; ndx < devices->len; ndx++) rpt_vstring(2, "%s", (char*) g_ptr_array_index(devices, ndx)); } g_ptr_array_free(devices, true); // 1 millisec devices = get_video_adapter_devices2(); if (debug) { DBG("get_video_adapter_devices2() took %jd microsec", NANOS2MICROS( cur_realtime_nanosec() - t0)); DBG("get_video_adapter_devices2() returned %d directories:", devices->len); for (int ndx = 0; ndx < devices->len; ndx++) rpt_vstring(2, "%s", (char*) g_ptr_array_index(devices, ndx)); } DBGF(debug, "Returning %d directories:", devices->len); #ifdef TEMP if (debug) { for (int ndx = 0; ndx < devices->len; ndx++) rpt_vstring(2, "%s", (char*) g_ptr_array_index(devices, ndx)); } #endif return devices; } #endif ddcutil-2.2.0/src/util/device_id_util.c0000644000175000001440000010323614754153540013515 /** @file device_id_util.c * Lookup PCI and USB device ids */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include /** \endcond */ #include "file_util.h" #include "multi_level_map.h" #include "report_util.h" #include "string_util.h" #include "device_id_util.h" #ifndef MAX_PATH #define MAX_PATH 256 #endif /** Indicates ID type */ typedef enum { ID_TYPE_PCI, ID_TYPE_USB } Device_Id_Type; // keep in order with enum Device_Id_Type static char * simple_device_fn[] = { "pci.ids", "usb.ids" }; /** Finds the pci.ids or usb.ids file. * * @param id_type ID_TYPE_PCI or ID_TYPE_USB * @return fully qualified file name of device id file, * NULL if not found * * @remark * It is the responsibility of the caller to free the returned value. */ static char * devid_find_file(Device_Id_Type id_type) { bool debug = false; char * known_pci_ids_dirs[] = { "/usr/share", "/usr/share/misc", "/usr/share/hwdata", NULL }; char * id_fn = simple_device_fn[id_type]; if (debug) printf("(%s) id_type=%d, id_fn = |%s|\n", __func__, id_type, id_fn); char * result = NULL; int ndx; for (ndx=0; known_pci_ids_dirs[ndx] != NULL; ndx++) { char fnbuf[MAX_PATH]; snprintf(fnbuf, MAX_PATH, "%s/%s", known_pci_ids_dirs[ndx], id_fn); if (debug) printf("(%s) Looking for |%s|\n", __func__, fnbuf); struct stat stat_buf; int rc = stat(fnbuf, &stat_buf); if (rc == 0) { result = g_strdup(fnbuf); break; } } if (debug) printf("(%s) id_type=%d, Returning: %s\n", __func__, id_type, result); return result; } // // Simple_Id_Table // // A simple data structure for the simple case where there is only a single // level of lookup typedef struct { gushort id; char * name; } Simple_Id_Table_Entry; typedef GPtrArray Simple_Id_Table; // array of Simple_Id_Table_Entry /* Creates a new Simple_Id_Table * * Arguments: * initial_size if > 0, size for initial allocation * * Returns: pointer to newly allocated table */ static Simple_Id_Table * create_simple_id_table(int initial_size) { Simple_Id_Table * new_table = NULL; if (initial_size > 0) new_table = g_ptr_array_sized_new(initial_size); else new_table = g_ptr_array_new(); // printf("(%s) Returning: %p\n", __func__, new_table); return new_table; } /* Adds an entry to a Simple_Id_Table * * Arguments: * simple_table pointer to Simple_Id_Table * id key of entry * name value of entry */ static Simple_Id_Table_Entry * sit_add(Simple_Id_Table * simple_table, gushort id, char * name) { Simple_Id_Table_Entry * new_entry = calloc(1, sizeof(Simple_Id_Table_Entry)); new_entry->id = id; new_entry->name = g_strdup(name); g_ptr_array_add(simple_table, new_entry); return new_entry; } static void report_simple_id_table(Simple_Id_Table * simple_table, int depth) { rpt_structure_loc("Simple_Id_Table", simple_table, depth); for (int ndx = 0; ndx < simple_table->len; ndx++) { Simple_Id_Table_Entry * cur_entry = g_ptr_array_index(simple_table, ndx); rpt_vstring(depth+1, "0x%04x -> |%s|", cur_entry->id, cur_entry->name); } } static char * get_simple_id_name(Simple_Id_Table * simple_table, gushort id) { char * result = NULL; for (int ndx = 0; ndx < simple_table->len; ndx++) { Simple_Id_Table_Entry * cur_entry = g_ptr_array_index(simple_table, ndx); if (cur_entry->id == id) { result = cur_entry->name; break; } } return result; } // // *** Global Variables *** // // stats 12/2015: // lines in pci.ids: 25,339 // vendors: 2,066 // total devices: 11,745 // subsystem: 10,974 static Multi_Level_Map * pci_vendors_mlm = {0}; static Multi_Level_Map * usb_vendors_mlm = {0}; static Simple_Id_Table * hid_descriptor_types; // tag HID static Simple_Id_Table * hid_descriptor_item_types; // tag R static Simple_Id_Table * hid_country_codes; // tag HCC - for keyboards static Multi_Level_Map * hid_usages_table; // tag HUT // // *** Input File Parsing *** // /* Parses a subrange of an array of text lines into an empty Simple_Id_Table * * Arguments: * simple_table * all_lines array of pointer to text lines to parse * segment_tag first token in lines, when this changes it indicates segment exhausted * cur_pos first line of all_lines to parse * end_pos updated with line number after last line of segment */ static void load_simple_id_segment( Simple_Id_Table * simple_table, // empty GPtrArray, will be filled in w Simple_Id_Table_Entry * GPtrArray * all_lines, // array of pointers to lines char * segment_tag, guint cur_pos, guint * end_pos) { bool debug = false; assert(simple_table); if (debug) { printf("(%s) Starting. simple_table=%p, segment_tag=%s, curpos=%d, -> |%s|\n", __func__, (void*)simple_table, segment_tag, cur_pos, (char *) g_ptr_array_index(all_lines,cur_pos)); } bool more = true; int linect = all_lines->len; while (more && cur_pos < linect) { char * a_line = g_ptr_array_index(all_lines, cur_pos++); rtrim_in_place(a_line); // printf("(%s) curpos=%d, a_line=|%s|\n", __func__, cur_pos-1, a_line); if ( strlen(a_line) == 0 || a_line[0] == '#') { // printf("(%s) Comment line\n", __func__); continue; } // split into: tag hexvalue name char atag[40]; gushort acode; char* aname = NULL; #ifndef NDEBUG int ct = #endif sscanf(a_line, "%s %hx %m[^\n]", atag, &acode, &aname); // printf("(%s) ct = %d, atag=|%s|, acode=0x%08x, aname=|%s|\n", // __func__, ct, atag, acode, aname); // do something with return code to avoid coverity warning assert(ct >= 0); if (!streq(atag, segment_tag)) { // printf("(%s) Tag doesn't match\n", __func__); free(aname); break; } sit_add(simple_table, acode, aname); free(aname); } if (cur_pos <= linect) cur_pos--; *end_pos = cur_pos; if (debug) printf("(%s) Set end_pos = %d\n", __func__, cur_pos); } static Multi_Level_Map * load_multi_level_segment( Multi_Level_Map * header, char * segment_tag, GPtrArray * all_lines, guint * curpos) { bool debug = false; guint linendx = *curpos; // guint to avoid warning re implicit conversion on while() test below if (debug) printf("(%s) Starting. linendx=%d, -> |%s|\n", __func__, linendx, (char *) g_ptr_array_index(all_lines,linendx)); MLM_Node * cur_nodes[8] = {NULL}; // todo: deal properly w max levels for (int ndx = 0; ndx < header->levels; ndx++) { header->level_detail[ndx].total_entries = 0; header->level_detail[ndx].cur_entry = NULL; } gushort cur_code; char * cur_name; bool more = true; while (more && linendx < all_lines->len) { char * a_line = g_ptr_array_index(all_lines, linendx++); int tabct = 0; while (a_line[tabct] == '\t') tabct++; if (strlen(rtrim_in_place(a_line+tabct)) == 0 || a_line[tabct] == '#') continue; if (tabct == 0) { char cur_tag[40]; cur_name = NULL; int ct = sscanf(a_line+tabct, "%s %4hx %m[^\n]", cur_tag, &cur_code, // &header->level_detail[tabct].cur_entry->code, &cur_name); // &header->level_detail[tabct].cur_entry->name ); if (!streq(cur_tag, segment_tag)) { if (cur_name) free(cur_name); // more = false; // needed for continue break; // or continue? } if (ct != 3) { printf("(%s) Error processing line %d: \"%s\"\n", __func__, linendx, a_line); printf("(%s) Lines has %d fields, not 3. Ignoring\n", __func__, ct); // hex_dump(a_line+tabct, strlen(a_line+tabct)); } else { header->level_detail[tabct].total_entries++; cur_nodes[tabct] = mlm_add_node(header, NULL, cur_code, cur_name); for (int lvl = tabct+1; lvl < header->levels; lvl++) { header->level_detail[lvl].cur_entry = NULL; cur_nodes[lvl] = NULL; } // printf("Successful level 0 node added. set header->level_detail[%d].cur_entry (addr %p) to %p\n", // tabct, &(header->level_detail[tabct].cur_entry), header->level_detail[tabct].cur_entry ); // mlt_cur_entries(header); } } // tabct == 0 else { // intermediate or leaf node if (!cur_nodes[tabct-1]) { printf("Error processing line %d: \"%s\"\n", linendx-1, a_line); printf("No enclosing level %d node\n", tabct-1); // printf("(A) tabct=%d\n", tabct); // mlt_cur_entries(header); // A free(header->level_detail[tabct].cur_entry); header->level_detail[tabct].cur_entry = NULL; } else { int ct = sscanf(a_line+tabct, "%4hx %m[^\n]", &cur_code, // &header->level_detail[tabct].cur_entry->code, &cur_name); // &header->level_detail[tabct].cur_entry->name); if (ct != 2) { printf("(%s) Error reading line %d: %s\n", __func__, linendx-1, a_line); } else { header->level_detail[tabct].total_entries++; // A if (tabct < header->levels-1) // if not a leaf // A header->level_detail[tabct].cur_entry->children = g_ptr_array_sized_new(20); // A g_ptr_array_add(header->level_detail[tabct-1].cur_entry->children, header->level_detail[tabct].cur_entry); cur_nodes[tabct] = mlm_add_node(header, cur_nodes[tabct-1], cur_code, cur_name); for (int lvl = tabct+1; lvl < header->levels; lvl++) { header->level_detail[lvl].cur_entry = NULL; cur_nodes[lvl] = NULL; } } } } // intermediate or leaf node } // while loop over lines if (debug) { for (int lvlndx=0; lvlndxlevels; lvlndx++) { printf("(%s) Table %s (tag %s): total level %d (%s) nodes: %d\n", __func__, header->table_name, header->segment_tag, lvlndx, header->level_detail[lvlndx].name, header->level_detail[lvlndx].total_entries); } } *curpos = (int) linendx; return header; } /* Find the start of the next segment in a line array, * i.e. a non-comment line that begins with a different tag * * Arguments: * lines array of pointers to lines * cur_ndx current position in line array * segment_tag first token of lines in current segment * * Returns: line number of start of next segment * * The buffer pointed to by segment_tag is updated with the newly * found tag. * * TODO: eliminate this side effect, apparently left over from refactoring (2/2018) */ static int find_next_segment_start(GPtrArray* lines, int cur_ndx, char* segment_tag) { bool debug = false; if (debug) printf("(%s) Starting cur_ndx=%d, segment_tag=|%s|\n", __func__, cur_ndx, segment_tag); int linect = lines->len; for(; cur_ndx < linect; cur_ndx++) { char * a_line = g_ptr_array_index(lines, cur_ndx); int tabct = 0; while (a_line[tabct] == '\t') tabct++; rtrim_in_place(a_line+tabct); if (strlen(a_line+tabct) == 0 || a_line[tabct] == '#') continue; // always skip comment and blank lines if (segment_tag) { // skipping the current segment if (tabct == 0) { char atag[40]; char* rest = NULL; #ifndef NDEBUG int ct = #endif sscanf(a_line, "%s %m[^\n]", atag, &rest); // printf("(%s) ct = %d\n", __func__, ct); // coverity scan gets unhappy if nothing sscanf's return code is not checked. // this does something trivial with it. assert(ct >= 0); if (rest) free(rest); if (!streq(atag,segment_tag)) { strcpy(segment_tag, atag); // free(rest); break; } } } } return cur_ndx; } // returns line number of end of segment static int load_device_ids(Device_Id_Type id_type, GPtrArray * all_lines) { bool debug = false; int total_vendors = 0; int total_devices = 0; int total_subsys = 0; MLM_Level usb_id_levels[] = { {"vendor", 5000, 0}, {"product", 20, 0}, {"interface", 10, 0} }; MLM_Level pci_id_levels[] = { {"vendor", 10000, 0}, {"device", 20, 0}, {"subsystem", 5, 0} }; #define MAX_LEVELS 5 Multi_Level_Map * mlm = NULL; int levelct = 3; if (id_type == ID_TYPE_PCI) { mlm = mlm_create("PCI Devices", 3, pci_id_levels); } else mlm = mlm_create("USB Devices", 3, usb_id_levels); MLM_Node * cur_node[MAX_LEVELS] = {NULL}; int linect = all_lines->len; assert(linect > 0); int linendx; char * a_line; bool device_ids_done = false; // end of PCI id section seen? for (linendx=0; linendxlen > 0); guint linendx; // char * a_line; linendx = load_device_ids(id_type, all_lines); // if usb.ids, look for additional segments if (id_type == ID_TYPE_USB) { // a_line = g_ptr_array_index(all_lines, linendx); // printf("(%s) First line of next segment: |%s|, linendx=%d\n", __func__, a_line, linendx); linendx--; // start looking on comment line before segment // a_line = g_ptr_array_index(all_lines, linendx); // printf("(%s) First line of next segment: |%s|, linendx=%d\n", __func__, a_line, linendx); #define MAX_TAG_SIZE 40 char tagbuf[MAX_TAG_SIZE]; tagbuf[0] = '\0'; // cast to avoid warning re loss of sign in implicit conversion // signed int is more than ample to hold number of lines int linect = all_lines->len; while (linendx < linect) { //printf("(%s) Before find_next_segment_start(), linendx=%d: |%s|\n", // __func__, linendx, (char *) g_ptr_array_index(all_lines, linendx)); linendx = find_next_segment_start(all_lines, linendx, tagbuf); // printf("(%s) Next segment starts at line %d: |%s|\n", // __func__, linendx, (char *) g_ptr_array_index(all_lines, linendx)); if (linendx >= linect) break; if ( streq(tagbuf,"HID") ) { hid_descriptor_types = create_simple_id_table(0); load_simple_id_segment(hid_descriptor_types, all_lines, tagbuf, linendx, &linendx); if (debug) { printf("(%s) After processing tag HID, linendx=%d\n", __func__, linendx); rpt_title("hid_descriptor_types: ", 0); report_simple_id_table(hid_descriptor_types, 1); } } else if ( streq(tagbuf,"R") ) { hid_descriptor_item_types = create_simple_id_table(0); load_simple_id_segment(hid_descriptor_item_types, all_lines, tagbuf, linendx, &linendx); if (debug) { printf("(%s) After processing tag R, linendx=%d\n", __func__, linendx); rpt_title("hid_descriptor_item_types: ", 0); report_simple_id_table(hid_descriptor_item_types, 1); } } else if ( streq(tagbuf,"HCC") ) { hid_country_codes = create_simple_id_table(0); load_simple_id_segment(hid_country_codes, all_lines, tagbuf, linendx, &linendx); if (debug) { printf("(%s) After HCC, linendx=%d\n", __func__, linendx); rpt_title("hid_country_codes: ", 0); report_simple_id_table(hid_country_codes, 1); } } else if ( streq(tagbuf,"HUT") ) { #ifdef OLD hid_usages_table = mlm_create( hid_usages_table0.table_name, hid_usages_table0.levels, hid_usages_table0.level_detail); #endif MLM_Level hut_level_desc[] = { {"usage page", 20, 0}, {"usage_id", 20, 0} }; hid_usages_table = mlm_create( "HUT", 2, hut_level_desc); load_multi_level_segment(hid_usages_table, tagbuf, all_lines, &linendx); // printf("(%s) After HUT, linendx=%d\n", __func__, linendx); // rpt_title("usages table: ", 0); // report_multi_level_table(hid_usages_table, 1); } } } if (debug) printf("(%s) Done. id_type=%d\n", __func__, id_type); } /* Locates a pci.ids or usb.ids file and loads its contents into internal tables. * * Arguments: * id_type * * Returns: nothing */ static void load_id_file(Device_Id_Type id_type){ bool debug = false; if (debug) printf("(%s) id_type=%d\n", __func__, id_type); char * device_id_fqfn = devid_find_file(id_type); int linect = 0; if (device_id_fqfn) { // char device_id_fqfn[MAX_PATH]; // snprintf(device_id_fqfn, MAX_PATH, id_fqfn, id_fn); // ??? if (debug) printf("(%s) device_id_fqfn = %s\n", __func__, device_id_fqfn); GPtrArray * all_lines = g_ptr_array_sized_new(30000); linect = file_getlines(device_id_fqfn, all_lines, true); if (linect > 0) { load_file_lines(id_type, all_lines); } g_ptr_array_set_free_func(all_lines, g_free); g_ptr_array_free(all_lines, true); free(device_id_fqfn); } // if pci.ids or usb.ids was found if (linect == 0) { // pci.ids/usb.ids not found or empty if (debug) printf("(%s) File not found or empty, creating dummy mlm", __func__); if (id_type == ID_TYPE_PCI) { MLM_Level pci_id_levels[] = { {"vendor", 10000, 0}, {"device", 20, 0}, {"subsystem", 5, 0} }; pci_vendors_mlm = mlm_create("PCI Devices", 3, pci_id_levels); } else { MLM_Level usb_id_levels[] = { {"vendor", 5000, 0}, {"product", 20, 0}, {"interface", 10, 0} }; usb_vendors_mlm = mlm_create("USB Devices", 3, usb_id_levels); } } if (debug) printf("(%s) Done. pci_vendors_mlm=%p, usb_vendors_mlm=%p\n", __func__, (void*)pci_vendors_mlm, (void*)usb_vendors_mlm); return; } // // Internal Report Functions // /* Reports a device id table. * * Arguments: * id_type * * Returns: nothing */ void report_device_ids_mlm(Device_Id_Type id_type) { Multi_Level_Map * all_devices = (id_type == ID_TYPE_PCI) ? pci_vendors_mlm : usb_vendors_mlm; GPtrArray * top_level_nodes = all_devices->root; int total_vendors = 0; int total_devices = 0; int total_subsys = 0; int vctr, dctr, sctr; MLM_Node * cur_vendor; MLM_Node * cur_device; MLM_Node * cur_subsys; for (vctr=0; vctr < top_level_nodes->len; vctr++) { total_vendors++; cur_vendor = g_ptr_array_index(top_level_nodes, vctr); printf("%04x %s\n", cur_vendor->code, cur_vendor->name); if (cur_vendor->children) { for (dctr=0; dctrchildren->len; dctr++) { total_devices++; cur_device = g_ptr_array_index(cur_vendor->children, dctr); printf("\t%04x %s\n", cur_device->code, cur_device->name); if (cur_device->children) { for (sctr=0; sctrchildren->len; sctr++) { total_subsys++; cur_subsys = g_ptr_array_index(cur_device->children, sctr); if (id_type == ID_TYPE_PCI) printf("\t\t%04x %04x %s\n", cur_subsys->code>>16, cur_subsys->code&0xffff, cur_subsys->name); else printf("\t\t%04x %s\n", cur_subsys->code, cur_subsys->name); } } } } } char * level3_name = (id_type == ID_TYPE_PCI) ? "subsystems" : "interfaces"; printf("(%s) Total vendors: %d, total devices: %d, total %s: %d\n", __func__, total_vendors, total_devices, level3_name, total_subsys); } // // *** Name Lookup *** // /** Gets the names associated with a PCI device. * * @param vendor_id * @param device_id * @param subvendor_id * @param subdevice_id * @param argct if 1, vendor_id is set * if 2, vendor_id and device_id are set * if 4, vendor_id, device_id, subvendor_id, and subdevice_id are set * * @return names for the ids * * @remark * Unfortunately, both 0000 and ffff are used as ids, so these can't use them as special * arguments to indicate "not set". Hence the argct parm. */ Pci_Usb_Id_Names devid_get_pci_names( gushort vendor_id, gushort device_id, gushort subvendor_id, gushort subdevice_id, int argct) { bool debug = false; if (debug) { printf("(%s) vendor_id = %02x, device_id=%02x, subvendor_id=%02x, subdevice_id=%02x\n", __func__, vendor_id, device_id, subvendor_id, subdevice_id); } assert( argct==1 || argct==2 || argct==4); devid_ensure_initialized(); guint ids[3] = {vendor_id, device_id, subvendor_id << 16 | subdevice_id}; // only diff from usb_id_get_names int levelct = (argct == 4) ? 3 : argct; // also this Multi_Level_Names mlm_names = mlm_get_names2(pci_vendors_mlm, levelct, ids); // and this Pci_Usb_Id_Names names2; names2.vendor_name = mlm_names.names[0]; names2.device_name = mlm_names.names[1]; names2.subsys_or_interface_name = mlm_names.names[2]; if (levelct == 3 && mlm_names.levels == 2) { // couldn't find the subsystem, see if at least we can look up the subsystem vendor guint ids[1] = {subvendor_id}; Multi_Level_Names mlm_names3 = mlm_get_names2(pci_vendors_mlm, 1, ids); if (mlm_names3.levels == 1) { names2.subsys_or_interface_name = mlm_names3.names[0]; } } if (debug) { printf("(%s) names2: vendor_name=%s, device_name=%s, subsys_or_interface_name=%s\n", __func__, names2.vendor_name, names2.device_name, names2.subsys_or_interface_name); } return names2; } /** Gets the names associated with a USB device. * * @param vendor_id * @param device_id * @param interface_id * @param argct if 1, vendor_id is set * if 2, vendor_id and device_id are set * if 4, vendor_id, device_id, and interface_id are set * * @return names for the ids */ Pci_Usb_Id_Names devid_get_usb_names( gushort vendor_id, gushort device_id, gushort interface_id, int argct) { bool debug = false; if (debug) { printf("(%s) vendor_id = %02x, device_id=%02x, interface_id=%02x\n", __func__, vendor_id, device_id, interface_id); } assert( argct==1 || argct==2 || argct==3); devid_ensure_initialized(); guint ids[3] = {vendor_id, device_id, interface_id}; Multi_Level_Names mlm_names = mlm_get_names2(usb_vendors_mlm, argct, ids); Pci_Usb_Id_Names names2; names2.vendor_name = mlm_names.names[0]; names2.device_name = mlm_names.names[1]; names2.subsys_or_interface_name = mlm_names.names[2]; if (debug) { printf("(%s) names2: vendor_name=%s, device_name=%s, subsys_or_interface_name=%s\n", __func__, names2.vendor_name, names2.device_name, names2.subsys_or_interface_name); } return names2; } /** Gets the page name for a USB usage page code * * @param usage_page_code * * @return page name, NULL if invalid code * * @remark * - Is top level field in HUT entry of usb.ids * - Corresponds to names_huts() in names.c */ char * devid_usage_code_page_name(gushort usage_page_code) { devid_ensure_initialized(); // Per USB HID Usage Tables spec v1.12, section 3.0, // Usage page ID xff00..xffff are vendor defined // x0092..xfeff are reserved // We regard any value < xff00 for which lookup fails as reserved. // This allows for additional usage pages beyond x0092 to be specified // in the usb.ids file. However, usb.ids includes the line: // HUT ff Vendor specific // This is incorrect. It is treating use page code as 1 byte instead of 2. // xff is in the reserved range. It is not a vendor defined page. char * result = "Reserved"; if (usage_page_code > 0xff00) result = "Vendor-defined"; else { // gushort * args = {usage_page_code}; Multi_Level_Names names_found = mlm_get_names(hid_usages_table, /*argct=*/ 1, usage_page_code); if (names_found.levels == 1) result = names_found.names[0]; } return result; } /** Gets the name of a HID usage code * * @param usage_page_code usage page * @param usage_simple_id id within page * * @return usage id name, NULL if not found * * @remark * - First and second fields of HUT entry in usb.ids * - Corresponds to names_hutus() in names.c */ char * devid_usage_code_id_name(gushort usage_page_code, gushort usage_simple_id) { static char resultbuf[12] = {0}; bool debug = false; if (debug) { printf("(%s) usage_page_code=0x%04x, usage_simple_id=0x%04x\n", __func__, usage_page_code, usage_simple_id); } devid_ensure_initialized(); char * result = NULL; if (usage_page_code == 0x81) { snprintf(resultbuf, 11, "ENUM_%d", usage_simple_id); result = resultbuf; } else { // gushort * args = {usage_page_code, usage_simple_id}; Multi_Level_Names names_found = mlm_get_names(hid_usages_table, 2, usage_page_code, usage_simple_id); if (names_found.levels == 2) result = names_found.names[1]; } return result; } /** Gets the name of a HID usage code, specified as a single value containing * the page id in the upper 16 bits and the simple id it in the lower 16 bits. * * @param extended_usage usage value * * @return usage id name, NULL if not found */ char * devid_usage_code_name_by_extended_id(uint32_t extended_usage) { return devid_usage_code_id_name( extended_usage >> 16, extended_usage & 0xffff ); } /** Returns the name of USB HID descriptor item tag. * * @param id item tag id * * @return name of item tag, NULL if not found * * @remark * - HID documentation refers to this as item tag. * usb.ids file refers to this as item type * - The value is actually 1 byte. * - This function corresponds to names.c function names_reporttag() */ char * devid_hid_descriptor_item_type(gushort id) { devid_ensure_initialized(); char * result = NULL; result = get_simple_id_name(hid_descriptor_item_types, id); return result; } // not used, but without this valgrind complains of memory leak char * devid_hid_descriptor_type(gushort id) { devid_ensure_initialized(); char * result = NULL; result = get_simple_id_name(hid_descriptor_types, id); return result; } // not used, but without this valgrind complains of memory leak char * devid_hid_descriptor_country_code(gushort id) { devid_ensure_initialized(); char * result = NULL; result = get_simple_id_name(hid_country_codes, id); return result; } // // *** Initialization *** // /** Initializes the PCI and USB id tables. * If the tables are already initialized, does nothing. */ bool devid_ensure_initialized() { bool debug = false; if (debug) printf("(%s) Starting. pci_vendors_mlm=%p, usb_vendors_mlm=%p\n", __func__, (void*)pci_vendors_mlm, (void*)usb_vendors_mlm); bool ok = (pci_vendors_mlm && usb_vendors_mlm); if (!ok) { if (debug) printf("(%s) Loading.\n", __func__); load_id_file(ID_TYPE_PCI); load_id_file(ID_TYPE_USB); ok = true; if (ok && debug) { // report_device_ids(ID_TYPE_PCI); // report_device_ids_mlm(ID_TYPE_PCI); // report_device_ids(ID_TYPE_USB); // report_device_ids_mlm(ID_TYPE_USB); } } if (debug) printf("(%s) Returning: %s\n", __func__, sbool(ok)); return ok; } ddcutil-2.2.0/src/util/udev_i2c_util.c0000644000175000001440000001540214754153540013277 /** @file udev_i2c_util.c * I2C specific udev utilities */ // Copyright (C) 2016-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include /** \endcond */ #include "debug_util.h" #include "report_util.h" #include "string_util.h" #include "sysfs_i2c_util.h" #include "sysfs_util.h" #include "udev_util.h" #include "udev_i2c_util.h" // // UDEV Inquiry // // Create, report, query, and destroy a list of summaries of UDEV I2C devices // /* Extract the i2c bus number from a device summary. * * Helper function for get_i2c_devices_using_udev() * * \param pointer to Udev_Device_Summary * \return I2C bus number from sysname attribute, -1 if unable to parse */ int udev_i2c_device_summary_busno(Udev_Device_Summary * summary) { int result = -1; // On Raspbian, not all sysattr names have the form i2c-n. if (str_starts_with(summary->sysname, "i2c-")) { const char * sbusno = summary->sysname+4; // DBGMSG("sbusno = |%s|", sbusno); int ibusno; bool ok = str_to_int(sbusno, &ibusno, 10); if (ok) result = ibusno; } // DBGMSG("sysname=|%s|. Returning: %d", summary->sysname, result); return result; } /* Compare 2 udev device summaries of I2C devices by their I2C bus number * * Helper function for get_i2c_devices_using_udev() */ static int compare_udev_i2c_device_summary(const void * a, const void * b) { Udev_Device_Summary * p1 = *(Udev_Device_Summary**) a; Udev_Device_Summary * p2 = *(Udev_Device_Summary**) b; assert( p1 && (memcmp(p1->marker, UDEV_DEVICE_SUMMARY_MARKER, 4) == 0)); assert( p2 && (memcmp(p2->marker, UDEV_DEVICE_SUMMARY_MARKER, 4) == 0)); int v1 = udev_i2c_device_summary_busno(p1); int v2 = udev_i2c_device_summary_busno(p2); int result = (v1 == v2) ? 0 : (v1 < v2) ? -1 : 1; // DBGMSG("v1=%d, v2=%d, returning: %d", v1, v2, result); return result; } /** Returns array of Udev_Device_Summary for I2C devices found by udev, * sorted by bus number. * * \return array of #Udev_Device_Summary * * @remark * Use #free_udev_device_summaries() to free the returned data structure. */ GPtrArray * get_i2c_devices_using_udev() { GPtrArray * summaries = summarize_udev_subsystem_devices("i2c-dev"); assert(summaries); if (summaries->len > 1) { g_ptr_array_sort(summaries, compare_udev_i2c_device_summary); } return summaries; } /** Reports a collection of #Udev_Device_Summary for I2C devices in table form. * * summaries array of #Udev_Device_Summary * title title line * depth logical indentation depth */ void report_i2c_udev_device_summaries(GPtrArray * summaries, char * title, int depth) { rpt_vstring(0,title); if (!summaries || summaries->len == 0) rpt_vstring(depth,"No devices detected"); else { rpt_vstring(depth,"%-11s %-10s %-35s %s", "Subsystem", "Sysname", "Sysattr Name", "Devpath"); for (int ndx = 0; ndx < summaries->len; ndx++) { Udev_Device_Summary * summary = g_ptr_array_index(summaries, ndx); assert( memcmp(summary->marker, UDEV_DEVICE_SUMMARY_MARKER, 4) == 0); // udev_i2c_device_summary_busno(summary); // ??? rpt_vstring(depth,"%-11s %-10s %-35s %s", summary->subsystem, summary->sysname, summary->sysattr_name, summary->devpath); } } } #ifdef NOT_WORTH_IT GPtrArray * get_i2c_smbus_devices_using_udev() { bool debug = false; GPtrArray * summaries = get_i2c_devices_using_udev(); if (summaries) { for (int ndx = summaries->len-1; ndx >= 0; ndx--) { Udev_Device_Summary * summary = g_ptr_array_index(summaries, ndx); assert(memcmp(summary->marker, UDEV_DEVICE_SUMMARY_MARKER, 4) == 0); if ( !str_starts_with(summary->sysattr_name, "SMBus") ) { // TODO: g_ptr_array_set_free_function() must already have been called g_ptr_array_remove_index(summaries, ndx); } } } if (debug) report_i2c_udev_device_summaries(summaries, "I2C SMBus Devices:", 0); return summaries; } #endif #ifdef UNUSED /** Given a specified I2C bus number, checks a list of I2C device * summaries to see if it is the bus number of a SMBUS device. * * \param summaries array of Udev_Device_Summary * \param sbusno I2C bus number, as string * * \return **true** if the number is that of an SMBUS device, **false* if not */ bool is_smbus_device_summary(GPtrArray * summaries, char * sbusno) { bool debug = false; char devname [10]; snprintf(devname, sizeof(devname), "i2c-%s", sbusno); // DBGMSF(debug, "sbusno=|%s|, devname=|%s|", sbusno, devname); if (debug) printf("(%s) sbusno=|%s|, devname=|%s|\n", __func__, sbusno, devname); bool result = false; for (int ndx = 0; ndx < summaries->len; ndx++) { Udev_Device_Summary * summary = g_ptr_array_index(summaries, ndx); if ( streq(summary->sysname, devname) && str_starts_with(summary->sysattr_name, "SMBus") ) { result = true; break; } } // DBGMSF(debug, "Returning: %s", bool_repr(result), result); if (debug) printf("(%s) Returning: %s", __func__, bool_repr(result)); return result; } #endif /** Gets the bus numbers of I2C devices reported by UDEV, * optionally filtered by the sys attribute name (e.g. to eliminate SMBus devices). * * \param keep_func predicate function * \return sorted #Byte_Value_Array of I2C device numbers * * \remark * ***keep_func*** takes a bus number as its sole argument, * returning true iff the number should be included * \remark * if the udev sysname value does not have the form i2c-n, * the udev node is ignored * \remark * if ***keep_func*** is NULL, all device numbers * are included, i.e. there is no filtering */ Byte_Value_Array get_i2c_device_numbers_using_udev_w_sysattr_name_filter(Sysattr_Name_Filter keep_func) { bool debug = false; if (debug) printf("(%s) Starting.\n", __func__); Byte_Value_Array bva = bva_create(); GPtrArray * summaries = get_i2c_devices_using_udev(); if (summaries) { for (int ndx = 0; ndx < summaries->len; ndx++) { Udev_Device_Summary * summary = g_ptr_array_index(summaries, ndx); bool keep = true; if (keep_func) keep = keep_func(summary->sysattr_name); if (keep) { int busno = udev_i2c_device_summary_busno(summary); if (busno >= 0) { // -1 if parse error assert(busno <= 127); bva_append(bva, busno); } } } g_ptr_array_free(summaries, true); } if (debug) bva_report(bva, "Returning I2c bus numbers:"); return bva; } ddcutil-2.2.0/src/util/udev_usb_util.c0000644000175000001440000004555514754153540013427 /** @file udev_usb_util.c * * USB specific udev utility functions */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include /** \endcond */ #include "report_util.h" #include "string_util.h" #include "udev_util.h" #include "udev_usb_util.h" Usb_Detailed_Device_Summary * new_usb_detailed_device_summary() { Usb_Detailed_Device_Summary * devsum = calloc(1, sizeof(Usb_Detailed_Device_Summary)); memcpy(devsum->marker, UDEV_DETAILED_DEVICE_SUMMARY_MARKER, 4); return devsum; } #ifdef REF char * vendor_id; ///< vendor id, as 4 hex characters char * product_id; ///< product id, as 4 hex characters char * vendor_name; ///< vendor name char * product_name; ///< product name char * busnum_s; ///< bus number, as a string char * devnum_s; ///< device number, as a string // to collect, then reduce to what's needed: char * prop_busnum ; char * prop_devnum ; char * prop_model ; char * prop_model_id ; char * prop_usb_interfaces ; char * prop_vendor ; char * prop_vendor_from_database ; char * prop_vendor_id ; char * prop_major ; char * prop_minor ; } Usb_Detailed_Device_Summary; #endif /** Frees a Usb_Detailed_Device_Summary. * All underlying memory is released. * * @param devsum pointer to **Usb_Detailed_Device_Summary** */ void free_usb_detailed_device_summary(Usb_Detailed_Device_Summary * devsum) { if (devsum) { assert( memcmp(devsum->marker, UDEV_DETAILED_DEVICE_SUMMARY_MARKER, 4) == 0); free(devsum->devname); free(devsum->vendor_id); free(devsum->product_id); free(devsum->vendor_name); free(devsum->product_name); free(devsum->busnum_s); free(devsum->devnum_s); free(devsum->prop_busnum); free(devsum->prop_devnum); free(devsum->prop_model); free(devsum->prop_model_id); free(devsum->prop_usb_interfaces); free(devsum->prop_vendor); free(devsum->prop_vendor_from_database); free(devsum->prop_vendor_id); free(devsum->prop_major); free(devsum->prop_minor); free(devsum); } } /** Reports a Usb_Detailed_Device_Summary instance. * * @param devsum pointer to **Usb_Detailed_Device_Summary** * @param depth logical indentation depth */ void report_usb_detailed_device_summary(Usb_Detailed_Device_Summary * devsum, int depth) { assert( devsum && (memcmp(devsum->marker, UDEV_DETAILED_DEVICE_SUMMARY_MARKER, 4) == 0)); rpt_structure_loc("Usb_Detailed_Device_Summary", devsum, depth); int d1 = depth+1; rpt_str("devname", NULL, devsum->devname, d1); // rpt_int("usb_busnum", NULL, devsum->usb_busnum, d1); // rpt_int("usb_devnum", NULL, devsum->usb_devnum, d1); // rpt_int("vid", NULL, devsum->vid, d1); // rpt_int("pid", NULL, devsum->pid, d1); rpt_str("vendor_id", NULL, devsum->vendor_id, d1); rpt_str("product_id", NULL, devsum->product_id, d1); rpt_str("vendor_name", NULL, devsum->vendor_name, d1); rpt_str("product_name", NULL, devsum->product_name, d1); rpt_str("busnum_s", NULL, devsum->busnum_s, d1); rpt_str("devnum_s", NULL, devsum->devnum_s, d1); rpt_str("prop_busnum ", NULL, devsum->prop_busnum, d1); rpt_str("prop_devnum ", NULL, devsum->prop_devnum, d1); rpt_str("prop_model ", NULL, devsum->prop_model, d1); rpt_str("prop_model_id", NULL, devsum->prop_model_id, d1); rpt_str("prop_usb_interfaces", NULL, devsum->prop_usb_interfaces, d1); rpt_str("prop_vendor", NULL, devsum->prop_vendor, d1); rpt_str("prop_vendor_from_database", NULL, devsum->prop_vendor_from_database, d1); rpt_str("prop_vendor_id", NULL, devsum->prop_vendor_id, d1); rpt_str("prop_major", NULL, devsum->prop_major, d1); rpt_str("prop_minor", NULL, devsum->prop_minor, d1); } // made unnecessary by g_strdup() // static __inline__ // char * safe_strdup(const char * s) { // return (s) ? strdup(s) : NULL; // } /** Look up information for a device name. * The expected use in in error messages. * * @param devname device name, e.g. /dev/usb/hiddev3 * @return pointer to newly allocated **Usb_Detailed_Device_Summary** struct, * NULL if not found */ Usb_Detailed_Device_Summary * lookup_udev_usb_device_by_devname(const char * devname, bool verbose) { assert(devname); // printf("(%s) Starting. devname=%s\n", __func__, devname); int depth = 0; int d1 = depth+1; struct udev * udev; struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct udev_device * dev = NULL; struct udev_device * dev0 = NULL; /* Create the udev object */ udev = udev_new(); if (!udev) { if (verbose) printf("(%s) Can't create udev\n", __func__); return NULL; // exit(1); } Usb_Detailed_Device_Summary * devsum = new_usb_detailed_device_summary(); devsum->devname = g_strdup(devname); /* Create a list of matching devices. */ enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_property(enumerate, "DEVNAME", devname); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); int devct = 0; /* udev_list_entry_foreach is a macro which expands to a loop. The loop will be executed for each member in devices, setting dev_list_entry to a list entry which contains the device's path in /sys. */ udev_list_entry_foreach(dev_list_entry, devices) { const char *path; /* Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it */ path = udev_list_entry_get_name(dev_list_entry); // rpt_vstring(depth, "path: %s", path); dev0 = udev_device_new_from_syspath(udev, path); /* udev_device_get_devnode() returns the path to the device node itself in /dev. */ // rpt_vstring(depth, "Device Node Path: %s", udev_device_get_devnode(dev)); // report_udev_device(dev, d1); /* The device pointed to by dev contains information about the named device. In order to get information about the USB device, get the parent device with the subsystem/devtype pair of "usb"/"usb_device". This will be several levels up the tree, but the function will find it.*/ dev = udev_device_get_parent_with_subsystem_devtype( dev0, "usb", "usb_device"); if (!dev) { if (verbose) rpt_vstring(depth, "Unable to find parent USB device."); udev_device_unref(dev0); continue; // exit(1); // TODO: fix } if (verbose) { puts(""); rpt_vstring(depth, "Parent device:"); } /* From here, we can call get_sysattr_value() for each file in the device's /sys entry. The strings passed into these functions (idProduct, idVendor, serial, etc.) correspond directly to the files in the directory which represents the USB device. Note that USB strings are Unicode, UCS2 encoded, but the strings returned from udev_device_get_sysattr_value() are UTF-8 encoded. */ if (verbose) report_udev_device(dev, d1); devsum->vendor_id = g_strdup( udev_device_get_sysattr_value(dev,"idVendor") ); devsum->product_id = g_strdup( udev_device_get_sysattr_value(dev,"idProduct") ); devsum->vendor_name = g_strdup( udev_device_get_sysattr_value(dev,"manufacturer") ); // have seen null devsum->product_name = g_strdup( udev_device_get_sysattr_value(dev,"product") ); devsum->busnum_s = g_strdup( udev_device_get_sysattr_value(dev,"busnum") ); devsum->devnum_s = g_strdup( udev_device_get_sysattr_value(dev,"devnum") ); devsum->prop_busnum = g_strdup(udev_device_get_property_value(dev, "BUSNUM") ); devsum->prop_devnum = g_strdup(udev_device_get_property_value(dev, "DEVNUM") ); devsum->prop_model = g_strdup(udev_device_get_property_value(dev, "ID_MODEL") ); devsum->prop_model_id = g_strdup(udev_device_get_property_value(dev, "ID_MODEL_ID") ); devsum->prop_usb_interfaces = g_strdup(udev_device_get_property_value(dev, "ID_USB_INTERFACES") ); devsum->prop_vendor = g_strdup(udev_device_get_property_value(dev, "ID_VENDOR") ); devsum->prop_vendor_from_database = g_strdup(udev_device_get_property_value(dev, "ID_VENDOR_FROM_DATABASE") ); devsum->prop_vendor_id = g_strdup(udev_device_get_property_value(dev, "ID_VENDOR_ID") ); devsum->prop_major = g_strdup(udev_device_get_property_value(dev, "MAJOR") ); devsum->prop_minor = g_strdup(udev_device_get_property_value(dev, "MINOR") ); hhs4_to_uint16(devsum->vendor_id, &devsum->vid); hhs4_to_uint16(devsum->product_id, &devsum->pid); // udev_device_unref(dev); udev_device_unref(dev0); // freeing dev0 also frees dev devct++; } /* Free the enumerator object */ udev_enumerate_unref(enumerate); udev_unref(udev); if (devct != 1) printf("(%s) Unexpectedly found %d matching devices for %s\n", __func__, devct, devname); if (devct == 0) { free_usb_detailed_device_summary(devsum); devsum = NULL; } // if (devsum) // report_usb_device_summary(devsum, 0); return devsum; } /** Reports on all devices in a UDEV subsystem * * @param subsystem subsystem name, e.g. "usbmisc" * @param show_usb_parent include reports on parent devices * @param depth logical indentation depth * * @remark * Adapted from USB sample code */ void probe_udev_subsystem(char * subsystem, bool show_usb_parent, int depth) { int d1 = depth+1; struct udev *udev; struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct udev_device* dev = NULL; struct udev_device* dev0 = NULL; /* Create the udev object */ udev = udev_new(); if (!udev) { printf("(%s) Can't create udev\n", __func__); goto bye; } /* Create a list of the devices in the specified subsystem. */ enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, subsystem); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); /* For each item enumerated, print out its information. udev_list_entry_foreach is a macro which expands to a loop. The loop will be executed for each member in devices, setting dev_list_entry to a list entry which contains the device's path in /sys. */ udev_list_entry_foreach(dev_list_entry, devices) { puts(""); rpt_vstring(depth, "***One Device ***"); const char *path; /* Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it */ path = udev_list_entry_get_name(dev_list_entry); rpt_vstring(depth, "path: %s", path); dev0 = udev_device_new_from_syspath(udev, path); /* udev_device_get_devnode() returns the path to the device node itself in /dev. */ rpt_vstring(depth, "Device Node Path: %s", udev_device_get_devnode(dev0)); report_udev_device(dev0, d1); if (show_usb_parent) { /* The device pointed to by dev contains information about the hidraw device. In order to get information about the USB device, get the parent device with the subsystem/devtype pair of "usb"/"usb_device". This will be several levels up the tree, but the function will find it.*/ dev = udev_device_get_parent_with_subsystem_devtype( dev, "usb", "usb_device"); if (!dev) { rpt_vstring(depth, "Unable to find parent USB device."); } else { puts(""); rpt_vstring(depth, "Parent device:"); /* From here, we can call get_sysattr_value() for each file in the device's /sys entry. The strings passed into these functions (idProduct, idVendor, serial, etc.) correspond directly to the files in the directory which represents the USB device. Note that USB strings are Unicode, UCS2 encoded, but the strings returned from udev_device_get_sysattr_value() are UTF-8 encoded. */ rpt_vstring(d1, "VID/PID: %s %s", udev_device_get_sysattr_value(dev,"idVendor"), udev_device_get_sysattr_value(dev, "idProduct")); rpt_vstring(d1, "%s", udev_device_get_sysattr_value(dev,"manufacturer") ); rpt_vstring(d1, "%s", udev_device_get_sysattr_value(dev,"product")); rpt_vstring(d1, "serial: %s", udev_device_get_sysattr_value(dev, "serial")); report_udev_device(dev, d1); } } udev_device_unref(dev0); } /* Free the enumerator object */ udev_enumerate_unref(enumerate); udev_unref(udev); bye: return; } /** Reports on a struct **udev_usb_devinfo**. * * @param dinfo pointer to struct * @param depth logical indentation depth */ void report_udev_usb_devinfo(struct udev_usb_devinfo * dinfo, int depth) { rpt_structure_loc("udev_usb_devinfo", dinfo, depth); int d1 = depth+1; rpt_vstring(d1, "%-20s %d 0x%04x", "busno", dinfo->busno, dinfo->busno); rpt_vstring(d1, "%-20s %d 0x%04x", "devno", dinfo->devno, dinfo->devno); } /** Use UDEV to get the bus and device numbers for a USB device * * @param subsystem device subsystem, e.g. "usbmisc" * @param simple_devname simple device name, e.g. "hiddev" * * @return pointer to Udev_Usb_Devinfo containing result\n * NULL if not found * * Adapted from UDEV sample code. */ Udev_Usb_Devinfo * get_udev_usb_devinfo(char * subsystem, char * simple_devname) { assert(subsystem); assert(simple_devname); bool debug = false; if (debug) printf("(%s) Starting. subsystem=|%s|, simple_devname=|%s|\n", __func__, subsystem, simple_devname); struct udev *udev; struct udev_enumerate *enumerate; struct udev_list_entry *dev_list_entry; struct udev_device *dev; Udev_Usb_Devinfo * result = NULL; udev = udev_new(); // create udev context object if (!udev) { // should never happen printf("(%s) Can't create udev\n", __func__); goto bye; } /* Create a list of the devices in the specified subsystem. */ enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, subsystem); udev_enumerate_add_match_sysname(enumerate, simple_devname); udev_enumerate_scan_devices(enumerate); // Given the specificity of our search, list should contain exactly 0 or 1 entries dev_list_entry = udev_enumerate_get_list_entry(enumerate); // get first entry of list if (dev_list_entry) { assert( udev_list_entry_get_next(dev_list_entry) == NULL); // should be 0 or 1 devices /* Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it */ const char * path = udev_list_entry_get_name(dev_list_entry); // printf("path: %s\n", path); dev = udev_device_new_from_syspath(udev, path); // udev_device_get_devnode() returns the path to the device node // itself in /dev, e.g. /dev/hidraw3, /dev/usb/hiddev2 if (debug) printf("(%s) Device Node Path: %s\n", __func__, udev_device_get_devnode(dev)); // report_udev_device(dev, 1); /* The device pointed to by dev contains information about the hidraw device. In order to get information about the USB device, get the parent device with the subsystem/devtype pair of "usb"/"usb_device". This will be several levels up the tree, but the function will find it.*/ dev = udev_device_get_parent_with_subsystem_devtype( dev, "usb", "usb_device"); if (!dev) { printf("(%s) Unable to find parent USB device for subsystem %s, device %s.", __func__, subsystem, simple_devname); } else { // printf("Parent device: \n"); /* From here, we can call get_sysattr_value() for each file in the device's /sys entry. The strings passed into these functions (idProduct, idVendor, serial, etc.) correspond directly to the files in the directory which represents the USB device. Note that USB strings are Unicode, UCS2 encoded, but the strings returned from udev_device_get_sysattr_value() are UTF-8 encoded. */ if (debug) { printf(" VID/PID: %s %s\n", udev_device_get_sysattr_value(dev,"idVendor"), udev_device_get_sysattr_value(dev, "idProduct")); printf(" %s\n %s\n", udev_device_get_sysattr_value(dev,"manufacturer"), udev_device_get_sysattr_value(dev,"product")); printf(" serial: %s\n", udev_device_get_sysattr_value(dev, "serial")); printf(" busnum: %s\n", udev_device_get_sysattr_value(dev, "busnum")); printf(" devnum: %s\n", udev_device_get_sysattr_value(dev, "devnum")); } const char * sbusnum = udev_device_get_sysattr_value(dev, "busnum"); const char * sdevnum = udev_device_get_sysattr_value(dev, "devnum"); result = calloc(1, sizeof(Udev_Usb_Devinfo)); //are these decimal or hex numbers? result->busno = atoi(sbusnum); result->devno = atoi(sdevnum); // report_udev_device(dev, 1); udev_device_unref(dev); } } /* Free the enumerator object */ udev_enumerate_unref(enumerate); udev_unref(udev); bye: if (debug) { printf("(%s) Returning: %p\n", __func__, (void*)result); if (result) report_udev_usb_devinfo(result, 1); } return result; } /** Encapsulates location of hiddev device files, in case it needs to be generalized \remark According to file https://www.kernel.org/doc/Documentation/hid/hiddev.txt, hiddev devices are always named /dev/usb/hiddevN (where n = 0..15). However, searching the web finds statements that the hiddev device files might be located in any of several distribution dependent directories, and code examples that looks in multiple directories. I suspect that for recent kernels/distributions the device file location is fixed, but that variation existed in the past. For now, assume the location is fixed. If in fact it proves to be variable, this function can be extended to use udev or other some other mechanisms to locate the hiddev directory. */ char * usb_hiddev_directory() { return "/dev/usb"; } ddcutil-2.2.0/src/util/udev_util.c0000644000175000001440000002670014754153540012545 /** @file udev_util.c * * UDEV utility functions */ // Copyright (C) 2016-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later // Adapted from source code at http://www.signal11.us/oss/udev/ /** \cond */ #include #include #include #include /** \endcond */ #include "debug_util.h" #include "report_util.h" #include "string_util.h" #include "udev_util.h" /* GDestroyNotify() function to be called when a data element in a GPtrRrray of * #Udev_Device_Summary is destroyed. * * Arguments: * data pointer to Udev_Device_Summary */ static void free_udev_device_summary(gpointer data) { if (data) { Udev_Device_Summary * summary = (Udev_Device_Summary *) data; assert(memcmp(summary->marker, UDEV_DEVICE_SUMMARY_MARKER, 4) == 0); summary->marker[3] = 'x'; // no need to free strings, they are consts free(summary->devpath); free(summary->sysattr_name); free(summary->sysname); free(summary->subsystem); free(summary); } } /** Destroys a GPtrArray of Udev_Device_Summary * * @param summaries pointer to GPtrArray of #Udev_Device_Summary */ void free_udev_device_summaries(GPtrArray* summaries) { g_ptr_array_free(summaries, true); } /** Returns a struct containing key fields extracted from a **struct udev_device**. * * \param dev pointer to struct udev_device * \return newly allocated #Udev_Device_Summary * * \remark * It is the responsibility of the caller to free the returned struct * using #free_udev_device_summary(). * The strings pointed within #Udev_Device_Summary are consts * within the UDEV data structures and should not be freed. */ static Udev_Device_Summary * get_udev_device_summary(struct udev_device * dev) { Udev_Device_Summary * summary = calloc(1,sizeof(struct udev_device_summary)); memcpy(summary->marker, UDEV_DEVICE_SUMMARY_MARKER, 4); // n. all strings returned are const char * summary->devpath = g_strdup(udev_device_get_devpath(dev)); summary->sysname = g_strdup(udev_device_get_sysname(dev)); summary->sysattr_name = g_strdup(udev_device_get_sysattr_value(dev, "name")); summary->subsystem = g_strdup(udev_device_get_subsystem(dev)); return summary; } /** Queries UDEV to obtain summaries of each device in a subsystem. * * @param subsystem subsystem name, e.g. "i2c-dev" * @return GPtrArray of #Udev_Device_Summary * * @remark * Use #free_udev_device_summaries() to free the returned data structure. */ GPtrArray * summarize_udev_subsystem_devices(char * subsystem) { struct udev *udev; struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct udev_device *dev; GPtrArray * summaries = g_ptr_array_sized_new(10); g_ptr_array_set_free_func(summaries, free_udev_device_summary); /* Create the udev object */ udev = udev_new(); if (!udev) { fprintf(stderr, "(%s) Can't create udev\n", __func__); goto bye; } /* Create a list of the devices in the specified subsystem. */ enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, subsystem); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); /* For each item enumerated, print out its information. udev_list_entry_foreach is a macro which expands to a loop. The loop will be executed for each member in devices, setting dev_list_entry to a list entry which contains the device's path in /sys. */ udev_list_entry_foreach(dev_list_entry, devices) { const char *path; /* Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it */ path = udev_list_entry_get_name(dev_list_entry); dev = udev_device_new_from_syspath(udev, path); g_ptr_array_add(summaries, get_udev_device_summary(dev)); udev_device_unref(dev); } udev_enumerate_unref(enumerate); udev_unref(udev); bye: return summaries; } /** Queries udev to find all devices with a given name attribute * * @param name e.g. DPMST * @return GPtrArray of #Udev_Device_Summary * * @remark * Use #free_udev_device_summaries() to free the returned data structure. */ GPtrArray * find_devices_by_sysattr_name(char * name) { struct udev *udev; struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct udev_device *dev; GPtrArray * result = g_ptr_array_sized_new(10); g_ptr_array_set_free_func(result, free_udev_device_summary); udev = udev_new(); // Create the udev object if (!udev) { printf("(%s) Can't create udev\n", __func__); goto bye; } /* Create a list of the devices in the specified subsystem. */ enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_sysattr(enumerate, "name", name); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); // udev_list_entry_foreach is a macro which expands to a loop. // The loop will be executed for each member in devices, setting dev_list_entry // to a list entry which contains the device's path in /sys. udev_list_entry_foreach(dev_list_entry, devices) { // Get the filename of the /sys entry for the device, // and create a udev_device object (dev) representing it const char * path = udev_list_entry_get_name(dev_list_entry); dev = udev_device_new_from_syspath(udev, path); g_ptr_array_add(result, get_udev_device_summary(dev)); udev_device_unref(dev); } udev_enumerate_unref(enumerate); udev_unref(udev); bye: return result; } /** Filters a **GPtrArray** of #Udev_Device_Summary removing * entries that do not satisfy the predicate function provided. * * summaries **GPtrArray** of #Udev_Device_Summary * func filter function, if returns false then delete the entry * \return NULL or **summaries** * * \remark * - if **summaries** is NULL, returns NULL * - if **summaries** is non_NULL, but keep_func is NULL, returns **summaries** */ GPtrArray * filter_device_summaries( GPtrArray * summaries, Udev_Summary_Filter_Func keep_func) { if (!summaries || !keep_func) goto bye; for (int ndx=0; ndx < summaries->len; ndx++) { Udev_Device_Summary * summary = g_ptr_array_index(summaries, ndx); if (!keep_func(summary)) g_ptr_array_remove_index(summaries, ndx); } bye: return summaries; } /** Report on a single UDEV device * * @param dev pointer to struct **udev_device** to report * @param depth logical indentation depth */ void report_udev_device(struct udev_device * dev, int depth) { bool debug = false; DBGF(debug, "Starting"); int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("struct udev_device", dev, depth); rpt_vstring(d1, "devpath: %s", udev_device_get_devpath(dev)); rpt_vstring(d1, "subsystem: %s", udev_device_get_subsystem(dev)); rpt_vstring(d1, "devtype: %s", udev_device_get_devtype(dev)); rpt_vstring(d1, "syspath: %s", udev_device_get_syspath(dev)); rpt_vstring(d1, "sysname: %s", udev_device_get_sysname(dev)); rpt_vstring(d1, "sysnum: %s", udev_device_get_sysnum(dev)); rpt_vstring(d1, "devnode: %s", udev_device_get_devnode(dev)); struct udev_list_entry * cur_entry; struct udev_list_entry * properties_list_entry; struct udev_list_entry * sysattr_list_entry; properties_list_entry = udev_device_get_properties_list_entry(dev); sysattr_list_entry = udev_device_get_sysattr_list_entry(dev); rpt_vstring(d1, "Properties:"); udev_list_entry_foreach(cur_entry, properties_list_entry) { const char * prop_name = udev_list_entry_get_name(cur_entry); const char * prop_value = udev_list_entry_get_value(cur_entry); #ifndef NDEBUG const char * prop_value2 = udev_device_get_property_value(dev, prop_name); assert(streq(prop_value, prop_value2)); #endif rpt_vstring(d2, "%s -> %s", prop_name, prop_value); } rpt_vstring(d1, "Sysattrs:"); udev_list_entry_foreach(cur_entry, sysattr_list_entry) { const char * attr_name = udev_list_entry_get_name(cur_entry); #ifndef NDEBUG const char * attr_value = udev_list_entry_get_value(cur_entry); assert(attr_value == NULL); #endif const char * attr_value2 = udev_device_get_sysattr_value(dev, attr_name); // hex_dump( (Byte*) attr_value2, strlen(attr_value2)+1); if (attr_value2 && strchr(attr_value2, '\n')) { // if (streq(attr_name, "uevent")) { // output is annoying to visually scan since it contains newlines Null_Terminated_String_Array ntsa = strsplit(attr_value2, "\n"); if (ntsa_length(ntsa) == 0) rpt_vstring(d2, "%s -> %s", attr_name, ""); else { rpt_vstring(d2, "%s -> %s", attr_name, ntsa[0]); int ndx = 1; while (ntsa[ndx]) { rpt_vstring(d2, "%*s %s", (int) strlen(attr_name) + 3, " ", ntsa[ndx]); ndx++; } } ntsa_free(ntsa, /* free_strings */ true); #ifdef ALTERNATIVE // simpler, works char * av = g_strdup(attr_value2); char * p = av; while (*p) { if (*p == 0x0a) *p = ','; p++; } rpt_vstring(d2, "%s -> %s", attr_name, av); free(av); #endif } // n. attr_name "descriptors" returns a hex value, not a null-terminated string // should display as hex, but how to determine length? // for example of reading, see http://fossies.org/linux/systemd/src/udev/udev-builtin-usb_id.c // not worth pursuing else { rpt_vstring(d2, "%s -> %s", attr_name, attr_value2); } } DBGF(debug, "Done"); } void show_udev_list_entries( struct udev_list_entry * entries, char * title) { printf( " %s: \n", title); struct udev_list_entry * cur = NULL; udev_list_entry_foreach(cur, entries) { const char * name = udev_list_entry_get_name(cur); const char * value = udev_list_entry_get_value(cur); printf(" %s -> %s\n", name, value); } } void show_sysattr_list_entries( struct udev_device * dev, struct udev_list_entry * head) { int d1 = 1; int d2 = 2; rpt_vstring(d1, "Sysattrs:"); struct udev_list_entry * cur_entry = NULL; udev_list_entry_foreach(cur_entry, head) { const char * attr_name = udev_list_entry_get_name(cur_entry); #ifndef NDEBUG const char * attr_value = udev_list_entry_get_value(cur_entry); assert(attr_value == NULL); #endif const char * attr_value2 = udev_device_get_sysattr_value(dev, attr_name); // hex_dump( (Byte*) attr_value2, strlen(attr_value2)+1); if (attr_value2 && strchr(attr_value2, '\n')) { // if (streq(attr_name, "uevent")) { // output is annoying to visually scan since it contains newlines char * av = g_strdup(attr_value2); char * p = av; while (*p) { if (*p == 0x0a) *p = ','; p++; } rpt_vstring(d2, "%s -> %s", attr_name, av); free(av); } // n. attr_name "descriptors" returns a hex value, not a null-terminated string // should display as hex, but how to determine length? // for example of reading, see http://fossies.org/linux/systemd/src/udev/udev-builtin-usb_id.c // not worth pursuing else { rpt_vstring(d2, "%s -> %s", attr_name, attr_value2); } } } ddcutil-2.2.0/src/util/failsim.c0000644000175000001440000004335714754153540012200 /** @file failsim.c * Functions that provide a simple failure simulation framework. */ // Copyright (C) 2017-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include /** \endcond */ #include "debug_util.h" #include "error_info.h" #include "file_util.h" #include "report_util.h" #include "string_util.h" #include "failsim.h" static Fsim_Name_To_Number_Func name_to_number_func = NULL; static Fsim_Name_To_Number_Func unmodulated_name_to_number_func = NULL; /** Sets the functions to be used to interpret a symbolic value * in a failure simulation control file. * * @param func normal function to use * @param unmodulated_func function to use when an unmodulated value is looked up */ void fsim_set_name_to_number_funcs( Fsim_Name_To_Number_Func func, Fsim_Name_To_Number_Func unmodulated_func) { name_to_number_func = func; unmodulated_name_to_number_func = unmodulated_func; } bool failsim_enabled = false; // could make this a global to control failure simulation // singleton failure simulation table static GHashTable * fst = NULL; // Describes a call occurrence for which an error is to be simulated typedef struct fsim_call_occ_rec { Fsim_Call_Occ_Type call_occ_type; int occno; int rc; bool modulated; } Fsim_Call_Occ_Rec; // This struct describes the failure simulation state of a function. It // a) contains an array of FsimCall_Occ_Rec defining the simulated errors // b) a counter updated at runtime of the number of times the function has been called. #define FSIM_FUNC_REC_MARKER "FSFR" typedef struct fsim_func_rec { char marker[4]; char * func_name; int callct; GArray * call_occ_recs; // array of Fsim_Call_Occ_Rec } Fsim_Func_Rec; char * fsim_call_occ_type_names[] = {"FSIM_CALL_OCC_RECURRING", "FSIM_CALL_OCC_SINGLE" }; // GHashTable destroy function for hash value (i.e. pointer to Fsim_Func_Rec) static void fsim_destroy_func_rec(gpointer data) { Fsim_Func_Rec * frec = (Fsim_Func_Rec *) data; assert(memcmp(frec->marker, FSIM_FUNC_REC_MARKER, 4) == 0); g_array_unref(frec->call_occ_recs); frec->marker[3] = 'x'; free(data); } // GHashTable destroy function for hash key (i.e. pointer to string) void fsim_destroy_key(gpointer data) { free(data); } /* Reports a single entry in the error simulation table, * i.e. the conditions under which an error will be simulated * for the function and the error value for the function to return. * * Arguments: * key_ptr pointer to function name * value_ptr pointer to GArray of Fsim_Call_Occ_Rec's * user_data_ptr pointer to logical indentation depth */ static void report_error_table_entry( gpointer key_ptr, gpointer value_ptr, gpointer user_data_ptr) { bool debug = false; if (debug) printf("(%s) Starting. value_ptr=%p, user_data_ptr=%p\n", __func__, value_ptr, user_data_ptr); char * key = (char *) key_ptr; Fsim_Func_Rec * frec = (Fsim_Func_Rec *) value_ptr; int * depth_ptr = (int *) user_data_ptr; int depth = *depth_ptr; rpt_vstring(depth, "function: %s", key); for (int ndx = 0; ndx < frec->call_occ_recs->len; ndx++) { Fsim_Call_Occ_Rec occ_rec = g_array_index(frec->call_occ_recs, Fsim_Call_Occ_Rec, ndx); rpt_vstring(depth+1, "rc = %d, occurrences=(%s, %d)", occ_rec.rc, (occ_rec.call_occ_type == FSIM_CALL_OCC_RECURRING) ? "recurring" : "single", occ_rec.occno); } } /* Returns the failure simulation table. * If the table does not already exist it is created. * * Arguments: none * * Returns: pointer to failure simulation table */ static GHashTable * fsim_get_or_create_failsim_table() { if (!fst) { fst = g_hash_table_new_full( g_str_hash, g_str_equal, fsim_destroy_key, fsim_destroy_func_rec); } return fst; } /* Gets the record for a function in the failure simulation table. * If a record does not already exist, a new one is created. * * Arguments: * funcname function mame * * Returns: pointer to Fsim_Func_Rec for the function */ static Fsim_Func_Rec * fsim_get_or_create_func_rec(char * funcname) { GHashTable * fst = fsim_get_or_create_failsim_table(); Fsim_Func_Rec * frec = g_hash_table_lookup(fst, funcname); if (!frec) { frec = calloc(1, sizeof(Fsim_Func_Rec)); memcpy(frec->marker, FSIM_FUNC_REC_MARKER, 4); frec->func_name = g_strdup(funcname); frec->callct = 0; frec->call_occ_recs = g_array_new( false, // zero_terminated true, // clear_ sizeof(Fsim_Call_Occ_Rec) ); g_hash_table_insert(fst, frec->func_name, frec); } return frec; } /** Adds an error description to the failure simulation table entry for a function. * * @param funcname function name * @param call_occ_type recurring or single * @param occno occurrence number * @param rc return code to simulate */ void fsim_add_error( char * funcname, Fsim_Call_Occ_Type call_occ_type, int occno, int rc) { bool debug = false; if (debug) printf("(%s) funcname=|%s|, call_occ_type=%d, occ type: %s, occno=%d, fsim_rc=%d\n", __func__, funcname, call_occ_type, (call_occ_type == FSIM_CALL_OCC_RECURRING) ? "recurring" : "single", occno, rc); Fsim_Call_Occ_Rec callocc_rec; callocc_rec.call_occ_type = call_occ_type; callocc_rec.occno = occno; callocc_rec.rc = rc; Fsim_Func_Rec* frec = fsim_get_or_create_func_rec(funcname); g_array_append_val(frec->call_occ_recs, callocc_rec); } /** Resets the call counter in a failure simulation table entry * * @param funcname function name */ void fsim_reset_callct(char * funcname) { if (fst) { Fsim_Func_Rec * frec = g_hash_table_lookup(fst, funcname); if (frec) frec->callct = 0; } } /** Delete all error descriptors for a function. * * @param funcname function name */ void fsim_clear_errors_for_func(char * funcname) { if (fst) { // not an error if key doesn't exist g_hash_table_remove(fst, funcname); } } /* Clears the entire failure simulation table. */ void fsim_clear_error_table() { if (fst) { g_hash_table_destroy(fst); fst = NULL; } } /** Report the failure simulation table. * * @param depth logical indentation depth */ void fsim_report_failure_simulation_table(int depth) { bool debug = false; int d1 = depth+1; if (debug) printf("(%s) d1=%d, &d1=%p\n", __func__, d1, &d1); if (fst) { if (g_hash_table_size(fst) == 0) { rpt_vstring(depth, "Failure simulation table: EMPTY"); } else { rpt_vstring(depth, "Failure simulation table:"); g_hash_table_foreach(fst, report_error_table_entry, &d1); } } else rpt_vstring(depth, "Failure simulation table not initialized"); } /* Interprets a string status code expression, returning its integer value. * * The string can take the following forms: * integer e.g. "-42" * boolean i.e. "true" or "false" * a symbolic status code name, optionally prefixed by * "modulated:" or "base:". * If neither "modulated" nor "base" is specified, "modulated" is assumed * e.g. "DDC_RC_ALL_ZERO", "base:EBUSY" * * Arguments: * rc_string string to evaluate * evaluated_rc where to return evaluated value * * Returns: true if evaluation successful, false if error */ // Issue: should unmodulated values be negative, or should // an optional minus sign be recognized? // e.g. should we specify -EBUSY for -22? bool eval_fsim_rc(char * rc_string, int * evaluated_rc) { bool debug = false; if (debug) printf("(%s) Starting. rc_string=%s\n", __func__, rc_string); char * end; bool ok = false; *evaluated_rc = 0; long int answer = strtol(rc_string, &end, 10); if (*end == '\0') { *evaluated_rc = (int) answer; ok = true; } else if (streq(rc_string, "true")) { *evaluated_rc = true; ok = true; } else if (streq(rc_string, "false")) { *evaluated_rc = false; ok = true; } else { bool is_modulated = true; if (str_starts_with(rc_string, "modulated:")) { is_modulated = true; rc_string = rc_string + strlen("modulated:"); } else if (str_starts_with(rc_string, "base:")) { is_modulated = false; rc_string = rc_string + strlen("base:"); } if (strlen(rc_string) == 0) ok = false; else if (is_modulated && name_to_number_func) ok = name_to_number_func(rc_string, evaluated_rc); else if (!is_modulated && unmodulated_name_to_number_func) ok = unmodulated_name_to_number_func(rc_string, evaluated_rc); else ok = false; } if (debug) printf("(%s) Done . rc_string=%s. Returning: %s, *evaluated_rc=%d\n", __func__, rc_string, sbool(ok), *evaluated_rc); return ok; } void emit_control_error(GPtrArray* errmsgs, const char * msg, ...) { va_list(args); va_start(args, msg); char * buffer = g_strdup_vprintf(msg, args); va_end(args); if (errmsgs) { g_ptr_array_add(errmsgs, g_strdup(buffer)); } else{ fprintf(stderr, "%s\n", buffer); } free(buffer); } // // Bulk load the failure simulation table // // cf dumpload load variants // /** Load the failure simulation table from an array of strings. * Each string describes one simulated error for a function, and has * the form: * @verbatim function_name status_code occurrence_descriptor @endverbatim * where: * - **status_code** has a form documented for eval_fsim_rc() * - **occurrence_descriptor** has the form "[*]integer"\n * examples: * - *7 every 7th call fails * - 7 the 7th call fails * - *1 every call fails * * Examples: * \verbatim i2c_set_addr base:EBUSY 6 ddc_verify false *1 \endverbatim * * @param lines array of lines */ bool fsim_load_control_from_gptrarray(GPtrArray * lines, GPtrArray * errmsgs) { bool debug = false; DBGF(debug, "Starting. ines.len = %d", lines->len); bool ok = false; bool dummy_data_flag = false; // Dummy data for development if (dummy_data_flag) { printf("(%s) Loading mock data\n", __func__); fsim_add_error("i2c_set_addr", FSIM_CALL_OCC_RECURRING, 2, -EBUSY); ok = true; goto bye; } ok = true; fst = g_hash_table_new(g_str_hash, g_str_equal); for (int ndx = 0; ndx < lines->len; ndx++) { char * aline = g_ptr_array_index(lines, ndx); if (debug) printf("(%s) line: %s\n", __func__, aline); char * trimmed_line = strtrim(aline); if (strlen(trimmed_line) > 0 && trimmed_line[0] != '#' && trimmed_line[0] != '*') { Null_Terminated_String_Array pieces = strsplit(trimmed_line, " "); // if (debug) // ntsa_show(pieces); bool valid_line = true; char * funcname = NULL; int fsim_rc = 0; Fsim_Call_Occ_Type occtype = FSIM_CALL_OCC_SINGLE; int occno = 0; if (ntsa_length(pieces) != 3) valid_line = false; else { funcname = pieces[0]; valid_line = eval_fsim_rc(pieces[1], &fsim_rc); if (valid_line) { char * occdef = pieces[2]; if (*occdef == '*') { occtype = FSIM_CALL_OCC_RECURRING; occdef++; } if (strlen(occdef) == 0) valid_line = false; else { char * end; occno = strtol(occdef, &end, 10); if (*end != '\0') valid_line = false; } } if (valid_line) { fsim_add_error( funcname, occtype, occno, fsim_rc); } } if (!valid_line) { emit_control_error(errmsgs, "Invalid control file line: %s", aline); ok = false; } ntsa_free(pieces, /* free_strings */ true); } free(trimmed_line); } bye: if (ok) { if (debug) fsim_report_failure_simulation_table(0); failsim_enabled = true; } DBGF(debug, "Returning: %s", __func__, sbool(ok)); return ok; } #ifdef FUTURE // TODO: implement bool fsim_load_control_string(char * s) { bool ok = false; return ok; } #endif /** Loads the failure simulation table from a control file. * * @param fn file name * * @return true if success, fails if error */ bool fsim_load_control_file(char * fn) { bool debug = false; DBGF(debug, "Starting. fn=%s", fn); GPtrArray * lines = g_ptr_array_new(); GPtrArray* errmsgs = g_ptr_array_new(); int linect = file_getlines(fn, lines, debug); DBGF(debug, "Read %d lines", linect); bool result = false; if (linect < 0) { fprintf(stderr, "Failed to read %s: %s\n", fn, strerror(-linect)); } else { result = fsim_load_control_from_gptrarray(lines, errmsgs); if (!result) { fprintf(stderr, "Error(s) reading failsim control file %s:\n", fn); for (int ndx = 0; ndx < errmsgs->len; ndx++) { fprintf(stderr, " %s\n", (char *) g_ptr_array_index(errmsgs, ndx)); } } } g_ptr_array_free(errmsgs, true); g_ptr_array_free(lines, true); DBGF(debug, "Done. Returning: %s, loaded:", sbool(result)); if (debug && result) fsim_report_failure_simulation_table(2); return result; } // // Execution time error check // /** This function is called at runtime to check if a failure should be * simulated. * * @param fn name of file from which check is performed * @param funcname name of function for which check is performed * * @return struct indicating whether failure should be simulated * and if so what the status code should be. * Note that the entire struct is returned on the stack, not * a pointer to the struct. */ Failsim_Result fsim_check_failure(const char * fn, const char * funcname) { bool debug = false; DBGF(debug, "Starting. funcname=%s", funcname); Failsim_Result result = {false, 0}; if (fst) { Fsim_Func_Rec * frec = g_hash_table_lookup(fst, funcname); if (frec) { frec->callct++; for (int ndx = 0; ndx < frec->call_occ_recs->len; ndx++) { Fsim_Call_Occ_Rec * occ_rec = &g_array_index(frec->call_occ_recs, Fsim_Call_Occ_Rec, ndx); DBGF(debug, "call_occ_type=%d, callct = %d, occno=%d", occ_rec->call_occ_type, frec->callct, occ_rec->occno); if (occ_rec->call_occ_type == FSIM_CALL_OCC_RECURRING) { if ( frec->callct % occ_rec->occno == 0) { result.force_failure = true; result.failure_value = occ_rec->rc; break; } } else { if (frec->callct == occ_rec->occno) { result.force_failure = true; result.failure_value = occ_rec->rc; break; } } } if (result.force_failure) { printf("Simulating failure for call %d of function %s, returning %d \n", frec->callct, funcname, result.failure_value); // printf("Call stack:\n"); // why wasn't this here in the original version? show_backtrace(2); } } } if (debug) printf("(%s) funcname=%s, returning (%d,%d)\n", __func__, funcname, result.force_failure, result.failure_value); return result; } #ifdef OUT bool fsim_bool_injector(bool status, const char * fn, const char * funcname) { bool debug = false; DBGF(debug, "Starting. status = %s, fn=%s, funcname=%s", SBOOL(status), fn, funcname); bool result = false; if (status && failsim_enabled) { // this is dicey true probably means success, but not necessarily Failsim_Result fsr = fsim_check_failure(fn, funcname); if (fsr.force_failure) result = fsr.failure_value; } DBGF(debug, "Done. Returning %s", SBOOL(result)); return result; } #endif int fsim_int_injector(int status, const char * fn, const char * funcname) { bool debug = false; DBGF(debug, "Starting. failsim_enabled = %s. status = %d, fn=%s, funcname=%s", sbool(failsim_enabled), status, fn, funcname); int result = 0; if (status && failsim_enabled) { Failsim_Result fsr = fsim_check_failure(fn, funcname); if (fsr.force_failure) result = fsr.failure_value; } DBGF(debug, "Done. Returning %d", result); return result; } Error_Info* fsim_errinfo_injector(Error_Info* erec, const char * fn, const char * funcname) { bool debug = false; DBGF(debug, "Starting. failsim_enabled-%s, status = %s, fn=%s, funcname=%s", sbool( failsim_enabled), errinfo_summary(erec), fn, funcname); Error_Info * result = NULL; if (!erec && failsim_enabled) { Failsim_Result fsr = fsim_check_failure(fn, funcname); if (fsr.force_failure) result = errinfo_new(fsr.failure_value, funcname, "Injected Error"); } DBGF(debug, "Done. Returning %s", errinfo_summary(result)); return result; } ddcutil-2.2.0/src/util/libdrm_util.c0000644000175000001440000005004714754153540013054 /** @file libdrm_util.c * Utilities for interpreting libdrm data structures */ // Copyright (C) 2017-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include // for all_displays_drm2() #include #include #include #include /** \endcond */ #include "coredefs_base.h" #include "data_structures.h" #include "drm_common.h" #include "report_util.h" #include "string_util.h" // for all_displays_drm2(): #include // for close() #include "debug_util.h" #include "file_util.h" #include "libdrm_util.h" // /usr/include/libdrm and /usr/include/drm may both contain copies // drm.h amd drm_mode.h, // DRM_MODE_PROP_ATOMIC is found in the libdrm/drm_mode.h, but not in drm/drm_mode.h // In case we've picked up drm/drm_mode.h: #ifndef DRM_MODE_PROP_ATOMIC #define DRM_MODE_PROP_ATOMIC 0x80000000 #endif // // Identifier name tables // // from libdrm/drm.h #define DRM_MODE_PROP_BITMASK (1<<5) /* bitmask of enumerated types */ /* extended-types: rather than continue to consume a bit per type, * grab a chunk of the bits to use as integer type id. */ #define DRM_MODE_PROP_EXTENDED_TYPE 0x0000ffc0 #define DRM_MODE_PROP_TYPE(n) ((n) << 6) // #define DRM_MODE_PROP_OBJECT (DRM_MODE_PROP_TYPE(1)) // #define DRM_MODE_PROP_SIGNED_RANGE (DRM_MODE_PROP_TYPE(2)) Value_Name drm_property_flag_table[] = { VN(DRM_MODE_PROP_PENDING), // (1<<0) == x01 VN(DRM_MODE_PROP_RANGE), // (1<<1) == x02 VN(DRM_MODE_PROP_IMMUTABLE), // (1<<2) == x04 VN(DRM_MODE_PROP_ENUM), // (1<<3) == x88 /* enumerated type with text strings */ VN(DRM_MODE_PROP_BLOB), // (1<<4) == x10 VN(DRM_MODE_PROP_BITMASK), // defined in libdrm/drm.h // VALUE_NAME(DRM_MODE_PROP_ATOMIC), // defined in libdrm/drm.h 64 bit value VN_END }; #ifdef OLD char * interpret_property_flags_r(uint32_t flags, char * buffer, int bufsz) { #ifdef OLD interpret_named_flags_old( drm_property_flag_table, flags, buffer, bufsz, ", "); // sepstr); #endif interpret_named_flags( flags, drm_property_flag_table, ", ", // sepstr buffer, bufsz ); uint32_t extended_type = flags & DRM_MODE_PROP_EXTENDED_TYPE; if (extended_type) { char * extended_name = "other extended type"; if (extended_type == DRM_MODE_PROP_OBJECT) extended_name = "DRM_MODE_PROP_OBJECT"; else if (extended_type == DRM_MODE_PROP_SIGNED_RANGE) extended_name = "DRM_MODE_PROP_SIGNED_RANGE"; sbuf_append(buffer, bufsz, ", ", extended_name); } if (flags & DRM_MODE_PROP_ATOMIC) sbuf_append(buffer, bufsz, ", ", "DRM_MODE_PROP_ATOMIC"); return buffer; } #endif #ifdef OLD char * interpret_property_flags_old(uint32_t flags) { int bufsz = 150; static char property_flags_string[150]; return interpret_property_flags_r(flags, property_flags_string, bufsz); } #endif #ifdef FRAGMENT char * vnt_interpret_flags( uint32_t flags_val, Value_Name_Title_Table bitname_table, bool use_title, char * sepstr) #endif char * interpret_property_flags(uint32_t flags) { static char * buf = NULL; if (buf) free(buf); buf = vnt_interpret_flags( flags, drm_property_flag_table, false, // use name field, not title field ", "); int bufsz = strlen(buf) + 100; buf = realloc(buf, bufsz); // in case we need to append uint32_t extended_type = flags & DRM_MODE_PROP_EXTENDED_TYPE; if (extended_type) { if (strlen(buf) > 0) STRLCAT(buf, ", ", bufsz); char * extended_name = "other extended type"; if (extended_type == DRM_MODE_PROP_OBJECT) extended_name = "DRM_MODE_PROP_OBJECT"; else if (extended_type == DRM_MODE_PROP_SIGNED_RANGE) extended_name = "DRM_MODE_PROP_SIGNED_RANGE"; STRLCAT(buf, extended_name, bufsz); } if (flags & DRM_MODE_PROP_ATOMIC) { if (strlen(buf) > 0) STRLCAT(buf, ", ", bufsz); STRLCAT(buf, "DRM_MODE_PROP_ATOMIC", bufsz); } return buf; } Value_Name_Title drmModeConnection_table[] = { VNT(DRM_MODE_CONNECTED, "connected" ), // 1 VNT(DRM_MODE_DISCONNECTED, "disconnected" ), // 2 VNT(DRM_MODE_UNKNOWNCONNECTION, "unknown" ), // 3 VNT_END }; /** Returns the symbolic name of a drmModeConnection value. * @param val connection state * @return symbolic name */ char * connector_status_name(drmModeConnection val) { return vnt_name(drmModeConnection_table, val); } /** Returns a description string for a drmModeConnection value. * @param val connection state * @return descriptive string */ char * connector_status_title(drmModeConnection val) { return vnt_title(drmModeConnection_table, val); } Value_Name_Title drm_encoder_type_table[] = { VNT(DRM_MODE_ENCODER_NONE, "None"), // 0 VNT(DRM_MODE_ENCODER_DAC, "DAC"), // 1 VNT(DRM_MODE_ENCODER_TMDS, "TDMS"), // 2 VNT(DRM_MODE_ENCODER_LVDS, "LVDS"), // 3 VNT(DRM_MODE_ENCODER_TVDAC, "TVDAC"), // 4 VNT(DRM_MODE_ENCODER_VIRTUAL, "Virtual"), // 5 VNT(DRM_MODE_ENCODER_DSI, "DSI"), // 6 VNT_END }; /** Returns a description string for an encoder type * @param encoder_type encolder type * @return descriptive string */ char * encoder_type_title(uint32_t encoder_type) { return vnt_title(drm_encoder_type_table, encoder_type); } // // Report functions for libdrm data structures // #ifdef REF typedef struct _drmModeRes { int count_fbs; uint32_t *fbs; int count_crtcs; uint32_t *crtcs; int count_connectors; uint32_t *connectors; int count_encoders; uint32_t *encoders; uint32_t min_width, max_width; uint32_t min_height, max_height; } drmModeRes, *drmModeResPtr; #endif static char * join_ids(char * buf, int bufsz, uint32_t* vals, int ct) { buf[0] = '\0'; if (ct > 0 && vals) { strncpy(buf, " -> ", bufsz); for (int ndx = 0; ndx < ct; ndx++) { char b2[20]; snprintf(b2, 20, "%d", vals[ndx]); sbuf_append(buf, bufsz, " ", b2) ; } } return buf; } /** Reports a drmModeRes struct. * * @param res pointer to drmModeRes instance * @param depth logical indentation depth */ void report_drmModeRes(drmModeResPtr res, int depth) { int d1 = depth+1; char buf[200]; int bufsz=200; rpt_structure_loc("drmModeRes", res, depth); rpt_vstring(d1, "%-20s %d", "count_fbs", res->count_fbs); join_ids(buf, bufsz, res->fbs, res->count_fbs); rpt_vstring(d1, "%-20s %p%s", "fbs", res->fbs, buf); rpt_vstring(d1, "%-20s %d", "count_crtcs", res->count_crtcs); join_ids(buf, bufsz, res->crtcs, res->count_crtcs); rpt_vstring(d1, "%-20s %p%s", "crtcs", res->crtcs, buf); rpt_vstring(d1, "%-20s %d", "count_connectors", res->count_connectors); join_ids(buf, bufsz, res->connectors, res->count_connectors); rpt_vstring(d1, "%-20s %p%s", "connectors", res->connectors, buf); rpt_vstring(d1, "%-20s %d", "count_encoders", res->count_encoders); join_ids(buf, bufsz, res->encoders, res->count_encoders); rpt_vstring(d1, "%-20s %p%s", "encoders", res->encoders, buf); rpt_vstring(d1, "%-20s %d", "min_width", res->min_width); rpt_vstring(d1, "%-20s %d", "max_width", res->max_width); rpt_vstring(d1, "%-20s %d", "min_height", res->min_height); rpt_vstring(d1, "%-20s %d", "max_height", res->max_height); } #ifdef REF typedef struct _drmModeModeInfo { uint32_t clock; uint16_t hdisplay, hsync_start, hsync_end, htotal, hskew; uint16_t vdisplay, vsync_start, vsync_end, vtotal, vscan; uint32_t vrefresh; uint32_t flags; uint32_t type; char name[DRM_DISPLAY_MODE_LEN]; } drmModeModeInfo, *drmModeModeInfoPtr; #endif void summarize_drmModeModeInfo(drmModeModeInfo * p, int depth) { // int d1 = depth+1; rpt_vstring(depth, "mode: %s", p->name); // rpt_vstring(d1, "flags: 0x%08x - %s", p->flags, ""); // rpt_vstring(d1, "type: %d = %s", p->type, ""); } #ifdef FOR_DRM_H // For struct in drm.h void report_drm_mode_card_res(struct drm_mode_card_res * res, int depth) { int d1 = depth+1; rpt_structure_loc("drm_mode_card_res", res, depth); rpt_vstring(d1, "%-20s, %ld 0x%08x, %p", "fb_id_ptr:", res->fb_id_ptr, res->fb_id_ptr, res->fb_id_ptr); rpt_vstring(d1, "%-20s, %d", "count_fbs", res->count_fbs); rpt_vstring(d1, "%-20s, %d", "count_crtcs", res->count_crtcs); rpt_vstring(d1, "%-20s, %d", "count_connectors", res->count_connectors); rpt_vstring(d1, "%-20s, %d", "count_encoders", res->count_encoders); rpt_vstring(d1, "%-20s, %d", "min_width", res->min_width); rpt_vstring(d1, "%-20s, %d", "max_width", res->max_width); rpt_vstring(d1, "%-20s, %d", "min_height", res->min_height); rpt_vstring(d1, "%-20s, %d", "max_height", res->max_height); } // This is struct in drm.h, not wrapper libdrm.h #ifdef REF struct drm_mode_get_connector { __u64 encoders_ptr; __u64 modes_ptr; __u64 props_ptr; __u64 prop_values_ptr; __u32 count_modes; __u32 count_props; __u32 count_encoders; __u32 encoder_id; /**< Current Encoder */ __u32 connector_id; /**< Id */ __u32 connector_type; __u32 connector_type_id; __u32 connection; __u32 mm_width; /**< width in millimeters */ __u32 mm_height; /**< height in millimeters */ __u32 subpixel; __u32 pad; }; #endif void report_drm_mode_get_connector(struct drm_mode_get_connector * p, int depth) { int d1 = depth+1; rpt_structure_loc("drm_mode_get_connector", p, depth); rpt_vstring(d1, "%-20s, %ld 0x%08x, %p", "props_ptr:", p->props_ptr, p->props_ptr, p->props_ptr); rpt_vstring(d1, "%-20s, %u", "count_modes", p->count_modes); rpt_vstring(d1, "%-20s, %u", "count_props", p->count_props); rpt_vstring(d1, "%-20s, %u", "count_encoders", p->count_encoders); rpt_vstring(d1, "%-20s, %u", "encouder_id", p->encoder_id); // current encoder rpt_vstring(d1, "%-20s, %d", "connector_id", p->connector_id); rpt_vstring(d1, "%-20s, %d", "connector_type", p->connector_type); rpt_vstring(d1, "%-20s, %d", "connector_type_id", p->connector_type_id); rpt_vstring(d1, "%-20s, %d", "connection", p->connection); rpt_vstring(d1, "%-20s, %d", "mm_width", p->mm_width); rpt_vstring(d1, "%-20s, %d", "mm_height", p->mm_height); rpt_vstring(d1, "%-20s, %d", "subpixel", p->subpixel); // rpt_vstring(d1, "%-20s, %d", "pad", p->pad); } #endif #ifdef REF typedef struct _drmModeConnector { uint32_t connector_id; uint32_t encoder_id; /**< Encoder currently connected to */ uint32_t connector_type; uint32_t connector_type_id; drmModeConnection connection; uint32_t mmWidth, mmHeight; /**< HxW in millimeters */ drmModeSubPixel subpixel; int count_modes; drmModeModeInfoPtr modes; int count_props; uint32_t *props; /**< List of property ids */ uint64_t *prop_values; /**< List of property values */ int count_encoders; uint32_t *encoders; /**< List of encoder ids */ } drmModeConnector, *drmModeConnectorPtr; #endif /* Reports a drmModeConnector struct * * Arguments: * fd file descriptor * p pointer to drmModeConnector struct * depth logical identation depth */ void report_drmModeConnector( int fd, drmModeConnector * p, int depth) { int d1 = depth+1; int d2 = depth+2; char buf[200]; int bufsz=200; rpt_structure_loc("drmModeConnector", p, depth); rpt_vstring(d1, "%-20s %d", "connector_id:", p->connector_id); rpt_vstring(d1, "%-20s %d - %s", "connector_type:", p->connector_type, drm_connector_type_name(p->connector_type)); rpt_vstring(d1, "%-20s %d", "connector_type_id:", p->connector_type_id); rpt_vstring(d1, "%-20s %u", "encoder_id", p->encoder_id); // current encoder #ifdef OLD rpt_vstring(d1, "%-20s %d", "count_encoders", p->count_encoders); buf[0] = '\0'; if (p->count_encoders > 0) { strncpy(buf, " -> ", 100); for (int ndx = 0; ndx < p->count_encoders; ndx++) { snprintf(buf+strlen(buf), 100-strlen(buf), "%d ", p->encoders[ndx]); } } rpt_vstring(d1, "%-20s %p%s", "encoders", p->encoders, buf); #endif rpt_vstring(d1, "%-20s %d", "count_encoders", p->count_encoders); join_ids(buf, bufsz, p->encoders, p->count_encoders); rpt_vstring(d1, "%-20s %p%s", "encoders", p->encoders, buf); rpt_vstring(d1, "%-20s %d", "count_props", p->count_props); for (int ndx = 0; ndx < p->count_props; ndx++) { uint64_t curval = p->prop_values[ndx]; // coverity workaround rpt_vstring(d2, "index=%d, property id (props)=%" PRIu32 ", property value (prop_values)=%" PRIu64 , ndx, p->props[ndx], curval); drmModePropertyPtr prop_ptr = drmModeGetProperty(fd, p->props[ndx]); if (prop_ptr) { report_property_value(fd, prop_ptr, p->prop_values[ndx], d2); drmModeFreeProperty(prop_ptr); } else { rpt_vstring(d2, "Unrecognized property id: %d, value=%"PRIu64, p->props[ndx], p->prop_values[ndx]); } } rpt_nl(); rpt_vstring(d1, "%-20s %d", "count_modes", p->count_modes); for (int ndx = 0; ndx < p->count_modes; ndx++) { // p->nodes is a pointer to an array of struct _drmModeModeInfo, not an array of pointers summarize_drmModeModeInfo( p->modes+ndx, d2); } rpt_vstring(d1, "%-20s %d - %s", "connection:", p->connection, connector_status_name(p->connection)); rpt_vstring(d1, "%-20s %d", "mm_width:", p->mmWidth); rpt_vstring(d1, "%-20s %d", "mm_height:", p->mmHeight); rpt_vstring(d1, "%-20s %d", "subpixel:", p->subpixel); rpt_nl(); } #ifdef REF typedef struct _drmModeProperty { uint32_t prop_id; uint32_t flags; char name[DRM_PROP_NAME_LEN]; int count_values; uint64_t *values; /* store the blob lengths */ int count_enums; struct drm_mode_property_enum *enums; int count_blobs; uint32_t *blob_ids; /* store the blob IDs */ } drmModePropertyRes, *drmModePropertyPtr; #endif /** Reports the raw bytes of a blob. * * @param blob_ptr pointer to a drmModePropertyBlobRes * @param depth logical indentation depth */ void report_drmModePropertyBlob(drmModePropertyBlobPtr blob_ptr, int depth) { rpt_vstring(depth, "blob id: %u", blob_ptr->id); rpt_hex_dump(blob_ptr->data, blob_ptr->length, depth); } /** Reports a property value * * @param fd file descriptor of open DRM device * @param prop_ptr pointer to struct containing property metadata * @param prop_value property value * @param depth logical indentation depth */ void report_property_value( int fd, drmModePropertyRes * prop_ptr, uint64_t prop_value, int depth) { int d1 = depth+1; rpt_vstring(depth, "Property id: %d", prop_ptr->prop_id); rpt_vstring(d1, "Name: %s", prop_ptr->name); rpt_vstring(d1, "Flags: 0x%04x - %s", (unsigned int) prop_ptr->flags, interpret_property_flags(prop_ptr->flags) ); rpt_vstring(d1, "prop_value: %"PRIu64" 0x%08x", prop_value, (unsigned int) prop_value); if (prop_ptr->flags & DRM_MODE_PROP_ENUM) { for (int i = 0; i < prop_ptr->count_enums; i++) { if (prop_ptr->enums[i].value == prop_value) { rpt_vstring(d1, "Property value(enum) = %"PRIu64" - %s", prop_value, prop_ptr->enums[i].name); break; } } } else if (prop_ptr->flags & DRM_MODE_PROP_BITMASK) { char buf[200] = ""; int bufsz=200; bool not_truncated = true; for (int i = 0; i < prop_ptr->count_enums && not_truncated; i++) { if (prop_ptr->enums[i].value & prop_value) { not_truncated = sbuf_append(buf, bufsz, ", ", prop_ptr->enums[i].name); } } rpt_vstring(d1, "Property value(bitmask) = 0x%04x - %s", (unsigned int) prop_value, buf); } else if (prop_ptr->flags & DRM_MODE_PROP_RANGE) { if (prop_ptr->count_values != 2) { rpt_vstring(d1, "Property value = %"PRIu64", Missing min or max value", prop_value); } else { rpt_vstring(d1, "Property value(range) = %" PRIu64 ", min=%" PRIu64 ", max=%" PRIu64, prop_value, prop_ptr->values[0], prop_ptr->values[1]); } } // if (prop_ptr->flags & DRM_MODE_PROP_BLOB) { else if (drm_property_type_is(prop_ptr, DRM_MODE_PROP_BLOB)) { drmModePropertyBlobPtr blob_ptr = drmModeGetPropertyBlob(fd, prop_value); if (!blob_ptr) { rpt_vstring(d1, "Blob not found"); } else { report_drmModePropertyBlob(blob_ptr, d1); drmModeFreePropertyBlob(blob_ptr); } } else if (drm_property_type_is(prop_ptr, DRM_MODE_PROP_OBJECT)) { rpt_vstring(d1, "Object type, name = %s, value=%"PRIu64, prop_ptr->name, prop_value); } else if (drm_property_type_is(prop_ptr, DRM_MODE_PROP_SIGNED_RANGE)) { if (prop_ptr->count_values != 2) { rpt_vstring(d1, "Signed property value = %"PRIu64", Missing min or max value", prop_value); } else { rpt_vstring(d1, "Property value(range) = %" PRIu64 ", min=%" PRIu64 ", max=%" PRIu64, prop_value, prop_ptr->values[0], prop_ptr->values[1]); } } else { rpt_vstring(d1, "Unrecognized type flags=0x%08x, value = %" PRIu64, prop_ptr->flags, prop_value); } } #ifdef UGH // this belongs in property description, not in value dump if (prop->flags & DRM_MODE_PROP_BLOB) { printf("\t\tblobs:\n"); for (i = 0; i < prop->count_blobs; i++) dump_blob(dev, prop->blob_ids[i]); printf("\n"); } else { assert(prop->count_blobs == 0); } printf("\t\tvalue:"); if (prop->flags & DRM_MODE_PROP_BLOB) dump_blob(dev, value); else printf(" %"PRIu64"\n", value); #endif /** Reports a **drmModePropertyRes struct * * @param p pointer to drmModePropertyRes * @param depth logical indentation deptn */ void report_drm_modeProperty(drmModePropertyRes * p, int depth) { rpt_structure_loc("drmModePropertyRes", p, depth); int d1 = depth+1; int d2 = depth+2; rpt_vstring(d1, "%-20s %d", "prop_id:", p->prop_id); rpt_vstring(d1, "%-20s 0x%08x - %s", "flags:", p->flags, interpret_property_flags(p->flags)); rpt_vstring(d1, "%-20s %s", "name:", p->name); // null terminated? rpt_vstring(d1, "%-20s %d", "count_values:", p->count_values); for (int ndx = 0; ndx < p->count_values; ndx++) { rpt_vstring(d2, "values[%d] = %lu", ndx, p->values[ndx]); } rpt_vstring(d1, "%-20s %d", "count_enums:", p->count_enums); for (int ndx = 0; ndx < p->count_enums; ndx++) { uint64_t curval = p->enums[ndx].value; // coverity workaround rpt_vstring(d2, "enums[%d] = %" PRIu64 ": %s", ndx, curval, (char *) p->enums[ndx].name); } rpt_vstring(d1, "%-20s %d", "count_blobs:", p->count_blobs); for (int ndx = 0; ndx < p->count_blobs; ndx++) { rpt_vstring(d2, "blob_ids[%d] = %u", ndx, p->blob_ids[ndx]); } } /** Emits a summary report for a **drmModePropertyRes struct * * @param p pointer to drmModePropertyRes * @param depth logical indentation deptn */ void summarize_drm_modeProperty(drmModePropertyRes * p, int depth) { rpt_vstring(depth, "Property %2d: %-20s flags: 0x%08x - %s", p->prop_id, p->name, p->flags, interpret_property_flags(p->flags) ); } ddcutil-2.2.0/src/util/drm_common.c0000644000175000001440000005502314754153540012677 /** @file drm_common.c * * Consolidates DRM function variants the have proliferated in the code base. */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include // for all_displays_drm2() #include #include #include #include #include #include // for close() used by probe_dri_device_using_drm_api #include #include #include /** \endcond */ #include "coredefs_base.h" #include "data_structures.h" #include "debug_util.h" #include "file_util.h" #include "subprocess_util.h" #include "regex_util.h" #include "report_util.h" #include "string_util.h" #include "sysfs_filter_functions.h" #include "sysfs_i2c_util.h" #include "sysfs_util.h" #include "timestamp.h" #include "drm_common.h" // from i2c_sysfs.c /** Checks if DRM is supported for a busid. * * Takes a bus id of the form: PCI:xxxx:xx:xx:d, :domain:bus:dev.func * * @param busid2 DRM PCI bus id */ bool check_drm_supported_using_drm_api(char * busid2) { bool debug = false; bool supports_drm = false; // Notes from examining the code for drmCheckModesettingAvailable() // // Checks if a modesetting capable driver has been attached to the pci id // n.b. drmCheckModesettingSupport() takes a busid string as argument, not filename // // Returns 0 if bus id valid and modesetting supported // -EINVAL if invalid bus id // -ENOSYS if no modesetting support // does not set errno int rc = drmCheckModesettingSupported(busid2); DBGF(debug, "drmCheckModesettingSupported() returned %d for %s", rc, busid2); switch (rc) { case (0): supports_drm = true; break; case (-EINVAL): DBGF(debug, "Invalid bus id (-EINVAL)"); break; case (-ENOSYS): DBGF(debug, "Modesetting not supported (-ENOSYS)"); break; default: DBGF(debug, "drmCheckModesettingSupported() returned undocumented status code %d", rc); } return supports_drm; } // from i2c/i2c_sysfs.c /** Checks if a video adapter supports DRM, using DRM functions. * * @param adapter_path fully qualified path of video adapter node in sysfs * @retval true driver supports DRM * @@retval false driver does not support DRM, or ddcutil not built with DRM support */ bool adapter_supports_drm_using_drm_api(const char * adapter_path) { bool debug = false; DBGF(debug, "Starting. adapter_path=%s", adapter_path); assert(adapter_path); bool result = false; #ifdef USE_LIBDRM char * adapter_basename = g_path_get_basename(adapter_path); char buf[20]; g_snprintf(buf, 20, "pci:%s", adapter_basename); free(adapter_basename); result = check_drm_supported_using_drm_api(buf); #endif DBGF(debug, "Done. Returning: %s", sbool(result)); return result; } /** Checks if all video adapters in an array of sysfs adapter paths * support DRM * * @oaram adapter_paths array of paths to adapter nodes in sysfs * @return true if all adapters support DRM, false if not or the array is empty */ bool all_video_adapters_support_drm_using_drm_api(GPtrArray * adapter_paths) { bool debug = false; DBGF(debug, "Starting. adapter_paths->len=%d", adapter_paths->len); bool result = false; if (adapter_paths && adapter_paths->len > 0) { result = true; for (int ndx = 0; ndx < adapter_paths->len; ndx++) { result &= adapter_supports_drm_using_drm_api(g_ptr_array_index(adapter_paths, ndx)); } } DBGF(debug, "Done. Returning: %s", sbool(result)); return result; } const char * drm_bus_type_name(uint8_t bus) { char * result = NULL; switch(bus) { case DRM_BUS_PCI: result = "pci"; break; // 0 case DRM_BUS_USB: result = "usb"; break; // 1 case DRM_BUS_PLATFORM: result = "platform"; break; // 2 case DRM_BUS_HOST1X: result = "host1x"; break; // 3 default: result = "unrecognized"; } return result; } /* Filter to find driN files using scandir() in get_filenames_by_filter() */ static int is_dri2(const struct dirent *ent) { return str_starts_with(ent->d_name, "card"); } /* Scans /dev/dri to obtain list of device names * * Returns: GPtrArray of device names, caller must free */ GPtrArray * get_dri_device_names_using_filesys() { const char *dri_paths[] = { "/dev/dri/", NULL }; GPtrArray* dev_names = get_filenames_by_filter(dri_paths, is_dri2); g_ptr_array_sort(dev_names, gaux_ptr_scomp); // needed? return dev_names; } bool probe_dri_device_using_drm_api(const char * devname) { bool debug = false; DBGF(debug, "Starting. devname = %s", devname); bool supports_drm = false; // int fd = open(devname,O_RDWR | O_CLOEXEC); // WTF? O_CLOEXEC undeclared, works in query_sysenv.c int fd = open(devname,O_RDWR); if (fd < 0) { DBGF(debug, "Error opening device %s using open(), errno=%d", devname, errno); } else { DBGF(debug, "Open succeeded for device: %s", devname); char busid2[30] = ""; struct _drmDevice * ddev; // gets information about the opened DRM device // returns 0 on success, negative error code otherwise int get_device_rc = drmGetDevice(fd, &ddev); if (get_device_rc < 0) { DBGF(debug, "drmGetDevice() returned %d = %s", get_device_rc, strerror(-get_device_rc)); } else { snprintf(busid2, sizeof(busid2), "%s:%04x:%02x:%02x.%d", drm_bus_type_name(ddev->bustype), ddev->businfo.pci->domain, ddev->businfo.pci->bus, ddev->businfo.pci->dev, ddev->businfo.pci->func); DBGF(debug, "domain:bus:device.func: %04x:%02x:%02x.%d", ddev->businfo.pci->domain, ddev->businfo.pci->bus, ddev->businfo.pci->dev, ddev->businfo.pci->func); DBGF(debug, "busid2 = |%s|", busid2); supports_drm = check_drm_supported_using_drm_api(busid2); drmFreeDevice(&ddev); } close(fd); } DBGF(debug, "Done. Returning: %s", sbool(supports_drm)); return supports_drm; } /** Checks if all display adapters support DRM. * * For each file in /dev/dri, use DRM API to ensure that * DRM is supported by using the drm api. * * @return true if all adapters support DRM * * @remark: unreliable on Wayland!? */ bool all_displays_drm_using_drm_api() { bool debug = false; DBGF(debug, "Starting"); bool result = false; // returns false on banner under Wayland!!!! int drm_available = drmAvailable(); DBGF(debug, "drmAvailable() returned: %d", drm_available); if (drm_available) { GPtrArray * dev_names = get_dri_device_names_using_filesys(); if (dev_names->len > 0) result = true; for (int ndx = 0; ndx < dev_names->len; ndx++) { char * dev_name = g_ptr_array_index(dev_names, ndx); if (! probe_dri_device_using_drm_api( dev_name)) result = false; } g_ptr_array_free(dev_names, true); } DBGF(debug, "Done. Returning: %s", sbool(result)); return result; } // from sysfs_i2c_util.c #ifdef UNUSED static void do_sysfs_drm_card_number_dir( const char * dirname, // /drm const char * simple_fn, // card0, card1, etc. void * data, int depth) { bool debug = false; if (debug) printf("(%s) Starting. dirname=%s, simple_fn=%s\n", __func__, dirname, simple_fn); Bit_Set_256 * card_numbers = (Bit_Set_256*) data; const char * s = simple_fn+4; int card_number = atoi(s); *card_numbers = bs256_insert(*card_numbers, card_number); if (debug) printf("(%s) Done. Added %d\n", __func__, card_number); } Bit_Set_32 get_sysfs_drm_card_numbers() { bool debug = false; char * dname = #ifdef TARGET_BSD "/compat/linux/sys/class/drm"; #else "/sys/class/drm"; #endif if (debug) printf("(%s) Examining %s\n", __func__, dname); Bit_Set_32 result = EMPTY_BIT_SET_32; dir_foreach( dname, predicate_cardN, // filter function do_sysfs_drm_card_number_dir, &result, // accumulator 0); if (debug) printf("(%s) Done. Returning DRM card numbers: %s\n", __func__, bs32_to_string_decimal(result, "", ", ")); return result; } #endif typedef struct { bool has_card_connector_dir; } Check_Card_Struct; #ifdef REF typedef void (*Dir_Foreach_Func)( const char * dirname, const char * fn, void * accumulator, int depth); #endif void dir_foreach_set_true(const char * dirname, const char * fn, void * accumulator, int depth) { bool debug = false; DBGF(debug, "dirname=%s, fn=%s, accumlator=%p, depth=%d", dirname, fn, accumulator, depth); Check_Card_Struct * accum = accumulator; DBGF(debug, "Setting accumulator->has_card_connector_dir = true"); accum->has_card_connector_dir = true; } void do_one_card(const char * dirname, const char * fn, void* accumulator, int depth) { bool debug = false; char buf[PATH_MAX]; g_snprintf(buf, sizeof(buf), "%s/%s", dirname, fn); DBGF(debug, "Examining dir buf=%s", buf); dir_foreach(buf, predicate_cardN_connector, dir_foreach_set_true, accumulator, depth); Check_Card_Struct * accum = accumulator; DBGF(debug, "Finishing with accumlator->has_card_connector_dir = %s", sbool(accum->has_card_connector_dir)); } // n. could enhance to collect the card connector subdir names bool card_connector_subdirs_exist(const char * adapter_dir) { bool debug = false; DBGF(debug, "Starting. adapter_dir = %s", adapter_dir); int lastpos= strlen(adapter_dir) - 1; char * delim = (adapter_dir[lastpos] == '/') ? "" : "/"; char drm_dir[PATH_MAX]; g_snprintf(drm_dir, PATH_MAX, "%s%sdrm", adapter_dir,delim); DBGF(debug, "drm_dir=%s", drm_dir); int d = (debug) ? 1 : -1; Check_Card_Struct * accumulator = calloc(1, sizeof(Check_Card_Struct)); dir_foreach(drm_dir, predicate_cardN, do_one_card, accumulator, d); bool has_card_subdir = accumulator->has_card_connector_dir; free(accumulator); DBGF(debug, "Done. Returning %s", sbool(has_card_subdir)); return has_card_subdir; } /** Check that all devices in a list of video adapter devices have drivers that implement * drm by looking for card_connector_dirs in each adapter's drm directory. * * @param adapter_devices array of /sys directory names for video adapter devices * @return true if all adapter video drivers implement drm */ bool check_video_adapters_list_implements_drm(GPtrArray * adapter_devices) { bool debug = false; assert(adapter_devices); uint64_t t0, t1; if (debug) t0 = cur_realtime_nanosec(); DBGF(debug, "adapter_devices->len=%d at %p", adapter_devices->len, adapter_devices); bool result = true; for (int ndx = 0; ndx < adapter_devices->len; ndx++) { // char * subdir_name = NULL; char * adapter_dir = g_ptr_array_index(adapter_devices, ndx); bool has_card_subdir = card_connector_subdirs_exist(adapter_dir); // DBGF(debug, "Examined. has_card_subdir = %s", sbool(has_card_subdir)); if (!has_card_subdir) { result = false; break; } } if (debug) { t1 = cur_realtime_nanosec(); DBG("elapsed: %jd microsec", NANOS2MICROS(t1-t0)); } DBGF(debug, "Done. Returning %s", sbool(result)); return result; } /** Checks that all video adapters on the system have drivers that implement drm * by checking that card connector directories drm/cardN/cardN-xxx exist. * * @return true if all video adapters have drivers implementing drm, false if not * * The degenerate case of no video adapters returns false. * */ bool check_all_video_adapters_implement_drm() { bool debug = false; DBGF(debug, "Starting"); uint64_t t0 = cur_realtime_nanosec(); // DBGF(debug, "t0=%"PRIu64, t0); GPtrArray * devices = get_video_adapter_devices(); uint64_t t1 = cur_realtime_nanosec(); // DBGF(debug, "t1=%"PRIu64, t1); // DBGF(debug, "t1-t0=%"PRIu64, t1-t0); DBGF(debug, "get_video_adapter_devices() took %jd microseconds", NANOS2MICROS(t1-t0)); bool all_drm = check_video_adapters_list_implements_drm(devices); uint64_t t2 = cur_realtime_nanosec(); // DBGF(debug, "t2=%"PRIu64, t2); // DBGF(debug, "t2-t1=%"PRIu64, t2-t1); DBGF(debug, "check_video_adapters_list_implements_drm() took %jd microseconds", NANOS2MICROS(t2-t1)); g_ptr_array_free(devices, true); // DBGF(debug, "t2-t0=%"PRIu64, t2-t0); DBGF(debug, "Done. Returning %s. elapsed=%jd microsec", sbool(all_drm), NANOS2MICROS(t2-t0)); return all_drm; } #ifdef TO_FIX /** Checks if a display has a DRM driver by looking for * card connector subdirs of drm in the adapter directory. * * @param busno I2C bus number * @return true/false */ bool is_drm_display_by_busno(int busno) { bool debug = false; DBGF(debug, "Starting. busno = %d", busno); bool result = false; char i2cdir[40]; g_snprintf(i2cdir, 40, "/sys/bus/i2c/devices/i2c-%d",busno); char * real_i2cdir = NULL; GET_ATTR_REALPATH(&real_i2cdir, i2cdir); DBGF(debug, "real_i2cdir = %s", real_i2cdir); assert(real_i2cdir); int d = (debug) ? 1 : -1; char * adapter_dir = find_adapter(real_i2cdir, d); // in i2c/i2c_sysfs.c, need to fix assert(adapter_dir); result = card_connector_subdirs_exist(adapter_dir); free(real_i2cdir); free(adapter_dir); DBGF(debug, "Done. Returning: %s", sbool(result)); return result; } #endif #ifndef DRM_MODE_CONNECTOR_USB // not defined in debian 11 (bullseye) #define DRM_MODE_CONNECTOR_USB 20 #endif Value_Name_Title drm_connector_type_table[] = { VNT(DRM_MODE_CONNECTOR_Unknown , "unknown" ), // 0 VNT(DRM_MODE_CONNECTOR_VGA , "VGA" ), // 1 VNT(DRM_MODE_CONNECTOR_DVII , "DVI-I" ), // 2 VNT(DRM_MODE_CONNECTOR_DVID , "DVI-D" ), // 3 VNT(DRM_MODE_CONNECTOR_DVIA , "DVI-A" ), // 4 VNT(DRM_MODE_CONNECTOR_Composite , "Composite" ), // 5 VNT(DRM_MODE_CONNECTOR_SVIDEO , "S-video" ), // 6 VNT(DRM_MODE_CONNECTOR_LVDS , "LVDS" ), // 7 VNT(DRM_MODE_CONNECTOR_Component , "Component" ), // 8 VNT(DRM_MODE_CONNECTOR_9PinDIN , "DIN" ), // 9 VNT(DRM_MODE_CONNECTOR_DisplayPort , "DP" ), // 10 VNT(DRM_MODE_CONNECTOR_HDMIA , "HDMI" ), // 11 VNT(DRM_MODE_CONNECTOR_HDMIB , "HDMI-B" ), // 12 VNT(DRM_MODE_CONNECTOR_TV , "TV" ), // 13 VNT(DRM_MODE_CONNECTOR_eDP , "eDP" ), // 14 VNT(DRM_MODE_CONNECTOR_VIRTUAL , "Virtual" ), // 15 VNT(DRM_MODE_CONNECTOR_DSI , "DSI" ), // 16 Display Signal Interface, used on Raspberry Pi VNT(DRM_MODE_CONNECTOR_DPI , "DPI" ), // 17 VNT(DRM_MODE_CONNECTOR_WRITEBACK , "WRITEBACK" ), // 18 VNT(DRM_MODE_CONNECTOR_SPI , "SPI" ), // 19 VNT(DRM_MODE_CONNECTOR_USB , "USB" ), // 20 VNT_END }; /** Returns the symbolic name of a connector type. * @param val connector type * @return symbolic name */ char * drm_connector_type_name(Byte val) { return vnt_name(drm_connector_type_table, val); } /** Returns the description string for a connector type. * @param val connector type * @return descriptive string */ char * drm_connector_type_title(Byte val) { return vnt_title(drm_connector_type_table, val); } // For getting the DRM connector type from the DRM connector name Value_Name_Title connector_type_lookup_table[] = { VNT(DRM_MODE_CONNECTOR_Unknown , "unknown" ), // 0 VNT(DRM_MODE_CONNECTOR_VGA , "VGA" ), // 1 VNT(DRM_MODE_CONNECTOR_DVII , "DVII" ), // 2 VNT(DRM_MODE_CONNECTOR_DVID , "DVID" ), // 3 VNT(DRM_MODE_CONNECTOR_DVIA , "DVIA" ), // 4 VNT(DRM_MODE_CONNECTOR_Composite , "Composite" ), // 5 VNT(DRM_MODE_CONNECTOR_SVIDEO , "Svideo" ), // 6 VNT(DRM_MODE_CONNECTOR_LVDS , "LVDS" ), // 7 VNT(DRM_MODE_CONNECTOR_Component , "Component" ), // 8 VNT(DRM_MODE_CONNECTOR_9PinDIN , "DIN" ), // 9 VNT(DRM_MODE_CONNECTOR_DisplayPort , "DP" ), // 10 VNT(DRM_MODE_CONNECTOR_HDMIA , "HDMI" ), // 11 alternate common name for HDMIA VNT(DRM_MODE_CONNECTOR_HDMIA , "HDMIA" ), // 11 VNT(DRM_MODE_CONNECTOR_HDMIB , "HDMIB" ), // 12 VNT(DRM_MODE_CONNECTOR_TV , "TV" ), // 13 VNT(DRM_MODE_CONNECTOR_eDP , "eDP" ), // 14 VNT(DRM_MODE_CONNECTOR_VIRTUAL , "Virtual" ), // 15 VNT(DRM_MODE_CONNECTOR_DSI , "DSI" ), // 16 Display Signal Interface, used on Raspberry Pi VNT(DRM_MODE_CONNECTOR_DPI , "DPI" ), // 17 VNT(DRM_MODE_CONNECTOR_WRITEBACK , "WRITEBACK" ), // 18 VNT(DRM_MODE_CONNECTOR_SPI , "SPI" ), // 19 VNT(DRM_MODE_CONNECTOR_USB , "USB" ), // 20 VNT_END }; int lookup_connector_type(const char * name) { int val = vnt_find_id( connector_type_lookup_table, name, true, // search by title true, // ignore_case, -1); // default_id return val; } char * dci_repr(Drm_Connector_Identifier dci) { char * buf = g_strdup_printf("[dci:cardno=%d,connector_id=%d,connector_type=%d=%s,connector_type_id=%d]", dci.cardno, dci.connector_id, dci.connector_type, drm_connector_type_name(dci.connector_type), dci.connector_type_id); return buf; } /** Thread safe function that returns a brief string representation of a #Drm_Connector_Identifier. * The returned value is valid until the next call to this function on the current thread. * * * \param dpath pointer to ##DDCA_IO_Path * \return string representation of #DDCA_IO_Path */ char * dci_repr_t(Drm_Connector_Identifier dci) { static GPrivate dci_repr_key = G_PRIVATE_INIT(g_free); char * repr = dci_repr(dci); char * buf = get_thread_fixed_buffer(&dci_repr_key, 100); g_snprintf(buf, 100, "%s", repr); free(repr); return buf; } bool dci_eq(Drm_Connector_Identifier dci1, Drm_Connector_Identifier dci2) { bool result = false; if (dci1.connector_id > 0 && dci1.connector_id == dci2.connector_id) { result = true; } else result = dci1.cardno == dci2.cardno && dci1.connector_type == dci2.connector_type && dci1.connector_type_id == dci2.connector_type_id; return result; } /** Compares 2 Drm_Connector_Identifier values. */ int dci_cmp(Drm_Connector_Identifier dci1, Drm_Connector_Identifier dci2) { int result = 0; if (dci1.cardno < dci2.cardno) result = -1; else if (dci1.cardno > dci2.cardno) result = 1; else { if (dci1.connector_type < dci2.connector_type) result = -1; else if (dci1.connector_type > dci2.connector_type) result = 1; else { if (dci1.connector_type_id < dci2.connector_type_id) result = -1; else if (dci1.connector_type_id > dci2.connector_type_id) result = 1; else result = 0; } } return result; } /** Compare drm connector names so that e.g. card1-DP-10 comes * after card1-DP-2, not before. */ int sys_drm_connector_name_cmp0(const char * s1, const char * s2) { int result = 0; // do something "reasonable" for pathological cases if (!s1 && s2) result = -1; else if (!s1 && !s2) result = 0; else if (s1 && !s2) result = 1; else { // normal case Drm_Connector_Identifier dci1 = parse_sys_drm_connector_name(s1); Drm_Connector_Identifier dci2 = parse_sys_drm_connector_name(s2); result = dci_cmp(dci1, dci2); } return result; } /** QSort style comparison function for sorting drm connector names. */ int sys_drm_connector_name_cmp(gconstpointer connector_name1, gconstpointer connector_name2) { bool debug = false; int result = 0; char * s1 = (connector_name1) ? *(char**)connector_name1 : NULL; char * s2 = (connector_name2) ? *(char**)connector_name2 : NULL; DBGF(debug, "s1=%p->%s, s2=%p->%s", s1, s1, s2, s2); result = sys_drm_connector_name_cmp0(s1, s2); DBGF(debug, "Returning: %d", result); return result; } Drm_Connector_Identifier parse_sys_drm_connector_name(const char * drm_connector) { bool debug = false; DBGF(debug, "Starting. drm_connector = |%s|", drm_connector); Drm_Connector_Identifier result = {-1,-1,-1,-1}; static const char * drm_connector_pattern = "^card([0-9])[-](.*)[-]([0-9]+)"; regmatch_t matches[4]; bool ok = compile_and_eval_regex_with_matches( drm_connector_pattern, drm_connector, 4, // max_matches, matches); if (ok) { // for (int kk = 0; kk < 4; kk++) { // rpt_vstring(1, "match %d, substring start=%d, end=%d", kk, matches[kk].rm_so, matches[kk].rm_eo); // } char * cardno_s = substr(drm_connector, matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so); char * connector_type = substr(drm_connector, matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so); char * connector_type_id_s = substr(drm_connector, matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so); // DBGF(debug, "cardno_s=|%s|", cardno_s); // DBGF(debug, "connector_type=|%s|", connector_type); // DBGF(debug, "connector_type_id_s=|%s|", connector_type_id_s); ok = str_to_int(cardno_s, &result.cardno, 10); assert(ok); ok = str_to_int(connector_type_id_s, &result.connector_type_id, 10); assert(ok); // DBGF(debug, "result.cardno: %d", result.cardno); // DBGF(debug, "connector_type_id: %d", result.connector_type_id); result.connector_type = lookup_connector_type(connector_type); free(connector_type); free(cardno_s); free(connector_type_id_s); } if (debug) { char * s = dci_repr(result); DBG("Done. Returning: %s", s); free(s); } return result; } ddcutil-2.2.0/src/util/x11_util.c0000644000175000001440000002470214754153540012213 /** @file x11_util.c X11 related utility functions */ /* Adapted from file randr-edid.c from libCEC. How to properly handle copyright? * * Copyright (C) 2014-2023 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * Adapted from libCEC by Pulse-Eight Limited. Pulse-Eight's copyright follows: * * This file is part of the libCEC(R) library. * * libCEC(R) is Copyright (C) 2011-2015 Pulse-Eight Limited. All rights reserved. * libCEC(R) is an original work, containing original code. * * libCEC(R) is a trademark of Pulse-Eight Limited. * * This program is dual-licensed; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * * Alternatively, you can license this library under a commercial license, * please contact Pulse-Eight Licensing for more information. * * For more information contact: * Pulse-Eight Licensing * http://www.pulse-eight.com/ * http://www.pulse-eight.net/ */ /** \cond */ #include #include #include #include #include #include #include #include #include #include #include #include /** \endcond */ // #include "env.h" // #include "randr-edid.h" #include "string_util.h" #include "x11_util.h" static const char * const edid_names[] = { #if (RANDR_MAJOR > 1) || (RANDR_MAJOR == 1 && RANDR_MINOR >2) RR_PROPERTY_RANDR_EDID, #else "EDID", #endif "EDID_DATA", "XFree86_DDC_EDID1_RAWDATA" }; #define EDID_NAME_COUNT (sizeof(edid_names)/sizeof(*edid_names)) // GPtrArray callback function // typedef: void (*GDestroyNotify)(gpointer data) static void edid_recs_free_func(gpointer voidptr) { X11_Edid_Rec * prec = voidptr; free(prec->edidbytes); free(prec->output_name); free(prec); } /* XRRGetScreenResourcesCurrent vs XRRGetScreenResources. from: https://stackoverflow.com/questions/29625442/how-to-find-the-dpi-of-a-monitor-on-which-a-specific-window-is-placed-in-linux There are actually 2 functions to query resources about the screens: XRRGetScreenResourcesCurrent and XRRGetScreenResources. The first one returns some cached value, while the latter one asks the server which may introduce polling. The description (search for RRGetScreenResources): https://www.x.org/releases/X11R7.6/doc/randrproto/randrproto.txt Someone went through the trouble timing it: https://github.com/glfw/glfw/issues/347 XRRGetScreenResourcesCurrent: Typically from 20 to 100 us. XRRGetScreenResources: Typically from 13600 to 13700 us. */ /** Obtains all the EDIDs known to X11. * * @return GPtrArray of X11_Edid_Rec * * It is the responsibility of the caller to free the returned data structure */ GPtrArray * get_x11_edids(bool use_screen_resources_current) { bool debug = false; GPtrArray * edid_recs = g_ptr_array_new(); g_ptr_array_set_free_func(edid_recs, edid_recs_free_func); //uint16_t physical_address = 0; /* open default X11 DISPLAY */ Display *disp = XOpenDisplay(NULL); if( disp ) { int event_base, error_base; int maj, min; if( XRRQueryExtension(disp, &event_base, &error_base) && XRRQueryVersion(disp, &maj, &min) ) { int version = (maj << 8) | min; if( version >= 0x0102 ) { size_t atom_avail = 0; Atom edid_atoms[EDID_NAME_COUNT]; if( XInternAtoms(disp, (char **)edid_names, EDID_NAME_COUNT, True, edid_atoms) ) { /* remove missing some atoms */ atom_avail = 0; for(size_t atom_count=0; atom_count 0 ) { int scr_count = ScreenCount(disp); int screen; for(screen=0; screen 1) || (RANDR_MAJOR == 1 && RANDR_MINOR >=3) if( version >= 0x0103 ) { /* get cached resources if they are available */ if (use_screen_resources_current) rsrc = XRRGetScreenResourcesCurrent(disp, root); } if( NULL == rsrc ) #endif rsrc = XRRGetScreenResources(disp, root); if( NULL != rsrc ) { int output_id; for( output_id=0; output_id < rsrc->noutput; ++output_id ) { RROutput rr_output_id = rsrc->outputs[output_id]; XRROutputInfo *output_info = XRRGetOutputInfo(disp, rsrc, rr_output_id); if( NULL != output_info ) { // printf("Found output %.*s\n", output_info->nameLen, output_info->name); if( RR_Connected == output_info->connection ) { // printf("is connected\n"); bool edid_found = false; for(size_t atom_count=0; !edid_found && atom_countedidbytes = calloc(1,128); memcpy(edidrec->edidbytes, data, 128); edidrec->output_name = calloc(1, output_info->nameLen + 1); memcpy(edidrec->output_name, output_info->name, output_info->nameLen); g_ptr_array_add(edid_recs, edidrec); edid_found = true; // physical_address = CEDIDParser::GetPhysicalAddressFromEDID(data, nitems); } XFree(data); } } } XRRFreeOutputInfo(output_info); } else break; /* problem ? */ } XRRFreeScreenResources(rsrc); } } } } } XCloseDisplay(disp); } if (debug) { int ndx = 0; printf("Returning %d X11_Edid_Recs\n", edid_recs->len); for (; ndx < edid_recs->len; ndx++) { X11_Edid_Rec * prec = g_ptr_array_index(edid_recs, ndx); printf(" Output name: %s -> %p\n", prec->output_name, prec->edidbytes); hex_dump(prec->edidbytes, 128); } } return edid_recs; } /** Frees the data structure returned by get_x11_edids() * * @param edidrecs pointer to GPtrArray of pointers to X11_Edid_Rec */ void free_x11_edids(GPtrArray * edidrecs) { g_ptr_array_free(edidrecs, true); } bool get_x11_dpms_info(unsigned short * power_level, unsigned char * state) { Display *disp = XOpenDisplay(NULL); bool result = false; if( disp ) { int major_opcode; int minor_opcode; int first_error; bool found_extension = XQueryExtension(disp, DPMSExtensionName, &major_opcode, &minor_opcode, &first_error); if (found_extension) { /* The DPMSInfo function returns information about the current * Display Power Management Signaling (DPMS) state. * The state return parameter indicates whether or not DPMS is enabled (TRUE) * or disabled (FALSE). The power_level return parameter indicates the current * power level (one of DPMSModeOn, DPMSModeStandby, DPMSModeSuspend, or DPMSModeOff.) */ result = DPMSInfo(disp, power_level, state); } XCloseDisplay(disp); } return result; } const char* dpms_power_level_name(unsigned short power_level) { char * name = NULL; switch(power_level) { case 0: name = "DPMSModeOn"; break; case 1: name = "DPMSModeStandby"; break; case 2: name = "DPMSModeSuspend"; break; case 3: name = "DPMSModeOff"; break; default: name = "Invalid Value"; } return name; } ddcutil-2.2.0/src/util/utilrpt.h0000664000175000001440000000223714754576332012266 /* utilrpt.h * * * Copyright (C) 2014-2017 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ /** \f * Report functions for other utility modules. * Avoids complex dependencies between report_util.c and other * util files. */ #ifndef UTILRPT_H_ #define UTILRPT_H_ #include "data_structures.h" void dbgrpt_buffer(Buffer * buffer, int depth); #endif /* UTILRPT_H_ */ ddcutil-2.2.0/src/util/file_util_base.h0000644000175000001440000000111514754576332013521 /** \file file_util_base.h * Core file utility functions. * This file exists so that includes in util directory can form * a directed graph. */ // Copyright (C) 2018-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef FILE_UTIL_BASE_H_ #define FILE_UTIL_BASE_H_ #include #include #ifdef __cplusplus extern "C" { #endif int file_getlines( const char * fn, GPtrArray* line_array, bool verbose) ; #ifdef __cplusplus } // extern "C" #endif #endif /* FILE_UTIL_BASE_H_ */ ddcutil-2.2.0/src/util/pnp_ids.h0000644000175000001440000000056214754576332012214 /** \file pnp_ids.h * * Provides a lookup table of 3 character manufacturer codes, * which are used, e.g. in EDIDs. */ // Copyright (C) 2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PNP_IDS_H_ #define PNP_IDS_H_ char * pnp_name(char * id); #ifdef TESTS void pnp_id_tests(); #endif #endif /* PNP_IDS_H_ */ ddcutil-2.2.0/src/util/subprocess_util.h0000644000175000001440000000200114754576332013773 /** @file subprocess_util.h * * Functions to execute shell commands */ // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SUBPROCESS_UTIL_H_ #define SUBPROCESS_UTIL_H_ /** \cond */ #include #include /** \endcond */ bool execute_shell_cmd( const char * shell_cmd); bool execute_shell_cmd_rpt( const char * shell_cmd, int depth); GPtrArray * execute_shell_cmd_collect( const char * shell_cmd); int execute_cmd_collect_with_filter( const char * shell_cmd, char ** filter_terms, bool ignore_case, int limit, GPtrArray ** result_loc); char * execute_shell_cmd_one_line_result(const char * shell_cmd); bool is_command_in_path( const char * cmd); int test_command_executability( const char * cmd); #endif /* SUBPROCESS_UTIL_H_ */ ddcutil-2.2.0/src/util/coredefs.h0000644000175000001440000000063614754576332012354 /** @file coredefs.h * Basic definitions that are not application specific */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef COREDEFS_H_ #define COREDEFS_H_ #include // for MIN() #include // for memcpy(), strlen() #include "coredefs_base.h" // shared with ddcui #endif /* COREDEFS_H_ */ ddcutil-2.2.0/src/util/i2c_util.h0000644000175000001440000000127214754576332012271 /** @file i2c_util.h * * I2C utility functions */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef I2C_UTIL_H_ #define I2C_UTIL_H_ #include int i2c_name_to_busno(const char * name); int extract_number_after_hyphen(const char * name); int i2c_compare(const void * v1, const void * v2); unsigned long i2c_get_functionality_flags_by_fd(int fd); char * i2c_interpret_functionality_flags(unsigned long functionality); void i2c_report_functionality_flags(long functionality, int maxline, int depth); bool dev_i2c_devices_exist(); #endif /* I2C_UTIL_H_ */ ddcutil-2.2.0/src/util/coredefs_base.h0000644000175000001440000000502314754576332013341 /** \file coredefs_base.h * Portion of coredefs.h shared with ddcui */ // Copyright (C) 2021-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef COREDEFS_BASE_H_ #define COREDEFS_BASE_H_ #include "config.h" // for TARGET_BSD, TARGET_LINUX #include // to check if EBUSY defined #ifndef EBUSY #define EBUSY 16 // not defined in at least EPEL 8, RHEL 8 (9/11/2023) #endif /** Raw byte */ typedef unsigned char Byte; #ifndef ARRAY_SIZE /** Number of entries in array */ #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif #ifndef ASSERT_IFF #define ASSERT_IFF(_cond1, _cond2) \ assert( ( (_cond1) && (_cond2) ) || ( !(_cond1) && !(_cond2) ) ) #endif /* gcc 8 introduced stringop- warnings: stringop-truncation, stringop-overflow, (more?) * These cause warnings for otherwise valid strncpy(), strncat(), g_strlcpy() code that * appears only when using gcc 8, not 7 or earlier. Writing code that compiles without * warnings everywhere, and in addition does not raise a Coverity defect * (e.g. access_dbuf_in_call) is difficult. See: * https://stackoverflow.com/questions/50198319/gcc-8-wstringop-truncation-what-is-the-good-practice * * Using: * #pragma GCC diagnostic ignored "-Wstringop-truncation" * suppresses the warning on GCC 8, but causes an unrecognized pragma error on gcc 7. * * Surrounding the strndup() expression in parentheses, as suggested in the stackoverflow * thread, works for gcc 7 and 8, but still triggers the Coverity Scan diagnostics, which * requires a coverity annotation, e.g. "converity[access_dbuf_in_call]"/ * * Using memcpy() avoids all the warnings, but has the drawback that STRLCPY(), unlike * strndup() etc., does not have a return value, so is not a drop-in replacement. * However, in practice, that return value is not used by callers. */ #define STRLCPY(_dst, _src, _size) \ do { \ memcpy(_dst, _src, MIN((_size)-1,strlen(_src))); \ _dst[ MIN((_size)-1,strlen(_src)) ] = '\0'; \ } while(0) #define STRLCAT(_dst, _src, _size) \ do { \ strncat(_dst, _src, (_size)-1); \ _dst[(_size)-1] = '\0'; \ } while(0) #define SETCLR_BIT(_flag_var, _bit, _onoff) \ do { \ if ( (_onoff) ) \ _flag_var |= _bit; \ else \ _flag_var &= ~_bit; \ } while(0) #define FREE(_ptr) \ do { \ if (_ptr) { \ free(_ptr); \ _ptr = NULL; \ } \ } while (0) #ifdef TARGET_BSD #define I2C "iic" #else #define I2C "i2c" #endif #endif /* COREDEFS_BASE_H_ */ ddcutil-2.2.0/src/util/device_id_util.h0000644000175000001440000000535314754576332013533 /* device_id_util.h * * * Copyright (C) 2014-2017 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ /** @file device_id_util.h * Lookup PCI and USB device ids */ #ifndef DEVICE_ID_UTIL_H_ #define DEVICE_ID_UTIL_H_ /** \cond */ #include #include #include #include /** \endcond */ // *** Initialization *** bool devid_ensure_initialized(); // *** Device ID lookup *** /** Return value for devid_get_pci_names() and devid_usb_names(). * Depending on the number of arguments to those functions, * device_name and subsys_or_interface_name may or may not be set. */ typedef struct { char * vendor_name; ///< vendor name char * device_name; ///< device name (may be NULL) char * subsys_or_interface_name; ///< subsystem or interface name (may be NULL) } Pci_Usb_Id_Names; Pci_Usb_Id_Names devid_get_pci_names( gushort vendor_id, gushort device_id, gushort subvendor_id, gushort subdevice_id, int argct); Pci_Usb_Id_Names devid_get_usb_names( gushort vendor_id, gushort device_id, gushort interface_id, int argct); // *** HID Descriptor Item Types *** // "item type" is the term used in usb.ids // "item tag" is the term used in USB HID documentation char * devid_hid_descriptor_item_type(gushort id); // R entry in usb.ids, corresponds to names_reporttag() // *** HID Descriptor Type *** // declared here but not defined // char * devid_hid_descriptor_type(gushort id); // HID entry in usb.ids // *** HUT table *** char * devid_usage_code_page_name(gushort usage_page_code); // corresponds to names_huts() char * devid_usage_code_id_name(gushort usage_page_code, gushort usage_simple_id); // corresponds to names_hutus() char * devid_usage_code_name_by_extended_id(uint32_t extended_usage); #endif /* DEVICE_ID_UTIL_H_ */ ddcutil-2.2.0/src/util/multi_level_map.h0000644000175000001440000000305414754576332013735 /** @file multi_level_map.h */ // Copyright (C) 2021-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** @file multi_level_map.h * Multi_Level_Map data structure */ #ifndef MULTI_LEVEL_TABLE_H_ #define MULTI_LEVEL_TABLE_H_ /** \cond */ #include /** \endcond */ #define MLT_MAX_LEVELS 4 typedef struct { int levels; char * names[MLT_MAX_LEVELS]; } Multi_Level_Names; typedef struct { int levels; guint ids[MLT_MAX_LEVELS]; } Multi_Level_Ids; typedef struct { gushort level; guint code; char * name; GPtrArray * children; } MLM_Node; /* Used to both describe a level in a **Multi_Level_Map** table, * /and maintain data about that level */ typedef struct { char * name; int initial_size; int total_entries; MLM_Node * cur_entry; } MLM_Level; void report_mlm_level(MLM_Level * level_desc, int depth); typedef struct { char* table_name; char* segment_tag; int levels; GPtrArray * root; MLM_Level level_detail[]; // MLM_Level * level_detail; } Multi_Level_Map; Multi_Level_Map * mlm_create(char * table_name, int levels, MLM_Level* level_detail); MLM_Node * mlm_add_node(Multi_Level_Map * mlm, MLM_Node * parent, guint key, char * value); void report_multi_level_map(Multi_Level_Map * mlm, int depth); Multi_Level_Names mlm_get_names(Multi_Level_Map * mlm, int argct, ...); Multi_Level_Names mlm_get_names2(Multi_Level_Map * mlm, int levelct, guint* ids); #endif /* MULTI_LEVEL_TABLE_H_ */ ddcutil-2.2.0/src/util/simple_ini_file.h0000644000175000001440000000177414754576332013715 /** \file simple_ini_file.h * * Reads an INI style configuration file */ // Copyright (C) 2021-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SIMPLE_INI_FILE_H_ #define SIMPLE_INI_FILE_H_ #ifdef __cplusplus extern "C" { #endif #include #include #include "error_info.h" #define PARSED_INI_FILE_MARKER "INIF" typedef struct { char marker[4]; char * config_fn; GHashTable * hash_table; } Parsed_Ini_File; int ini_file_load( const char * ini_filename, GPtrArray* errmsgs, Parsed_Ini_File** ini_file_loc); char * ini_file_get_value( Parsed_Ini_File * ini_file, const char * segment, const char * id); void ini_file_dump( Parsed_Ini_File * ini_file); void ini_file_free( Parsed_Ini_File * parsed_ini_file); #ifdef __cplusplus } // extern "C" #endif #endif /* SIMPLE_INI_FILE_H_ */ ddcutil-2.2.0/src/util/udev_usb_util.h0000644000175000001440000000626414754576332013436 /* udev_usb_util.h * * * Copyright (C) 2016-2021 Sanford Rockowitz * * Licensed under the GNU General Public License Version 2 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ /** \file * USB specific udev utility functions */ #ifndef UDEV_USB_UTIL_H_ #define UDEV_USB_UTIL_H_ /** \cond */ #include #include #include /** \endcond */ void probe_udev_subsystem(char * udev_class, bool show_usb_parent, int depth); #define UDEV_DETAILED_DEVICE_SUMMARY_MARKER "UDDS" /** Identifying information for UDEV device * * @remark * Currently (3/2017) used solely for informational messages, * so no need to convert from strings to integers. */ typedef struct { char marker[4]; ///< always "UDDS" char * devname; ///< e.g. /dev/usb/hiddev2 // int usb_busnum; // int usb_devnum; uint16_t vid; uint16_t pid; char * vendor_id; ///< vendor id, as 4 hex characters char * product_id; ///< product id, as 4 hex characters char * vendor_name; ///< vendor name char * product_name; ///< product name char * busnum_s; ///< bus number, as a string char * devnum_s; ///< device number, as a string // to collect, then reduce to what's needed: char * prop_busnum ; char * prop_devnum ; char * prop_model ; char * prop_model_id ; char * prop_usb_interfaces ; char * prop_vendor ; char * prop_vendor_from_database ; char * prop_vendor_id ; char * prop_major ; char * prop_minor ; } Usb_Detailed_Device_Summary; void free_usb_detailed_device_summary(Usb_Detailed_Device_Summary * devsum); void report_usb_detailed_device_summary(Usb_Detailed_Device_Summary * devsum, int depth); Usb_Detailed_Device_Summary * lookup_udev_usb_device_by_devname( const char * devname, bool verbose); /** USB bus number/device number pair */ typedef struct udev_usb_devinfo { uint16_t busno; ///< USB bus number uint16_t devno; ///< device number on USB bus } Udev_Usb_Devinfo; void report_udev_usb_devinfo(struct udev_usb_devinfo * dinfo, int depth); Udev_Usb_Devinfo * get_udev_usb_devinfo(char * subsystem, char * simple_devname); // Move function to hiddev utility library? /** Excapsulates location of hiddev device files, in case it needs to be generalized */ char * usb_hiddev_directory(); #endif /* UDEV_USB_UTIL_H_ */ ddcutil-2.2.0/src/util/xdg_util.h0000644000175000001440000000311214754576332012371 /** \file xdg_util.h * Implement XDG Base Directory Specification */ // Copyright (C) 2020-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef XDG_UTIL_H_ #define XDG_UTIL_H_ #ifdef __cplusplus extern "C" { #endif char * xdg_data_home_dir(); // $XDG_DATA_HOME or $HOME/.local/share char * xdg_config_home_dir(); // $XDG_CONFIG_HOME or $HOME/.config char * xdg_cache_home_dir(); // $XDG_CACHE_HOME or $HOME/.cache char * xdg_state_home_dir(); // $XDG_STATE_HOME or $HOME/.local/state char * xdg_data_dirs(); // $XDG_DATA_DIRS or /usr/local/share:/usr/share char * xdg_config_dirs(); // $XDG_CONFIG_DIRS or /etc/xdg char * xdg_data_path(); // XDG_DATA_HOME directory, followed by XDG_DATA_DIRS char * xdg_config_path(); // XDG_CONFIG_HOME directory, followed by XDG_CONFIG_DIRS char * xdg_data_home_file( const char * application, const char * simple_fn); char * xdg_config_home_file(const char * application, const char * simple_fn); char * xdg_cache_home_file( const char * application, const char * simple_fn); char * xdg_state_home_file( const char * application, const char * simple_fn); char * find_xdg_data_file( const char * application, const char * simple_fn); char * find_xdg_config_file(const char * application, const char * simple_fn); char * find_xdg_cache_file( const char * application, const char * simple_fn); char * find_xdg_state_file( const char * application, const char * simple_fn); void xdg_tests(); #ifdef __cplusplus } // extern "C" #endif #endif /* XDG_UTIL_H_ */ ddcutil-2.2.0/src/util/ddcutil_config_file.h0000644000175000001440000000177114754576332014537 /** @file ddcutil_config_file.h */ // Copyright (C) 2021-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DDCUTIL_CONFIG_FILE_H_ #define DDCUTIL_CONFIG_FILE_H_ #ifdef __cplusplus extern "C" { #endif #include #include "error_info.h" int tokenize_options_line( const char * string, char *** tokens_loc); int read_ddcutil_config_file( const char * ddcutil_application, char ** config_fn_loc, char ** untokenized_option_string_loc, GPtrArray * errmsgs); int apply_config_file( const char * ddcutil_application, // "ddcutil", "ddcui", "libddcutil" int old_argc, char ** old_argv, int * new_argc_loc, char *** new_argv_loc, char ** untokenized_option_string_loc, char ** configure_fn_loc, GPtrArray * errmsgs); #ifdef __cplusplus } // extern "C" #endif #endif /* DDCUTIL_CONFIG_FILE_H_ */ ddcutil-2.2.0/src/util/edid.h0000644000175000001440000000765514754576332011477 /** @file edid.h * * Functions for processing the Parsed_Edid data structure, irrespective of how * the bytes of the EDID are obtained. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef EDID_H_ #define EDID_H_ /** \cond */ #include #include #include #include #include // normally included by stdlib.h, but explicitly required for Alpine Linux /** \endcond */ #include "coredefs.h" // Field sizes for holding strings extracted from an EDID // Note that these are sized to allow for a trailing null character. #define EDID_MFG_ID_FIELD_SIZE 4 #define EDID_EXTRA_STRING_FIELD_SIZE 14 #define EDID_MODEL_NAME_FIELD_SIZE 14 #define EDID_SERIAL_ASCII_FIELD_SIZE 14 #define EDID_SOURCE_MAX_LEN 5 #define EDID_SOURCE_FIELD_SIZE 6 //Calculates checksum for a 128 byte EDID Byte edid_checksum(const Byte * edid); bool is_valid_edid_checksum(const Byte * edidbytes); bool is_valid_edid_header(const Byte * edidbytes); bool is_valid_raw_edid(const Byte * edidbytes, int len); bool is_valid_raw_cea861_extension_block(const Byte * edid, int len); void parse_mfg_id_in_buffer(const Byte * mfgIdBytes, char * buffer, int bufsize); void get_edid_mfg_id_in_buffer(const Byte* edidbytes, char * buffer, int bufsize); #define EDID_MARKER_NAME "EDID" /** Represents a parsed EDID */ typedef struct { char marker[4]; ///< always "EDID" Byte bytes[128]; ///< raw bytes of EDID char mfg_id[EDID_MFG_ID_FIELD_SIZE]; ///< 3 character mfg id, null terminated uint16_t product_code; ///< product code number char model_name[EDID_MODEL_NAME_FIELD_SIZE]; ///< model name (tag 0xfc) uint32_t serial_binary; ///< binary serial number char serial_ascii[EDID_SERIAL_ASCII_FIELD_SIZE]; ///< serial number string (tag 0xff) char extra_descriptor_string[EDID_EXTRA_STRING_FIELD_SIZE]; ///< (tag 0xfe) int year; ///< can be year of manufacture or model bool is_model_year; ///< true if year is model year, false if manufacture year uint8_t manufacture_week; ///< xFF if is_model_year == true Byte edid_version_major; ///< EDID major version number Byte edid_version_minor; ///< EDID minor version number uint16_t wx; ///< whitepoint x coordinate uint16_t wy; ///< whitepoint y coordinate uint16_t rx; ///< red x coordinate uint16_t ry; ///< red y coordinate uint16_t gx; ///< green x coordinate uint16_t gy; ///< green y coordinate uint16_t bx; ///< blue x coordinate uint16_t by; ///< blue y coordinate Byte video_input_definition; /// EDID byte 20 (x14) Byte supported_features; ///< EDID byte 24 (x18) supported features bitmap uint8_t extension_flag; ///< number of optional extension blocks char edid_source[EDID_SOURCE_FIELD_SIZE]; ///< describes source of EDID } Parsed_Edid; Parsed_Edid * create_parsed_edid(const Byte* edidbytes); Parsed_Edid * create_parsed_edid2(const Byte* edidbytes, const char * source); void report_parsed_edid_base(Parsed_Edid * edid, bool verbose_synopsis, bool show_raw, int depth); bool is_input_digital(Parsed_Edid * edid); void report_parsed_edid(Parsed_Edid * edid, bool verbose, int depth); Parsed_Edid * copy_parsed_edid(Parsed_Edid * original); void free_parsed_edid(Parsed_Edid * parsed_edid); bool is_laptop_parsed_edid(Parsed_Edid * parsed_edid); #endif /* EDID_H_ */ ddcutil-2.2.0/src/util/glib_string_util.h0000644000175000001440000000205514754576332014117 /** @file glib_string_util.h * * Functions that depend on both glib_util.c and string_util.c * * glib_string_util.c/h exist to avoid circular dependencies. */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include /** \endcond */ #ifndef GLIB_STRING_UTIL_H_ #define GLIB_STRING_UTIL_H_ char * join_string_g_ptr_array(GPtrArray* strings, char * sepstr); char * join_string_g_ptr_array_t(GPtrArray* strings, char * sepstr); char * join_string_g_ptr_array2(GPtrArray* strings, char * sepstr, bool sort); char * join_string_g_ptr_array2_t(GPtrArray* strings, char * sepstr, bool sort); int gaux_string_ptr_array_find(GPtrArray * haystack, const char * needle); bool gaux_unique_string_ptr_arrays_equal(GPtrArray *first, GPtrArray* second); GPtrArray * gaux_unique_string_ptr_arrays_minus(GPtrArray *first, GPtrArray* second); void gaux_unique_string_ptr_array_include(GPtrArray * arry, char * new_value); #endif /* GLIB_STRING_UTIL_H_ */ ddcutil-2.2.0/src/util/systemd_util.h0000644000175000001440000000052614754576332013305 /** @file systemd_util.h */ // Copyright (C) 2017-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSTEMD_UTIL_H_ #define SYSTEMD_UTIL_H_ #include GPtrArray * get_current_boot_messages(char ** filter_terms, bool ignore_case, int limit); #endif /* SYSTEMD_UTIL_H_ */ ddcutil-2.2.0/src/util/glib_util.h0000644000175000001440000000361014754576332012527 /** @file glib_util.h * * Utility functions for glib. */ // Copyright (C) 2014-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef GLIB_UTIL_H_ #define GLIB_UTIL_H_ /** \cond */ #include #include /** \endcond */ #ifdef __cplusplus extern "C" { #endif gpointer * g_list_to_g_array( GList * glist, guint * length); gint gaux_ptr_scomp( gconstpointer a, gconstpointer b); gint gaux_ptr_intcomp( gconstpointer a, gconstpointer b); void * get_thread_dynamic_buffer( GPrivate * buf_key_ptr, GPrivate * bufsz_key_ptr, guint16 required_size); void * get_thread_fixed_buffer( GPrivate * buf_key_ptr, guint16 required_size); GPtrArray * gaux_ptr_array_truncate( GPtrArray * gpa, int limit); // Future: typedef gpointer (*GAuxDupFunc)(gpointer src); GPtrArray * gaux_ptr_array_append_array( GPtrArray * dest, GPtrArray * src, GAuxDupFunc dup_func); GPtrArray * gaux_ptr_array_join( GPtrArray * gpa1, GPtrArray * gpa2, GAuxDupFunc dup_func, GDestroyNotify element_free_func); GPtrArray * gaux_ptr_array_copy( GPtrArray * src, GAuxDupFunc dup_func, GDestroyNotify element_free_func); GPtrArray * gaux_deep_copy_string_array( GPtrArray * old_names); GPtrArray * gaux_ptr_array_from_null_terminated_array( gpointer * src, GAuxDupFunc dup_func, GDestroyNotify element_free_func); gboolean gaux_streq( // alternative to g_str_equal(), has GEqualFunc signature gconstpointer a, gconstpointer b); gboolean gaux_ptr_array_find_with_equal_func( GPtrArray * haystack, gconstpointer needle, GEqualFunc equal_func, guint * index_); #ifdef __cplusplus } #endif #endif /* GLIB_UTIL_H_ */ ddcutil-2.2.0/src/util/udev_util.h0000644000175000001440000000254214754576332012560 /** @file udev_util.h * UDEV utility functions */ // Copyright (C) 2016-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef UDEV_UTIL_H_ #define UDEV_UTIL_H_ /** \cond */ #include #include #include /** \endcond */ #define UDEV_DEVICE_SUMMARY_MARKER "UDSM" /** Summary information for one UDEV device */ typedef struct udev_device_summary { char marker[4]; ///< always "UDSM" char * sysname; ///< e.g. i2c-3 char * devpath; ///< device path char * sysattr_name; ///< sysattr name char * subsystem; ///< subsystem, e.g. usbmisc } Udev_Device_Summary; void free_udev_device_summaries(GPtrArray* summaries); GPtrArray * summarize_udev_subsystem_devices(char * subsystem); GPtrArray * find_devices_by_sysattr_name(char * name); // Function returns true if keep, false if discard typedef bool (*Udev_Summary_Filter_Func)(Udev_Device_Summary * summary); GPtrArray * filter_device_summaries(GPtrArray * summaries, Udev_Summary_Filter_Func func); void report_udev_device(struct udev_device * dev, int depth); void show_udev_list_entries( struct udev_list_entry * entries, char * title); void show_sysattr_list_entries( struct udev_device * dev, struct udev_list_entry * head); #endif /* UDEV_UTIL_H_ */ ddcutil-2.2.0/src/util/failsim.h0000664000175000001440000000611414754576332012205 /** @file failsim.h * * Functions that provide a simple failure simulation framework. */ // Copyright (C) 2017-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef FAILSIM_H_ #define FAILSIM_H_ #include "config.h" /** \cond */ #include #include #include "error_info.h" /** \endcond */ // Issue: Where to send error messages? extern bool failsim_enabled; // // Initialization // typedef bool (*Fsim_Name_To_Number_Func)(const char * name, int * p_number); void fsim_set_name_to_number_funcs( Fsim_Name_To_Number_Func func, Fsim_Name_To_Number_Func unmodulated_func); /** Indicates whether a failure should occur exactly once or be recurring */ typedef enum {FSIM_CALL_OCC_RECURRING, FSIM_CALL_OCC_SINGLE} Fsim_Call_Occ_Type; // // Error table manipulation // void fsim_add_error( char * funcname, Fsim_Call_Occ_Type call_occ_type, int occno, int rc); void fsim_clear_errors_for_func(char * funcname); void fsim_clear_error_table(); void fsim_report_failure_simulation_table(int depth); void fsim_reset_callct(char * funcname); // // Bulk load error table // bool fsim_load_control_from_gptrarray(GPtrArray * lines, GPtrArray * err_msg_accumulator); // bool fsim_load_control_string(char * s); // unimplemented bool fsim_load_control_file(char * fn); // // Runtime error check // // int fsim_check_failure(const char * fn, const char * funcname); /* Return value for fsim_check_failure(). * Indicates whether a failure should be forced and if so the * simulated status code the function should return. */ typedef struct { bool force_failure; int failure_value; } Failsim_Result; Failsim_Result fsim_check_failure(const char * fn, const char * funcname); #ifdef UNUSED #ifdef ENABLE_FAILSIM #define FAILSIM \ do { \ Failsim_Result __rcsim = fsim_check_failure(__FILE__, __func__); \ if (__rcsim.force_failure) \ return __rcsim.failure_value; \ } while(0); #define FAILSIM_EXT(__addl_cmds) \ do { \ Failsim_Result __rcsim = fsim_check_failure(__FILE__, __func__); \ if (__rcsim.force_failure) { \ __addl_cmds; \ return __rcsim.failure_value; \ } \ } while(0); #else #define FAILSIM #define FAILSIM_EXT(__addl_cmds) #endif #endif bool fsim_bool_injector(bool status, const char * fn, const char * func); int fsim_int_injector(int status, const char * fn, const char * func); Error_Info* fsim_errinfo_injector(Error_Info* status, const char * fn, const char * func); #ifdef UNUSED #ifdef ENABLE_FAILSIM #define INJECT_BOOL_ERROR(status) fsim_bool_injector(status, __FILE__, __func__) #define INJECT_INT_ERROR(status) fsim_int_injector(status, __FILE__, __func__) #define INJECT_ERRINFO_ERROR(status) fsim_errinfo_injector(status, __FILE__, __func__) #else #define INJECT_BOOL_ERROR(status) status #define INJECT_INT_ERROR(status) status #define INJECT_ERRINFO_ERROR(status) status #endif #endif #endif /* FAILSIM_H_ */ ddcutil-2.2.0/src/util/backtrace.h0000644000175000001440000000065414754576332012501 /** @file backtrace.h */ // Copyright (C) 2016-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef BACKTRACE_H_ #define BACKTRACE_H_ #ifdef __cplusplus extern "C" { #endif #include GPtrArray * get_backtrace(int stack_adjust); void backtrace_to_syslog(int priority, int stack_adjust); #ifdef __cplusplus } // extern "C" #endif #endif /* BACKTRACE_H_ */ ddcutil-2.2.0/src/util/common_inlines.h0000644000175000001440000000140314754576332013564 /** @file common_inlines.h */ // Copyright (C) 2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef COMMON_INLINES_H_ #define COMMON_INLINES_H_ #ifdef __cplusplus extern "C" { #endif #include #include // TODO: merge tid(), pid() with linux_errno.c/h static inline pid_t tid() { static __thread pid_t thread_id2; if (!thread_id2) thread_id2 = syscall(SYS_gettid); return thread_id2; } #define TID() (intmax_t) tid() static inline pid_t pid() { static __thread pid_t process_id; if (!process_id) process_id = syscall(SYS_gettid); return process_id; } #define PID() (intmax_t) pid() #ifdef __cplusplus } // extern "C" #endif #endif /* COMMON_INLINES_H_ */ ddcutil-2.2.0/src/util/common_printf_formats.h0000644000175000001440000000042614754576332015164 /** @file common_printf_formats.h */ // Copyright (C) 2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef COMMON_PRINTF_FORMATS_H_ #define COMMON_PRINTF_FORMATS_H_ #define PRItid "[%6jd]" #endif /* COMMON_PRINTF_FORMATS_H_ */ ddcutil-2.2.0/src/util/data_structures.h0000644000175000001440000002151614754576332013776 /** @file data_structures.h * General purpose data structures */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DATA_STRUCTURES_H #define DATA_STRUCTURES_H #ifdef __cplusplus extern "C" { #endif /** \cond */ #include #include #include /** \endcond */ #include "coredefs_base.h" // for Byte #include "string_util.h" // // Buffer with length management // #define BUFFER_MARKER "BUFR" /** Buffer with length management */ typedef struct { char marker[4]; ///< always "BUFR" Byte * bytes; ///< pointer to internal buffer int buffer_size; ///< size of internal buffer int len; ///< number of bytes in buffer uint16_t size_increment; ///< if > 0, auto-extend increment } Buffer; Buffer * buffer_new(int size, const char * trace_msg); void buffer_set_size_increment(Buffer * buffer, uint16_t increment); Buffer * buffer_dup(Buffer * srcbuf, const char * trace_msg); Buffer * buffer_new_with_value(Byte * bytes, int bytect, const char * trace_msg); int buffer_length(Buffer * buffer); void buffer_set_length(Buffer * buffer, int bytect); void buffer_free(Buffer * buffer, const char * trace_msg); void buffer_put(Buffer * buffer, Byte * bytes, int bytect); void buffer_set_byte(Buffer * buffer, int offset, Byte byte); void buffer_set_bytes(Buffer * buffer, int offset, Byte * bytes, int bytect); void buffer_append(Buffer * buffer, Byte * bytes, int bytect); void buffer_strcat(Buffer * buffer, char * str); void buffer_add(Buffer * buffer, Byte byte); void buffer_dump(Buffer * buffer); void buffer_rpt(Buffer * buffer, int depth); bool buffer_eq(Buffer* buf1, Buffer* buf2); void buffer_extend(Buffer* buf, int addl_bytes); // // Circular String Buffer // typedef struct { char ** lines; int size; int ct; } Circular_String_Buffer; /** Allocates a new #Circular_String_Buffer * * @param size buffer size (number of entries) * @return newly allocated #Circular_String_Buffer */ Circular_String_Buffer * csb_new(int size); void csb_add(Circular_String_Buffer * csb, char * line, bool copy); GPtrArray * csb_to_g_ptr_array(Circular_String_Buffer * csb); void csb_free(Circular_String_Buffer * csb, bool free_strings); // // Identifier id to name and description lookup // /** \def VN(v) * Creates a Value_Name table entry by specifying its symbolic name. * * @param v symbolic name */ #define VN(v) {v,#v,NULL} /** \def VN_END * Terminating entry for a Value_Name table. */ #define VN_END {0xff,NULL,NULL} /** \def VNT(v,t) * Creates a Value_Name_Title table entry by specifying its symbolic name * and description * * @param v symbolic name * @param t symbol description */ #define VNT(v,t) {v,#v,t} /** Terminating entry for a Value_Name_Title table. */ #define VNT_END {0xff,NULL,NULL} /** A Value_Name_Title table is used to map byte values to their * symbolic names and description (title). * Each entry is a value/name/description triple.. * * The table is terminated by an entry whose name and description fields are NULL. */ typedef struct { uint32_t value; ///< value char * name; ///< symbolic name char * title; ///< value description } Value_Name_Title; typedef Value_Name_Title Value_Name_Title_Table[]; typedef Value_Name_Title Value_Name; typedef Value_Name_Title_Table Value_Name_Table; char * vnt_name( Value_Name_Title* table, uint32_t val); char * vnt_title(Value_Name_Title* table, uint32_t val); int32_t vnt_find_id( Value_Name_Title_Table table, const char * s, bool use_title, // if false, search by symbolic name, if true, search by title bool ignore_case, int32_t default_id); #define INTERPRET_VNT_FLAGS_BY_NAME false #define INTERPRET VNT_FLAGS_BY_TITLE true char * vnt_interpret_flags( uint32_t flags_val, Value_Name_Title_Table bitname_table, bool use_title, char * sepstr); char * vnt_interpret_flags_t( uint32_t flags_val, Value_Name_Title_Table bitname_table, bool use_title, char * sepstr); #define VN_INTERPRET_FLAGS(_flags_val, _bitname_table, _sepstr) \ vnt_interpret_flags(_flags_val, _bitname_table, false, _sepstr) #define VN_INTERPRET_FLAGS_T(_flags_val, _bitname_table, _sepstr) \ vnt_interpret_flags_t(_flags_val, _bitname_table, false, _sepstr) // // Byte Value Array // typedef bool *IFilter(int i); /** An opaque structure containing an array of bytes that * can grow dynamically. Note that the same byte value can * appear multiple times. */ typedef void * Byte_Value_Array; Byte_Value_Array bva_create(); void bva_free(Byte_Value_Array bva); void bva_sort(Byte_Value_Array bva); bool bva_sorted_eq(Byte_Value_Array bva1, Byte_Value_Array bva2); int bva_length(Byte_Value_Array bva); bool bva_contains(Byte_Value_Array bva, Byte item); Byte bva_get(Byte_Value_Array bva, guint ndx); void bva_append(Byte_Value_Array bva, Byte item); Byte * bva_bytes(Byte_Value_Array bva); Byte_Value_Array bva_filter(Byte_Value_Array bva, IFilter filter_func); char * bva_as_string(Byte_Value_Array bva, bool as_hex, char * sep); void bva_report(Byte_Value_Array ids, char * title); bool bva_store_bytehex_list(Byte_Value_Array bva, char * start, int len); // void test_value_array(); // for testing // // Bit_Set_256 // typedef struct { uint8_t bytes[32]; } Bit_Set_256; extern const Bit_Set_256 EMPTY_BIT_SET_256; bool bs256_eq(Bit_Set_256 set1, Bit_Set_256 set2); int bs256_count(Bit_Set_256 set); bool bs256_contains(Bit_Set_256 flags, uint8_t val); int bs256_first_bit_set(Bit_Set_256 bitset); Bit_Set_256 bs256_insert(Bit_Set_256 flags, uint8_t val); Bit_Set_256 bs256_remove(Bit_Set_256 flags, uint8_t val); Bit_Set_256 bs256_or(Bit_Set_256 set1, Bit_Set_256 set2); // union Bit_Set_256 bs256_and(Bit_Set_256 set1, Bit_Set_256 set2); // intersection Bit_Set_256 bs256_and_not(Bit_Set_256 set1, Bit_Set_256 set2); // subtract #define bs256_minus bs256_and_not void bs256_repr(Bit_Set_256 flags, char * buffer, int buflen); char * bs256_to_string_t(Bit_Set_256 set, const char * value_prefix, const char * septr); // provides for bbf_to_string() char * bs256_to_string_decimal_t(Bit_Set_256 set, const char * value_prefix, const char * septr); Bit_Set_256 bs256_from_string(char * unparsed_string, Null_Terminated_String_Array * error_msgs_loc); Bit_Set_256 bs256_from_bva(Byte_Value_Array bva); int bs256_to_bytes(Bit_Set_256 flags, Byte * buffer, int buflen); Buffer * bs256_to_buffer(Bit_Set_256 flags); /** Opaque iterator for Bit_Set_256 */ typedef void * Bit_Set_256_Iterator; Bit_Set_256_Iterator bs256_iter_new(Bit_Set_256 bs256lags); void bs256_iter_free( Bit_Set_256_Iterator iter); void bs256_iter_reset(Bit_Set_256_Iterator iter); int bs256_iter_next( Bit_Set_256_Iterator iter); // defines to make use a little less verbose #define BS256 Bit_Set_256 #define BS256_REPR(_bs) bs256_to_string_decimal_t(_bs, "", ",") // // Bit_Set_32 // typedef uint32_t Bit_Set_32; extern const Bit_Set_32 EMPTY_BIT_SET_32; extern const int BIT_SET_32_MAX; int bs32_count(Bit_Set_32 set); bool bs32_contains(Bit_Set_32 flags, uint8_t val); Bit_Set_32 bs32_insert(Bit_Set_32 flags, uint8_t val); char* bs32_to_bitstring(Bit_Set_32 val, char * buf, int bufsz); char* bs32_to_string(Bit_Set_32 bitset, const char* value_prefix, const char* sepstr); char* bs32_to_string_decimal(Bit_Set_32 bitset, const char* value_prefix, const char* sepstr); // // Byte_Value_Array <-> Bit_Set_256 cross-compatibility functions // bool bva_bs256_same_values( Byte_Value_Array bva , Bit_Set_256 bs256); Bit_Set_256 bva_to_bs256(Byte_Value_Array bva); /** Function signature for passing function that appends a value to * either a #Byte_Bit_Flags or a #Byte_Value_Array */ typedef void (*Byte_Appender) (void * data_struct, Byte val); void bva_appender(void * data_struct, Byte val); void bs256_appender(void * data_struct, Byte val); // Store a value in either a Byte_Value_Array or a Byte_Bit_Flag bool store_bytehex_list(char * start, int len, void * data_struct, Byte_Appender appender); // // Callback registration // void generic_register_callback(GPtrArray** registered_callbacks_loc, void * func); bool generic_unregister_callback(GPtrArray* registered_callbacks, void *func); #ifdef __cplusplus } // extern "C" #endif #endif /* DATA_STRUCTURES_H */ ddcutil-2.2.0/src/util/debug_util.h0000644000175000001440000000225314754576332012702 /** @file debug_util.h * * Functions for debugging */ // Copyright (C) 2016-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DEBUG_UTIL_H_ #define DEBUG_UTIL_H_ #ifdef __cplusplus extern "C" { #endif #include #include #include "backtrace.h" // so existing code doesn't need to include #define ASSERT_WITH_BACKTRACE(_condition) \ do { \ if ( !(_condition) ) { \ show_backtrace(0); \ assert(_condition); \ } \ } while(0) void show_backtrace(int stack_adjust); void set_simple_dbgmsg_min_funcname_size(int new_size); bool simple_dbgmsg( bool debug_flag, const char * funcname, const int lineno, const char * filename, const char * format, ...); #define DBGF(debug_flag, format, ...) \ do { if (debug_flag) simple_dbgmsg(debug_flag, __func__, __LINE__, __FILE__, format, ##__VA_ARGS__); } while(0) #define DBG(format, ...) \ simple_dbgmsg(true, __func__, __LINE__, __FILE__, format, ##__VA_ARGS__) #ifdef __cplusplus } // extern "C" #endif #endif /* DEBUG_UTIL_H_ */ ddcutil-2.2.0/src/util/drm_common.h0000644000175000001440000000322514754576332012711 /** @file drm_common.h */ // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef DRM_COMMON_H_ #define DRM_COMMON_H_ /** \cond */ #include #include #include #include "data_structures.h" /** \endcond */ #ifdef UNUSED Bit_Set_32 get_sysfs_drm_card_numbers(); #endif const char * drm_bus_type_name(uint8_t bus); bool check_drm_supported_using_drm_api(char * busid2); bool adapter_supports_drm_using_drm_api(const char * adapter_path); bool all_displays_drm_using_drm_api(); bool check_video_adapters_list_implements_drm(GPtrArray * adapter_devices); bool check_all_video_adapters_implement_drm(); GPtrArray * get_dri_device_names_using_filesys(); bool all_video_adapters_support_drm_using_drm_api(GPtrArray * adapter_paths); extern Value_Name_Title_Table drm_connector_type_table; char * drm_connector_type_name(Byte val); char * drm_connector_type_title(Byte val); typedef struct { int cardno; int connector_id; int connector_type; int connector_type_id; } Drm_Connector_Identifier; char * dci_repr(Drm_Connector_Identifier dci); char * dci_repr_t(Drm_Connector_Identifier dci); bool dci_eq(Drm_Connector_Identifier dci1, Drm_Connector_Identifier dci2); int dci_cmp(Drm_Connector_Identifier dci1, Drm_Connector_Identifier dci2); int sys_drm_connector_name_cmp0(const char * s1, const char * s2); int sys_drm_connector_name_cmp(gconstpointer connector_name1, gconstpointer connector_name2); Drm_Connector_Identifier parse_sys_drm_connector_name(const char * drm_connector); #endif /* DRM_COMMON_H_ */ ddcutil-2.2.0/src/util/error_info.h0000644000175000001440000001005214754576332012717 /** \f error_info.h * * Struct for reporting errors that collects causes * * #Error_Info provides a pseudo-exception framework that can be integrated * with more traditional status codes. Instead of returning a status code, * a C function returns a pointer to an #Error_Info instance in the case of * an error, or NULL if there is no error. Information about the cause of an * error is retained for use by higher levels in the call stack. */ // Copyright (C) 2017-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef ERROR_INFO_H_ #define ERROR_INFO_H_ #ifdef __cplusplus extern "C" { #endif #include #include #define ERRINFO_STATUS(_erec) ( (_erec) ? _erec->status_code : 0 ) #define ERROR_INFO_MARKER "EINF" /** Struct for reporting errors, designed for collecting contributing errors */ typedef struct error_info { char marker[4]; ///< always EINF int status_code; ///< status code char * func; ///< name of function generating status code char * detail; ///< explanation (may be NULL) int max_causes; ///< max number entries in array currently pointed to by **causes** int cause_ct; ///< number of causal errors struct error_info ** causes; ///< pointer to array of pointers to Error_Info #ifdef ALT GPtrArray * causes_alt; // GPointerArray of Ddc_Error * #endif } Error_Info; typedef char * (*ErrInfo_Status_String)(int code); bool errinfo_all_causes_same_status( Error_Info * ddc_excp, int status_code); void errinfo_init( ErrInfo_Status_String name_func, ErrInfo_Status_String desc_func); void errinfo_free( Error_Info * erec); #define ERRINFO_FREE(_erec) \ if (_erec) \ errinfo_free(_erec); void errinfo_free_with_report( Error_Info * erec, bool report, const char * func); #define ERRINFO_FREE_WITH_REPORT(_erec, _report) \ if (_erec) \ errinfo_free_with_report(_erec, (_report), __func__) Error_Info * errinfo_new( int status_code, const char * func, const char * detail, ...); Error_Info * errinfo_copy(Error_Info* old); #define ERRINFO_NEW(_status_code, _detail, ...) \ errinfo_new(_status_code, __func__, _detail, ##__VA_ARGS__) Error_Info * errinfo_new_with_cause( int status_code, Error_Info * cause, const char * func, const char * detail_fmt, ...); #ifdef UNUSED Error_Info * errinfo_new_chained( Error_Info * cause, const char * func); #endif Error_Info * errinfo_new_with_causes( int status_code, Error_Info ** causes, int cause_ct, const char * func, char * detail, ...); Error_Info * errinfo_new_with_causes_gptr( int status_code, GPtrArray* causes, const char * func, char * detail, ...); #ifdef UNUSED Error_Info * errinfo_new_with_callee_status_codes( int status_code, int * callee_status_codes, int callee_status_code_ct, const char * callee_func, const char * func); #endif void errinfo_add_cause( Error_Info * erec, Error_Info * cause); void errinfo_set_status( Error_Info * erec, int rc); void errinfo_set_detail( Error_Info * erec, const char * detail_fmt, ...); char * errinfo_array_summary( Error_Info ** errors, int error_ct); char * errinfo_causes_string( Error_Info * erec); void errinfo_report_collect( Error_Info * erec, GPtrArray * collector, int depth); void errinfo_report( Error_Info * erec, int depth); void errinfo_report_details(Error_Info * erec, int depth); char * errinfo_summary( Error_Info * erec); #ifdef __cplusplus } // extern "C" #endif #endif /* ERROR_INFO_H_ */ ddcutil-2.2.0/src/util/file_util.h0000644000175000001440000001054214754576332012533 /** \file file_util.h * File utility functions */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef FILE_UTIL_H_ #define FILE_UTIL_H_ /** \cond */ #include #include #include #include /** \endcond */ #include "error_info.h" #include "file_util_base.h" Error_Info * file_getlines_errinfo( const char * filename, GPtrArray * lines); char * file_get_first_line( const char * fn, bool verbose); int file_get_last_lines( const char * fn, int maxlines, GPtrArray** line_array_loc, bool verbose); GByteArray * read_binary_file( const char * fn, int est_size, bool verbose); char * read_file_single_string( const char * filename, bool verbose); bool any_file_exists( const char * fqfn); bool regular_file_exists( const char * fqfn); bool directory_exists( const char * fqfn); /** Signature of Filter function for get_filenames_by_filter() */ typedef int (*Dirent_Filter)( const struct dirent *end); GPtrArray * get_filenames_by_filter( const char * dirnames[], Dirent_Filter filter_func); int filename_for_fd( int fd, char** fn_loc); char * filename_for_fd_t( int fd); /** Signature of filename filter function passed to #dir_foreach(). */ typedef bool (*Filename_Filter_Func)( const char * simple_fn); typedef bool (*Filename_Filter_Func_With_Arg)( const char * simple_fn, const char * arg); /** Signature of the filter function passed to #dir_ordered_foreach, * #dir_filtered_ordered_foreach */ typedef bool (*Dir_Filter_Func) ( const char * dirname, const char * simple_fn); /** Signature of function called by #dir_foreach to process each file. */ typedef void (*Dir_Foreach_Func)( const char * dirname, const char * fn, void * accumulator, int depth); void dir_foreach( const char * dirname, Filename_Filter_Func fn_filter, Dir_Foreach_Func func, void * accumulator, int depth); void dir_ordered_foreach( const char * dirname, Filename_Filter_Func fn_filter, GCompareFunc compare_func, Dir_Foreach_Func func, void * accumulator, int depth); void dir_ordered_foreach_with_arg( const char * dirname, Filename_Filter_Func_With_Arg fn_filter, const char * fn_filter_arg, GCompareFunc compare_func, Dir_Foreach_Func func, void * accumulator, int depth); void dir_filtered_ordered_foreach( const char * dirname, Dir_Filter_Func dir_filter, GCompareFunc compare_func, Dir_Foreach_Func func, void * accumulator, int depth); /** Signature of function called by #dir_foreach_terminatable to process each file. */ typedef bool (*Terminating_Dir_Foreach_Func)( const char * dirname, const char * fn, void * accumulator, int depth); void dir_foreach_terminatable( const char * dirname, Filename_Filter_Func fn_filter, Terminating_Dir_Foreach_Func func, void * accumulator, int depth); void filter_and_limit_g_ptr_array( GPtrArray * line_array, char ** filter_terms, bool ignore_case, int limit, bool free_strings); void filter_and_limit_g_ptr_array2( GPtrArray * line_array, char ** filter_terms, bool ignore_case, int limit); int read_file_with_filter( GPtrArray * line_array, const char * fn, char ** filter_terms, bool ignore_case, int limit, bool free_strings); int rek_mkdir( const char * path, FILE * ferr); int fopen_mkdir( const char * path, const char * mode, FILE * ferr, FILE ** fp_loc); long get_inode_by_fn(const char * fqfn); long get_inode_by_fd(int fd); #endif /* FILE_UTIL_H_ */ ddcutil-2.2.0/src/util/libdrm_util.h0000644000175000001440000000206314754576332013064 /** @file libdrm_util.h * Utilities for use with libdrm */ // Copyright (C) 2017-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef LIBDRM_UTIL_H_ #define LIBDRM_UTIL_H_ /** \cond */ #include #include #include /** \endcond */ char * drm_connector_type_name( Byte val); char * drm_connector_type_title(Byte val); char * connector_status_name( drmModeConnection val); char * connector_status_title(drmModeConnection val); char * encoder_type_title(uint32_t encoder_type); void report_drmModeRes( drmModeResPtr res, int depth); void report_drmModePropertyBlob( drmModePropertyBlobPtr blob_ptr, int depth); void report_drmModeConnector( int fd, drmModeConnector * p, int depth); void report_drm_modeProperty( drmModePropertyRes * p, int depth); void summarize_drm_modeProperty(drmModePropertyRes * p, int depth); void report_property_value(int fd, drmModePropertyPtr prop_ptr, uint64_t prop_value, int depth) ; #endif /* LIBDRM_UTIL_H_ */ ddcutil-2.2.0/src/util/linux_util.h0000644000175000001440000000171414754576332012754 /** \file linux_util.h * Miscellaneous Linux utilities */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef LINUX_UTIL_H_ #define LINUX_UTIL_H_ #include #include #include int get_kernel_config_parm(const char * parm_name, char * buffer, int bufsz); bool is_module_built_in(const char * module_name); #define KERNEL_MODULE_NOT_FOUND 0 // not found #define KERNEL_MODULE_BUILTIN 1 // module is built into kernel #define KERNEL_MODULE_LOADABLE_FILE 2 // module is a loadable file int module_status_by_modules_builtin_or_existence(const char * module_name); bool is_module_loadable(const char * module_name); intmax_t get_thread_id(); intmax_t get_process_id(); bool is_valid_thread_or_process(pid_t id); void rpt_lsof(const char * fqfn, int depth); GPtrArray* rpt_lsof_collect(const char * fqfn); #endif /* LINUX_UTIL_H_ */ ddcutil-2.2.0/src/util/msg_util.h0000644000175000001440000000157614754576332012411 /** @file msg_util.h */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef MSG_UTIL_H_ #define MSG_UTIL_H_ #ifdef __cplusplus extern "C" { #endif #include #include extern bool dbgtrc_show_time; // prefix debug/trace messages with elapsed time extern bool dbgtrc_show_wall_time; // prefix debug/trace messages with wall time extern bool dbgtrc_show_thread_id; // prefix debug/trace messages with thread id extern bool dbgtrc_show_process_id; // prefix debug/trace messages with process id extern bool dbgtrc_trace_to_syslog_only; extern bool stdout_stderr_redirected; extern __thread bool msg_decoration_suspended; char* get_msg_decoration(char * buf, uint bufsize, bool dest_syslog); char* formatted_wall_time(); #ifdef __cplusplus } #endif #endif /* MSG_UTIL_H_ */ ddcutil-2.2.0/src/util/regex_util.h0000644000175000001440000000075714754576332012735 // regex_util.h // Copyright (C) 2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef REGEX_UTIL_H_ #define REGEX_UTIL_H_ #include #include void free_regex_hash_table(); bool compile_and_eval_regex(const char * pattern, const char * value); bool compile_and_eval_regex_with_matches( const char * pattern, const char * value, size_t max_matches, regmatch_t * pm); #endif /* REGEX_UTIL_H_ */ ddcutil-2.2.0/src/util/report_util.h0000644000175000001440000000655014754576332013133 /** @file report_util.h * * Report utility package */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef REPORT_UTIL_H_ #define REPORT_UTIL_H_ #ifdef __cplusplus extern "C" { #endif /** \cond */ #include #include #include /** \endcond */ #include "coredefs_base.h" #include "string_util.h" #ifdef PERHAPS #define RPT_PREFIX_NONE 0x00 #define RPT_PREFIX_PID 0x01 #define RPT_PREFIX_TID 0x02 #define RPT_PREFIX_TS 0x04 #define RPT_PREFIX_WTD 0x08 extern __thread Byte rpt_prefix_options; #endif // If set, report messages are written to the system log, not the terminal extern bool redirect_reports_to_syslog; // If set, report messages have a letter tag appended, as a debugging aid // for identifying message source location. extern bool tag_output; void rpt_set_default_ornamentation_enabled(bool onoff); bool rpt_get_ornamentation_enabled(); bool rpt_set_ornamentation_enabled(bool enabled); void rpt_set_default_output_dest(FILE* output_dest); void rpt_push_output_dest(FILE* new_dest); void rpt_pop_output_dest(); FILE * rpt_cur_output_dest(); void rpt_reset_output_dest_stack(); void rpt_change_output_dest(FILE* new_dest); void rpt_debug_output_dest(); int rpt_get_indent(int depth); void rpt_flush(); void rpt_nl(); void rpt_title(const char * title, int depth); void rpt_label(int depth, const char * text); void rpt_label_collect(int depth, GPtrArray* collector, const char * text); void rpt_multiline(int depth, ...); void rpt_g_ptr_array(int depth, GPtrArray * strings); void rpt_vstring(int depth, char * format, ...) ; void rpt_vstring_collect(int depth, GPtrArray* collector, char * format, ...); void rpt_2col(char * s1, char * s2, int col2offset, bool offset_absolute, int depth); void rpt_structure_loc(const char * name, const void * ptr, int depth); void rpt_hex_dump(const Byte * data, int size, int depth); void rpt_ntsa(Null_Terminated_String_Array ntsa, int depth); int rpt_file_contents(const char * fn, bool verbose, int depth); // Remaining rpt_ functions share common formatting void rpt_str(const char * name, char * info, const char * val, int depth); void rpt_int(char * name, char * info, int val, int depth); void rpt_unsigned(char * name, char * info, int val, int depth); void rpt_bool(char * name, char * info, bool val, int depth); /** Interpretation function used by rpt_mapped_int() */ typedef char * (*Value_To_Name_Function)(int val); void rpt_mapped_int(char * name, char * info, int val, Value_To_Name_Function func, int depth); void rpt_int_as_hex(char * name, char * info, int val, int depth); void rpt_uint8_as_hex(char * name, char * info, unsigned char val, int depth) ; void rpt_bytes_as_hex(const char * name, char * info, Byte * bytes, int ct, bool hex_prefix_flag, int depth); typedef struct { char * flag_name; char * flag_info; int flag_val; } Flag_Info; typedef struct { int flag_info_ct; Flag_Info * flag_info_recs; } Flag_Dictionary; typedef struct { int flag_name_ct; char ** flag_names; } Flag_Name_Set; void rpt_ifval2(char * name, char * info, int val, Flag_Name_Set * pflagNameSet, Flag_Dictionary * pDict, int depth); #ifdef __cplusplus } // extern "C" #endif #endif /* REPORT_UTIL_H_ */ ddcutil-2.2.0/src/util/string_util.h0000644000175000001440000001367414754576332013133 /** @file string_util.h * String utility functions header file */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef STRING_UTIL_H_ #define STRING_UTIL_H_ /** \cond */ #include #include #include #include /** \endcond */ #include "coredefs_base.h" #include "glib_util.h" #ifdef __cplusplus extern "C" { #endif // // General // static inline const char * sbool(uint64_t val) { return (val) ? "true" : "false"; } // A macro alternative to sbool() #define SBOOL(val) ( (val) ? "true" : "false" ) // // String functions (other than hex) // bool streq(const char * s1, const char * s2); bool is_abbrev(const char * value, const char * longname, size_t minchars); bool str_starts_with(const char * value_to_test, const char * start_part); bool str_ends_with(const char * value_to_test, const char * end_part); int str_contains(const char * value_to_test, const char * segment); bool str_all_printable(const char * s); void strupper(char * s); void strlower(char * s); char * strdup_uc(const char* s); char * strjoin( const char ** pieces, const int ct, const char * sepstr); char * chars_to_string(const char * start, int len); char * strtrim(const char * s); char * strtrim_r(const char * s, char * buffer, int bufsz); char * ltrim_in_place(char * s); char * rtrim_in_place(char * s); char * trim_in_place(char * s); char * substr(const char * s, size_t startpos, size_t ct); char * lsub(const char * s, size_t ct); char * str_replace_char(char * s, char old_char, char new_char); char * strcat_new(char * s1, char * s2); bool sbuf_append(char * buf, int bufsz, char * sepstr, char * nextval); char * ascii_strcasestr(const char * haystack, const char * needle); int indirect_strcmp(const void * a, const void * b); typedef bool (*String_Comp_Func)(const char * a, const char * b); int matches_by_func( const char * word, const char ** match_list, String_Comp_Func comp_func); int exactly_matches_any(const char * word, const char ** match_list); int starts_with_any( const char * word, const char ** match_list); char * int_array_to_string(uint16_t * start, int ct); /** pointer to null-terminated array of strings */ typedef char** Null_Terminated_String_Array; // equivalent to GStrv void ntsa_free( Null_Terminated_String_Array string_array, bool free_strings); int ntsa_length(Null_Terminated_String_Array string_array); void ntsa_show( Null_Terminated_String_Array string_array); int ntsa_findx( Null_Terminated_String_Array string_array, const char * value, String_Comp_Func func); int ntsa_find( Null_Terminated_String_Array string_array, const char * value); Null_Terminated_String_Array ntsa_join( Null_Terminated_String_Array a1, Null_Terminated_String_Array a2, bool dup); Null_Terminated_String_Array ntsa_copy(Null_Terminated_String_Array a1, bool dup); Null_Terminated_String_Array ntsa_prepend(char * value, Null_Terminated_String_Array string_array, bool dup); Null_Terminated_String_Array ntsa_create_empty_array(); Null_Terminated_String_Array strsplit(const char * str_to_split, const char* delims); Null_Terminated_String_Array strsplit_maxlength( const char * str_to_split, uint16_t max_piece_length, const char * delims); GPtrArray * ntsa_to_g_ptr_array(Null_Terminated_String_Array ntsa); Null_Terminated_String_Array g_ptr_array_to_ntsa(GPtrArray * garray, bool duplicate); // // Numeric conversion // bool str_to_long( const char * sval, long * p_ival, int base); bool str_to_int( const char * sval, int * p_ival, int base); bool str_to_float(const char * sval, float * p_fval); // // Hex value conversion. // char * canonicalize_possible_hex_value(char * string_value); bool hhs_to_byte_in_buf(const char * s, Byte * result); // converts null terminated string into buffer bool any_one_byte_hex_string_to_byte_in_buf(const char * s, Byte * result); bool hhc_to_byte_in_buf(const char * hh, Byte * result); // converts 2 characters at hh into buffer int hhs_to_byte_array(const char * hhs, Byte** ba_loc); bool hhs4_to_uint16(char * hhs4, uint16_t* result); char * hexstring(const Byte * bytes, int size); // buffer returned must be freed char * hexstring_t( const unsigned char * bytes, int len); char * hexstring2( const unsigned char * bytes, // bytes to convert int len, // number of bytes const char * sepstr, // separator string between hex digits bool uppercase, // use upper case hex characters char * buffer, // buffer in which to return hex string size_t bufsz); // buffer size char * hexstring3_t( const unsigned char * bytes, // bytes to convert int len, // number of bytes const char * sepstr, // separator string between hex digits uint8_t hunk_size, // separator string frequency bool uppercase); // use upper case hex characters void hex_dump_indented_collect(GPtrArray * collector, const Byte* data, int size, int indents); void fhex_dump_indented(FILE * fh, const Byte* data, int size, int indents); void fhex_dump( FILE * fh, const Byte* bytes, int size); void hex_dump( const Byte* bytes, int size); // // Standard function variants that handle stream == NULL // int f0putc(int c, FILE * stream); int f0puts(const char * s, FILE * stream); int f0printf( FILE * stream, const char * format, ...); int vf0printf(FILE * stream, const char * format, va_list ap); // // Miscellaneous // bool all_bytes_zero(Byte * bytes, int bytect); bool apply_filter_terms(const char * text, char ** terms, bool ignore_case); #ifdef __cplusplus } #endif #endif /* STRING_UTIL_H_ */ ddcutil-2.2.0/src/util/sysfs_filter_functions.h0000644000175000001440000000262414754576332015365 /** \f sysfs_filter_functions.h */ //// Copyright (C) 2021-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_FILTER_FUNCTIONS_H_ #define SYSFS_FILTER_FUNCTIONS_H_ #include #include "data_structures.h" // Filename_Filter_Func bool predicate_cardN( const char * value); bool predicate_cardN_connector(const char * value); bool predicate_i2c_N( const char * value); bool predicate_any_D_00hh( const char * value); // Filename_Filter_Func_With_Arg bool fn_equal( const char * filename, const char * val); bool fn_starts_with( const char * filename, const char * val); bool predicate_exact_D_00hh(const char * value, const char * sbusno); // Dir_Filter_Func bool is_drm_connector( const char * dirname, const char * simple_fn); bool is_i2cN_dir( const char * dirname, const char * fn_ignored); // for e.g. dirname i2c-3 bool is_drm_dp_aux_subdir( const char * dirname, const char * val); bool is_card_connector_dir(const char * dirname, const char * simple_fn); // for e.g. card0-DP-1 bool is_cardN_dir( const char * dirname, const char * simple_fn); // for e.g. card0 bool has_class_display_or_docking_station(const char * dirname, const char * simple_fn); bool has_class_display( const char * dirname, const char * simple_fn); #endif /* SYSFS_FILTER_FUNCTIONS_H_ */ ddcutil-2.2.0/src/util/sysfs_i2c_util.h0000644000175000001440000000065614754576332013525 /** @file sysfs_i2c_util.h * i2c specific /sys functions */ // Copyright (C) 2020-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_I2C_UTIL_H_ #define SYSFS_I2C_UTIL_H_ #include #include "data_structures.h" bool is_module_loaded_using_sysfs( const char * module_name); GPtrArray * get_video_adapter_devices(); #endif /* SYSFS_I2C_UTIL_H_ */ ddcutil-2.2.0/src/util/sysfs_util.h0000644000175000001440000001006714754576332012765 /** \file sysfs_util.h * Functions for reading /sys file system */ // Copyright (C) 2016-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef SYSFS_UTIL_H_ #define SYSFS_UTIL_H_ #include "config.h" #include #include char * read_sysfs_attr( const char * dirname, const char * attrname, bool verbose); char * read_sysfs_attr_w_default( const char * dirname, const char * attrname, const char * default_value, bool verbose); char * read_sysfs_attr_w_default_r( const char * dirname, const char * attrname, const char * default_value, char * buf, unsigned bufsz, bool verbose); GByteArray * read_binary_sysfs_attr( const char * dirname, const char * attrname, int est_size, bool verbose); char * get_rpath_basename( const char * path); bool set_rpt_sysfs_attr_silent(bool silent); void rpt_attr_output( int depth, const char * node, const char * op, const char * value); bool rpt_attr_text( int depth, char ** value_loc, const char * fn_segment, ...); #define RPT_ATTR_TEXT(depth, value_loc, fn_segment, ...) \ rpt_attr_text(depth, value_loc, fn_segment, ##__VA_ARGS__, NULL) #define GET_ATTR_TEXT(value_loc, fn_segment, ...) \ rpt_attr_text(-1, value_loc, fn_segment, ##__VA_ARGS__, NULL) bool rpt_attr_int( int depth, int * value_loc, const char * fn_segment, ...); #define RPT_ATTR_INT(depth, value_loc, fn_segment, ...) \ rpt_attr_int(depth, value_loc, fn_segment, ##__VA_ARGS__, NULL) #define GET_ATTR_INT(value_loc, fn_segment, ...) \ rpt_attr_int(-1, value_loc, fn_segment, ##__VA_ARGS__, NULL) bool rpt_attr_binary( int depth, GByteArray ** value_loc, const char * fn_segment, ...); bool rpt_attr_edid( int depth, GByteArray ** value_loc, const char * fn_segment, ...); #define RPT_ATTR_EDID(depth, value_loc, fn_segment, ...) \ rpt_attr_edid(depth, value_loc, fn_segment, ##__VA_ARGS__, NULL) #define GET_ATTR_EDID(value_loc, fn_segment, ...) \ rpt_attr_edid(-1, value_loc, fn_segment, ##__VA_ARGS__, NULL) bool rpt_attr_realpath( int depth, char ** value_loc, const char * fn_segment, ...); #define RPT_ATTR_REALPATH(depth, value_loc, fn_segment, ...) \ rpt_attr_realpath(depth, value_loc, fn_segment, ##__VA_ARGS__, NULL) #define GET_ATTR_REALPATH(value_loc, fn_segment, ...) \ rpt_attr_realpath(-1, value_loc, fn_segment, ##__VA_ARGS__, NULL) bool rpt_attr_realpath_basename( int depth, char ** value_loc, const char * fn_segment, ...); #define RPT_ATTR_REALPATH_BASENAME(depth, value_loc, fn_segment, ...) \ rpt_attr_realpath_basename(depth, value_loc, fn_segment, ##__VA_ARGS__, NULL) #define GET_ATTR_REALPATH_BASENAME(value_loc, fn_segment, ...) \ rpt_attr_realpath_basename(-1, value_loc, fn_segment, ##__VA_ARGS__, NULL) typedef bool (*Fn_Filter)(const char * fn, const char * val); bool rpt_attr_single_subdir( int depth, char ** value_loc, Fn_Filter predicate_function, const char * predicate_value, const char * fn_segment, ...); #define RPT_ATTR_SINGLE_SUBDIR(depth, value_loc, predicate_func, predicate_val, fn_segment, ...) \ rpt_attr_single_subdir(depth, value_loc, predicate_func, predicate_val, fn_segment, ##__VA_ARGS__, NULL) #define GET_ATTR_SINGLE_SUBDIR(value_loc, predicate_func, predicate_val, fn_segment, ...) \ rpt_attr_single_subdir(-1, value_loc, predicate_func, predicate_val, fn_segment, ##__VA_ARGS__, NULL) bool rpt_attr_note_subdir( int depth, char ** value_loc, const char * fn_segment, ...); #define RPT_ATTR_NOTE_SUBDIR(depth, value_loc, fn_segment, ...) \ rpt_attr_note_subdir(depth, value_loc, fn_segment, ##__VA_ARGS__, NULL) #endif /* SYSFS_UTIL_H_ */ ddcutil-2.2.0/src/util/timestamp.h0000644000175000001440000000205414754576332012561 /** @file timestamp.h * * Timestamp management */ // Copyright (C) 2014-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef TIMESTAMP_H_ #define TIMESTAMP_H_ #ifdef __cplusplus extern "C" { #endif /** \cond */ #include /** \endcond */ // // Timestamp Generation // uint64_t cur_realtime_nanosec(); // Returns the current value of the realtime clock in nanoseconds void show_timestamp_history(); // For debugging uint64_t elapsed_time_nanosec(); // nanoseconds since start of program, first call initializes char * formatted_elapsed_time_t(guint precision); // printable elapsed time char * formatted_time_t(uint64_t nanos); char * formatted_epoch_time_t(time_t epoch_seconds); #define NANOS2MICROS( _nanosec ) (((_nanosec) + 500)/1000) #define NANOS2MILLIS( _nanosec ) (((_nanosec)+500000)/1000000) #define MILLIS2NANOS( _millisec) (_millisec*(uint64_t)1000000) #define MILLIS2MICROS(_millisec) (_millisec*(uint64_t)1000) #ifdef __cplusplus } #endif #endif /* TIMESTAMP_H_ */ ddcutil-2.2.0/src/util/traced_function_stack.h0000644000175000001440000000242314754576332015112 /** @file traced_function_stack.h */ // Copyright (C) 2024-2025 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef TRACED_FUNCTION_STACK_H_ #define TRACED_FUNCTION_STACK_H_ #ifdef __cplusplus extern "C" { #endif #include #include extern bool traced_function_stack_enabled; extern bool traced_function_stack_errors_fatal; extern __thread GQueue * traced_function_stack; extern __thread bool traced_function_stack_suspended; extern __thread bool debug_tfs; bool set_debug_thread_tfs(bool newval); void push_traced_function(const char * funcname); char* peek_traced_function(); void pop_traced_function(const char * funcname); void collect_traced_function_stack(GPtrArray* collector, GQueue * stack, bool reverse, int stack_adjust); void debug_current_traced_function_stack(bool reverse); GPtrArray* get_current_traced_function_stack_contents(bool most_recent_last); void current_traced_function_stack_to_syslog(int syslog_priority, bool reverse); void reset_current_traced_function_stack(); void free_current_traced_function_stack(); void free_all_traced_function_stacks(); #ifdef __cplusplus } // extern "C" #endif #endif /* TRACED_FUNCTION_STACK_H_ */ ddcutil-2.2.0/src/util/udev_i2c_util.h0000644000175000001440000000165614754576332013322 /** @file udev_i2c_util.h * I2C specific udev utilities */ // Copyright (C) 2016-2021 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef UDEV_I2C_UTIL_H_ #define UDEV_I2C_UTIL_H_ /** \cond */ #include #include /** \endcond */ #include "data_structures.h" #include "udev_util.h" GPtrArray * // array of Udev_Device_Summary get_i2c_devices_using_udev(); int udev_i2c_device_summary_busno(Udev_Device_Summary * summary); void report_i2c_udev_device_summaries( GPtrArray * summaries, // array of Udev_Device_Summary char * title, int depth) ; /** Signature of function that tests sys attribute name */ typedef bool (*Sysattr_Name_Filter)(const char * sysattr_name); Byte_Value_Array get_i2c_device_numbers_using_udev_w_sysattr_name_filter(Sysattr_Name_Filter keep_func); #endif /* UDEV_I2C_UTIL_H_ */ ddcutil-2.2.0/src/util/x11_util.h0000644000175000001440000000141214754576332012221 /** @file x11_util.h Utilities for X11 */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef X11_UTIL_H_ #define X11_UTIL_H_ /** \cond */ #include /** \endcond */ #include "coredefs.h" /** Represents one EDID known to X11 */ typedef struct { char * output_name; ///< RandR output name Byte * edidbytes; ///< pointer to 128 byte EDID } X11_Edid_Rec; GPtrArray * get_x11_edids(bool use_screen_resources_current); // returns array of X11_Edid_Rec void free_x11_edids(GPtrArray * edidrecs); bool get_x11_dpms_info(unsigned short * power_level, unsigned char * state); const char* dpms_power_level_name(unsigned short power_level); #endif /* X11_UTIL_H_ */ ddcutil-2.2.0/src/vcp/0000775000175000001440000000000014754576332010301 5ddcutil-2.2.0/src/vcp/Makefile.am0000644000175000001440000000140614754153540012244 AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) if WARNINGS_ARE_ERRORS_COND AM_CFLAGS += "-Werror" endif # vcp_feature_codes.c requires extensive changes if -Wpedantic # AM_CFLAGS += -Wpedantic CLEANFILES = \ *expand clean-local: @echo "(src/vcp/Makefile) clean-local" mostlyclean-local: @echo "(src/vcp/Makefile) mostlyclean-local" distclean-local: @echo "(src/vcp/Makefile) distclean-local" dist-hook: @echo "(src/vcp/Makefile) dist-hook" # Intermediate Library noinst_LTLIBRARIES = libvcp.la libvcp_la_SOURCES = \ parse_capabilities.c \ parsed_capabilities_feature.c \ persistent_capabilities.c \ vcp_feature_codes.c \ vcp_feature_values.c ddcutil-2.2.0/src/vcp/Makefile.in0000664000175000001440000005273114754576155012301 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @WARNINGS_ARE_ERRORS_COND_TRUE@am__append_1 = "-Werror" subdir = src/vcp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libvcp_la_LIBADD = am_libvcp_la_OBJECTS = parse_capabilities.lo \ parsed_capabilities_feature.lo persistent_capabilities.lo \ vcp_feature_codes.lo vcp_feature_values.lo libvcp_la_OBJECTS = $(am_libvcp_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/parse_capabilities.Plo \ ./$(DEPDIR)/parsed_capabilities_feature.Plo \ ./$(DEPDIR)/persistent_capabilities.Plo \ ./$(DEPDIR)/vcp_feature_codes.Plo \ ./$(DEPDIR)/vcp_feature_values.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libvcp_la_SOURCES) DIST_SOURCES = $(libvcp_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ $(GLIB_CFLAGS) \ -I$(top_srcdir)/src \ -I$(top_srcdir)/src/public AM_CFLAGS = $(AM_CFLAGS_STD) $(am__append_1) # vcp_feature_codes.c requires extensive changes if -Wpedantic # AM_CFLAGS += -Wpedantic CLEANFILES = \ *expand # Intermediate Library noinst_LTLIBRARIES = libvcp.la libvcp_la_SOURCES = \ parse_capabilities.c \ parsed_capabilities_feature.c \ persistent_capabilities.c \ vcp_feature_codes.c \ vcp_feature_values.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/vcp/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/vcp/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libvcp.la: $(libvcp_la_OBJECTS) $(libvcp_la_DEPENDENCIES) $(EXTRA_libvcp_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libvcp_la_OBJECTS) $(libvcp_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parse_capabilities.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parsed_capabilities_feature.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/persistent_capabilities.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vcp_feature_codes.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vcp_feature_values.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/parse_capabilities.Plo -rm -f ./$(DEPDIR)/parsed_capabilities_feature.Plo -rm -f ./$(DEPDIR)/persistent_capabilities.Plo -rm -f ./$(DEPDIR)/vcp_feature_codes.Plo -rm -f ./$(DEPDIR)/vcp_feature_values.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-local distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/parse_capabilities.Plo -rm -f ./$(DEPDIR)/parsed_capabilities_feature.Plo -rm -f ./$(DEPDIR)/persistent_capabilities.Plo -rm -f ./$(DEPDIR)/vcp_feature_codes.Plo -rm -f ./$(DEPDIR)/vcp_feature_values.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool mostlyclean-local pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-local \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am dist-hook \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-local distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool mostlyclean-local pdf \ pdf-am ps ps-am tags tags-am uninstall uninstall-am .PRECIOUS: Makefile clean-local: @echo "(src/vcp/Makefile) clean-local" mostlyclean-local: @echo "(src/vcp/Makefile) mostlyclean-local" distclean-local: @echo "(src/vcp/Makefile) distclean-local" dist-hook: @echo "(src/vcp/Makefile) dist-hook" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/vcp/parse_capabilities.c0000644000175000001440000007145414634376340014213 /** @file parse_capabilities.c * Parse the capabilities string returned by DDC, query the parsed data structure. */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include /** \endcond */ #include "util/report_util.h" #include "util/string_util.h" #include "base/core.h" #include "base/ddc_command_codes.h" #include "base/displays.h" #include "base/rtti.h" #include "base/vcp_version.h" #include "vcp/parsed_capabilities_feature.h" #include "vcp/vcp_feature_codes.h" #include "vcp/parse_capabilities.h" static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_NONE; #undef CAPABILITIES_TESTS // #define CAPABILITIES_TESTS #ifdef CAPABILITIES_TESTS // not made static to avoid warning about unused variable char* test_cap_strings[] = { // GSM LG Ultra HD "(prot(monitor)type(LED)model(25UM65)cmds(01 02 03 0C E33 F3)" "vcp(0203(10 00)0405080B0C101214(05 07 08 0B) 16181A5260(3033 04)6C6E70" "87ACAEB6C0C6C8C9D6(01 04)DFE4E5E6E7E8E9EAEBED(00 10 20 40)EE(00 01)" "FE(01 02 03)FF)mswhql(1)mccs_ver(2.1))", // Asus PB287 "(prot(monitor) type(LCD)model LCDPB287 cmds(01 02 03 07 0C F3) " "vcp(02 04 05 08 0B 0C 10 12 14(05 06 08 0B) 16 18 1A 60(11 12 0F) " "62 6C 6E 70 8D(01 02) A8 AC AE B6 C6 C8 C9 D6(01 04) DF) " "mccs_ver(2.1)asset_eep(32)mpu(01)mswhql(1))", }; #endif Value_Name_Table capabilities_validity_names = { VN(CAPABILITIES_VALID), VN(CAPABILITIES_USABLE), VN(CAPABILITIES_INVALID), VN_END }; char * capabilities_validity_name(Parsed_Capabilities_Validity validity) { return vnt_name(capabilities_validity_names, validity); } void dbgrpt_parsed_capabilities(Parsed_Capabilities * pcaps, int depth) { int d1 = depth+1; int d2 = depth+2; rpt_structure_loc("Parsed_Capabilities", pcaps, depth); if (pcaps) { rpt_vstring(d1, "raw value: %s", pcaps->raw_value); rpt_vstring(d1, "raw_value_synthesized: %s", sbool(pcaps->raw_value_synthesized)); rpt_vstring(d1, "model: %s", pcaps->model); rpt_vstring(d1, "mccs version string: %s", pcaps->mccs_version_string); rpt_vstring(d1, "parsed_mccs_version: %d.%d = %s", pcaps->parsed_mccs_version.major, pcaps->parsed_mccs_version.minor, format_vspec(pcaps->parsed_mccs_version) ); rpt_vstring(d1, "raw_cmds_segment_seen: %s", sbool(pcaps->raw_cmds_segment_seen)); rpt_vstring(d1, "raw_cmds_segment_valid: %s", sbool(pcaps->raw_cmds_segment_valid) ); char * t = (pcaps->commands) ? bva_as_string(pcaps->commands, /*as_hex=*/true, " ") : NULL; rpt_vstring(d1, "commands: %s", (t) ? t : "NULL"); if (t) free(t); rpt_vstring(d1, "raw_vcp_features_seen: %s", sbool(pcaps->raw_vcp_features_seen)); rpt_vstring(d1, "vcp_features.len: %d", pcaps->vcp_features->len); rpt_vstring(d1, "caps_validity: %s", capabilities_validity_name(pcaps->caps_validity)); if (!pcaps->messages || pcaps->messages->len == 0) rpt_label(d1, "No messages"); else { rpt_label(d1, "Messages:"); for (int ndx = 0; ndx < pcaps->messages->len; ndx++) rpt_vstring(d2, "%s", (char *) g_ptr_array_index(pcaps->messages, ndx)); } } } /** Frees a Parsed_Capabilities record * * @param pcaps pointer to #Parsed_Capabilities struct */ void free_parsed_capabilities(Parsed_Capabilities * pcaps) { bool debug = false; DBGMSF(debug, "Starting. pcaps=%p", pcaps); assert( pcaps ); assert( memcmp(pcaps->marker, PARSED_CAPABILITIES_MARKER, 4) == 0); free(pcaps->raw_value); free(pcaps->mccs_version_string); free(pcaps->model); if (pcaps->commands) bva_free(pcaps->commands); if (pcaps->vcp_features) { DBGMSF(debug, "vcp_features->len = %d", pcaps->vcp_features->len); int ndx; for (ndx=pcaps->vcp_features->len-1; ndx >=0; ndx--) { Capabilities_Feature_Record * vfr = g_ptr_array_index(pcaps->vcp_features, ndx); // report_feature(vfr); free_capabilities_feature_record(vfr); g_ptr_array_remove_index(pcaps->vcp_features, ndx); } g_ptr_array_free(pcaps->vcp_features, true); if (pcaps->messages) g_ptr_array_free(pcaps->messages, true); } pcaps->marker[3] = 'x'; free(pcaps); } // // *** Utility Functions *** // /* Point to the first non-space character in a string. * * @param s pointer to string * \parsm len length of string * @return pointer to first non-space character of string, * end of string if not found */ char * ltrim(char * s, int len) { while (len > 0 && *s == ' ') { len--; s++; } return s; } /** Finds the matching closing parenthesis for the * current open parenthesis. * * @param start first character to examine (must be '(') * @param end points to end of string, i.e. the byte * after the last character to examine * @return pointer pointer to closing parenthesis, * end if closing parenthesis not found */ static char * find_closing_paren( char * start, char * end) { assert( *start == '('); char * pos = start+1; int depth = 1; while (pos < end && depth > 0) { if (*pos == '(') depth++; else if (*pos == ')') depth--; pos++; } if (depth == 0) pos--; return pos; } Parsed_Capabilities_Validity update_validity( Parsed_Capabilities_Validity validity, Parsed_Capabilities_Validity cur_validity) { // could be clever using the ordering of the numeric value of enum // but this is robust against enum changes Parsed_Capabilities_Validity result = CAPABILITIES_USABLE; if (validity == CAPABILITIES_INVALID || cur_validity == CAPABILITIES_INVALID) result = CAPABILITIES_INVALID; else if (validity == CAPABILITIES_VALID && cur_validity == CAPABILITIES_VALID) result = CAPABILITIES_VALID; return result; } // // Parsing // /* Capabilities string format: Parenthesized expression containing sequence of "segments" each segment consists of a segment name, followed by a parenthesized value */ // // cmds() segment // /** Parses the value of the cmds segment, which is a list of 2 character values * separated by spaces. * * @param start start of values * @param len segment length * @param messages accumulates error messages * @return #Byte_Value_Array indicating command values seen, * NULL if a parsing error * * @remark * Alternatively, return a ByteBitFlag value, or pass a * preallocted ByteBitFlag instance * * @remark * On every monitor tested, the values are separated by spaces. * However, per the Access Bus spec, Section 7, values need not be separated by spaces, * e.g. 010203 is valid */ static Byte_Value_Array parse_cmds_segment( char * start, int len, GPtrArray * messages) { bool debug = false; DBGMSF(debug, "Starting. start=%p, len=%d", start, len); Byte_Value_Array cmd_ids = bva_create(); bool ok = store_bytehex_list(start, len, cmd_ids, bva_appender); // ok = false; // force failure for testing if (!ok) { char * s = g_strdup_printf("Error processing commands list: %.*s", len, start); g_ptr_array_add(messages, s); } if (!ok) { bva_free(cmd_ids); cmd_ids = NULL; } DBGMSF(debug, "Done. Returning %p", cmd_ids); return cmd_ids; } // // vcp segment // #ifdef FUTURE void parse_vcp_values(char * start, int len, GPtrArray* messages) { } #endif // // vcp() segment // typedef struct { char * code_start; int code_len; char * values_start; int values_len; char * remainder_start; int remainder_len; bool valid; } Vcp_Feature_Segment; /** Parse the value of a vcp() segment.. * * @param start offset to start of segment * @param len length of segment * @param messages accumulates error messages * * A VCP contains either the feature code in hex, or the feature code followed * by a parenthesized list of values (in hex). * * @returns GPtrArray of Capabilities_Feature_Record * * * The returned pointer is never NULL. The **GPtrArray** it points to may * contain 0 pointers. */ static Parsed_Capabilities_Validity parse_vcp_segment( char * start, int len, GPtrArray * vcp_array, GPtrArray * messages) { bool debug = false; DBGMSF(debug, "Starting. len = %d, start=%p -> %.*s", len, start, len, start); // Vcp_Code_Table_Entry * vcp_entry; // future? Parsed_Capabilities_Validity result = CAPABILITIES_VALID; char * pos = start; char * end = start + len; DBGMSF(debug, "Parsing: |%.*s|", len, start); Byte cur_feature_id = 0x00; // initialization logically unnecessary, but o.w. get warning bool valid_feature; int value_len = 0; // initialization logically unnecessary, but o.w. get warning char * value_start = NULL; // ditto while (pos < end) { valid_feature = false; // strip leading blanks while(*pos == ' ' && pos < end) pos++; if (pos == end) break; char * st = pos; while (*pos != ' ' && *pos != '(' && pos < end) pos++; int len = pos-st; DBGMSF(debug, "Found: Feature code subsegment: %.*s", len, st); // If len > 2, feature codes not separated by blanks. Take just the first 2 characters if (len > 2) { pos = st + 2; len = 2; } bool feature_code_ok = false; if (len == 2) { // cur_feature_id = hhc_to_byte(st); // what if invalid hex? feature_code_ok = hhc_to_byte_in_buf(st, &cur_feature_id); if (feature_code_ok) { valid_feature = true; value_start = NULL; value_len = 0; } } if (!feature_code_ok) { char * s = g_strdup_printf("Feature %.*s (Invalid code)",1,st); g_ptr_array_add(messages, s); // f0printf(ferr(), "Feature: %.*s (invalid code)\n", 1, st); if (result == CAPABILITIES_VALID) result = CAPABILITIES_USABLE; } if (*pos == '(') { // find matching ) char * value_end = find_closing_paren(pos, end); if (value_end == end) { g_ptr_array_add(messages, g_strdup("Value parse terminated without closing parenthesis") ); // TODO: recover from error, this is bad data from the monitor result = CAPABILITIES_INVALID; goto bye; // Error is fatal } value_start = pos+1; value_len = value_end - (pos + 1); // printf(" Values: %.*s\n", value_len, value_start); pos = value_end + 1; // point to character after closing paren } if (valid_feature) { Capabilities_Feature_Record * vfr = parse_capabilities_feature(cur_feature_id, value_start, value_len, messages); // if (debug) { // DDCA_MCCS_Version_Spec dummy_version = {0,0}; // report_capabilities_feature(vfr, dummy_version, 1); // } if (!vfr->valid_values && result == CAPABILITIES_VALID) result = CAPABILITIES_USABLE; g_ptr_array_add(vcp_array, vfr); } } bye: if (result != CAPABILITIES_VALID) DBGMSF(debug, "feature = 0x%02x, %s", cur_feature_id, capabilities_validity_name(result) ); return result; } #ifdef IN_PROGRESS /** Process the VCP segment * * @param start offset to start of segment * @param len length of segment * @param messages accumulates error messages * * @returns GPtrArray of Capabilities_Feature_Record * * * The returned pointer is never NULL. The **GPtrArray** it points to may * contain 0 pointers. */ Parsed_Capabilities_Validity parse_vcp_segment_new( char * start, int len, GPtrArray * vcp_array, GPtrArray * messages) { bool debug = false; DBGMSF(debug, "Starting. len = %d, start=%p -> %.*s", len, start, len, start); // Vcp_Code_Table_Entry * vcp_entry; // future? Parsed_Capabilities_Validity validity = CAPABILITIES_VALID; Vcp_Feature_Segment* segment = NULL; char * pos = start; while( (segment = next_vcp_feature_segment(pos, len, messages)) ) { // start debug code if (!segment->valid) { // issue msg? break; } DBGMSG("call a function to process the segment"); Parsed_Capabilities_Validity cur_validity = parse_single_feature(segment, vcp_array, messages); validity = update_validity(validity, cur_validity); pos = segment->remainder_start; len = segment->remainder_len; } DBGMSG("Begin regular parsing"); Parsed_Capabilities_Validity result = CAPABILITIES_VALID; // char * pos = start; char * end = start + len; DBGMSF(debug, "Parsing: |%.*s|", len, start); Byte cur_feature_id = 0x00; // initialization logically unnecessary, but o.w. get warning bool valid_feature; int value_len = 0; // initialization logically unnecessary, but o.w. get warning char * value_start = NULL; // ditto while (pos < end) { valid_feature = false; // strip leading blanks while(*pos == ' ' && pos < end) pos++; if (pos == end) break; char * st = pos; while (*pos != ' ' && *pos != '(' && pos < end) pos++; int len = pos-st; DBGMSF(debug, "Found: Feature code subsegment: %.*s", len, st); // If len > 2, feature codes not separated by blanks. Take just the first 2 characters if (len > 2) { pos = st + 2; len = 2; } bool feature_code_ok = false; if (len == 2) { // cur_feature_id = hhc_to_byte(st); // what if invalid hex? feature_code_ok = hhc_to_byte_in_buf(st, &cur_feature_id); if (feature_code_ok) { valid_feature = true; value_start = NULL; value_len = 0; } } if (!feature_code_ok) { char * s = g_strdup_printf("Feature %.*s (Invalid code)",1,st); g_ptr_array_add(messages, s); // f0printf(ferr(), "Feature: %.*s (invalid code)\n", 1, st); if (result == CAPABILITIES_VALID) result = CAPABILITIES_USABLE; } if (*pos == '(') { // find matching ) char * value_end = find_closing_paren(pos, end); if (value_end == end) { g_ptr_array_add(messages, "Value parse terminated without closing parenthesis" ); // TODO: recover from error, this is bad data from the monitor result = CAPABILITIES_INVALID; goto bye; // Error is fatal } value_start = pos+1; value_len = value_end - (pos + 1); // printf(" Values: %.*s\n", value_len, value_start); pos = value_end + 1; // point to character after closing paren } if (valid_feature) { Capabilities_Feature_Record * vfr = parse_capabilities_feature(cur_feature_id, value_start, value_len, messages); // if (debug) { // DDCA_MCCS_Version_Spec dummy_version = {0,0}; // report_capabilities_feature(vfr, dummy_version, 1); // } if (!vfr->valid_values && result == CAPABILITIES_VALID) result = CAPABILITIES_USABLE; g_ptr_array_add(vcp_array, vfr); } } bye: if (result != CAPABILITIES_VALID) DBGMSG("feature = 0x%02x, %s", cur_feature_id, capabilities_validity_name(result) ); return result; } #endif // // Top level functions for parsing a capabilities string // // A top level segment of the capabilities string // Has the form " name(value)", e.g. "commands(01 02 04 08)" typedef struct { char * name_start; int name_len; char * value_start; int value_len; char * remainder_start; int remainder_len; } Capabilities_Segment; // implement if necessary: // void dbgrpt_capabilities_segment(Capabilities_Segment * segment, int depth) { /** Extract the next top level segment of the capabilities string. * * @param start current position in the capabilities string * @param len length of remainder of capabilities string * @return pointer to newly allocated Capabilities_Segment describing the segment * It is the responsibility of the caller to free the returned struct, * BUT NOT THE LOCATIONS IT ADDRESSES */ static Capabilities_Segment * next_capabilities_segment(char * start, int len, GPtrArray* messages, char * capabilities_staring_start) { bool debug = false; DBGMSF(debug, "Starting. len=%d, start=%p -> |%.*s|", len, start, len, start); const char * global_start = capabilities_staring_start; // was: start; char * end = start+len; Capabilities_Segment * segment = calloc(1, sizeof(Capabilities_Segment)); // n. Apple Cinema Display precedes segment name with blank char * trimmed_start = ltrim(start, len); int trimmed_len = len - (trimmed_start - start) ; char * errmsg = NULL; // DBGMSG("trimmed_len=%ld, trimmed_start=%p -> |%.*s|", // trimmed_len, trimmed_start, trimmed_len, trimmed_start); if (trimmed_len == 0) { // just indicate there's no more to do free(segment); segment = NULL; goto bye; } char * pos = trimmed_start; #define REQUIRE(_condition, _msg, _position) \ if (!(_condition)) { \ g_ptr_array_add(messages, g_strdup_printf("%s at offset %jd", \ _msg, (intmax_t)( _position-global_start)) ); \ segment->name_start = segment->value_start = segment->remainder_start = NULL; \ segment->name_len = segment->value_len = segment->remainder_len = 0; \ goto bye; \ } REQUIRE( *trimmed_start != '(' , "Missing segment name", pos); segment->name_start = trimmed_start; while (pos < end && *pos != '(' && *pos != ' ') {pos++;} // name stops with either left paren or space REQUIRE( pos < end, "Nothing follows segment name", pos); segment->name_len = pos-trimmed_start; while ( pos < end && *pos == ' ' ) { pos++; } // blanks following segment name errmsg = g_strdup_printf("Nothing follows segment name (2) %.*s", segment->name_len, segment->name_start); REQUIRE( pos < end, errmsg, pos); free(errmsg); errmsg = NULL; // assert(*pos == '('); DBGMSF(debug, "pos=%p, trimmed_start=%p", pos, trimmed_start); segment->name_len = pos - trimmed_start; DBGMSF(debug, "start=%p, len=%d, trimmed_start=%p", start, len, trimmed_start); DBGMSF(debug, "name_len = %d, name_start = %p -> %.*s", segment->name_len, segment->name_start, segment->name_len, segment->name_start); errmsg = g_strdup_printf("Missing parenthesized value for segment %.*s", segment->name_len, segment->name_start); REQUIRE(*pos == '(', errmsg, pos); free(errmsg); errmsg = NULL; segment->value_start = pos+1; pos =find_closing_paren(pos, end); errmsg = g_strdup_printf("No closing parenthesis for segment %.*s", segment->name_len, segment->name_start); REQUIRE(pos < end, errmsg, pos); free(errmsg); errmsg=NULL; segment->value_len = pos - segment->value_start; REQUIRE(segment->value_len > 0, "zero length value", pos); segment->remainder_start = pos+1; segment->remainder_len = end - (pos+1); // printf("name: |%.*s|\n", segment->name_len, segment->name_start); // printf("value: |%.*s|\n", segment->value_len, segment->value_start); // printf("remainder: |%.*s|\n", segment->remainder_len, segment->remainder_start); bye: if (errmsg) free(errmsg); DBGMSF(debug, "Returning: %p", segment); return segment; } /** Parses the entire capabilities string * * @param buf_start starting address of string * @param buf_len length of string (not including trailing null) * * @return pointer to newly allocated ParsedCapabilities structure */ Parsed_Capabilities * parse_capabilities( char * buf_start, int buf_len) { assert(buf_start); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "buf_len=%d, buf_start=%p->|%.*s|", buf_start, buf_len, buf_len, buf_start); if ( IS_DBGTRC(debug, TRACE_GROUP) ) { rpt_hex_dump((Byte*)buf_start, buf_len, 1); } // right trim white space while ( buf_len > 0 && *(buf_start+buf_len-1) == ' ') { buf_len--; } char * capabilities_string_start = buf_start; Parsed_Capabilities* pcaps = calloc(1, sizeof(Parsed_Capabilities)); memcpy(pcaps->marker, PARSED_CAPABILITIES_MARKER, 4); // Explicitly initialize all fields as documentation pcaps->raw_value = chars_to_string(buf_start, buf_len); pcaps->raw_value_synthesized = false; // set by user of function pcaps->mccs_version_string = NULL; pcaps->parsed_mccs_version = DDCA_VSPEC_UNQUERIED; pcaps->raw_cmds_segment_seen = false; pcaps->commands = NULL; pcaps->raw_vcp_features_seen = false; pcaps->raw_cmds_segment_valid = false; pcaps->caps_validity = CAPABILITIES_VALID; pcaps->vcp_features = g_ptr_array_sized_new(40); pcaps->messages = g_ptr_array_new(); // DBGMSG("Initial buf_len=%d, buf_start=%p -> |%.*s|", buf_len, buf_start, buf_len, buf_start); // Apple Cinema display violates spec, does not surround capabilities string with parens if (buf_start[0] == '(') { if (buf_start[buf_len-1] != ')') { g_ptr_array_add(pcaps->messages, g_strdup("Capabilities string lacks closing parenthesis")); pcaps->caps_validity = CAPABILITIES_INVALID; goto bye; } // trim starting and ending parens buf_start = buf_start+1; buf_len = buf_len -2; } // DBGMSG("Adjusted buf_len=%d, buf_start=%p -> |%.*s|", buf_len, buf_start, buf_len, buf_start); while (buf_len > 0) { Capabilities_Segment * seg = next_capabilities_segment(buf_start, buf_len, pcaps->messages, capabilities_string_start); if (seg->name_start == NULL) { // error condition encountered pcaps->caps_validity = CAPABILITIES_INVALID; free(seg); break; } buf_start = seg->remainder_start; buf_len = seg->remainder_len; DBGMSF(debug, "Segment: |%.*s| -> |%.*s|", seg->name_len, seg->name_start, seg->value_len, seg->value_start ); // cmds segment if (seg->name_len == 4 && // avoid buffer overflow memcmp(seg->name_start, "cmds", seg->name_len) == 0) { pcaps->raw_cmds_segment_seen = true; pcaps->commands = parse_cmds_segment(seg->value_start, seg->value_len, pcaps->messages); pcaps->raw_cmds_segment_valid = (pcaps->commands); // ?? if (!pcaps->commands) { if (pcaps->caps_validity == CAPABILITIES_VALID) pcaps->caps_validity = CAPABILITIES_USABLE; } } // vcp segment else if (seg->name_len == 3 && (memcmp(seg->name_start, "vcp", seg->name_len) == 0 || memcmp(seg->name_start, "VCP", seg->name_len) == 0 // hack for Apple Cinema Display ) ) { pcaps->raw_vcp_features_seen = true; Parsed_Capabilities_Validity vcp_segment_validity = parse_vcp_segment(seg->value_start, seg->value_len, pcaps->vcp_features, pcaps->messages); pcaps->caps_validity = update_validity(pcaps->caps_validity, vcp_segment_validity); } else if (seg->name_len == 8 && memcmp(seg->name_start, "mccs_ver" /* was "mccs_version_string" WHY? */, seg->name_len) == 0) { pcaps->mccs_version_string = chars_to_string(seg->value_start, seg->value_len); DDCA_MCCS_Version_Spec vspec = parse_vspec(pcaps->mccs_version_string); // n. will be DDCA_VSPEC_UNQUERIED if no value string, DDCA_VSPEC_UNKNOWN if invalid pcaps->parsed_mccs_version = vspec; DBGMSF(debug, "parsed version: %s", format_vspec(vspec)); if ( vcp_version_eq(vspec,DDCA_VSPEC_UNKNOWN)) { if (pcaps->caps_validity == CAPABILITIES_VALID) pcaps->caps_validity = CAPABILITIES_USABLE; char * errmsg = g_strdup_printf("Invalid mccs_ver: \"%s\"", pcaps->mccs_version_string); g_ptr_array_add(pcaps->messages, errmsg); } } else if ( seg->name_len == 5 && memcmp(seg->name_start, "model", seg->name_len) == 0 ) { DBGMSF(debug, "model: |%.*s|", seg->value_len, seg->value_start); pcaps->model = chars_to_string(seg->value_start, seg->value_len); // DBGMSF(debug, "pcaps->model = |%s|", pcaps->model); } else { // additional segment names seen: asset_eep, mpu, mswhql DBGMSF(debug, "Ignoring segment: %.*s", seg->name_len, seg->name_start); } free(seg); // allocated by next_capabilities_segment() } bye: DBGTRC_RET_STRUCT(debug, DDCA_TRC_NONE, "Parsed_Capabilities", dbgrpt_parsed_capabilities, pcaps); return pcaps; } /** Parses a capabilities string * * @param caps null terminated capabilities string * @return pointer to newly allocated #Parsed_Capabilities structure */ Parsed_Capabilities* parse_capabilities_string( char * caps) { assert(caps); #ifdef CAPABILITIES_TESTS // Uncomment to enable test DBGMSG("Substituting test capabilities string"); caps = test_cap_strings[1]; #endif return parse_capabilities(caps, strlen(caps)); } // // Functions to query Parsed_Capabilities // /** Returns list of feature ids in a #Parsed_Capabilities structure. * * @param pcaps pointer to #Parsed_Capabilities * @param readable_only restrict returned list to readable features * * @return #Bit_Set_256 value indicating features found */ Bit_Set_256 get_parsed_capabilities_feature_ids( Parsed_Capabilities * pcaps, bool readable_only) { assert(pcaps); bool debug = false; DBGMSF(debug, "Starting. readable_only=%s, feature count=%d", sbool(readable_only), pcaps->vcp_features->len); // Byte_Bit_Flags flags = bbf_create(); Bit_Set_256 flags = EMPTY_BIT_SET_256; if (pcaps->vcp_features) { // pathological case of 0 length capabilities string for (int ndx = 0; ndx < pcaps->vcp_features->len; ndx++) { Capabilities_Feature_Record * frec = g_ptr_array_index(pcaps->vcp_features, ndx); // DBGMSG("Feature 0x%02x", frec->feature_id); bool add_feature_to_list = true; if (readable_only) { VCP_Feature_Table_Entry * vfte = vcp_find_feature_by_hexid_w_default(frec->feature_id); if (!is_feature_readable_by_vcp_version(vfte, pcaps->parsed_mccs_version)) add_feature_to_list = false; if (vfte->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) free_synthetic_vcp_entry(vfte); } if (add_feature_to_list) // bbf_insert(flags, frec->feature_id); flags = bs256_insert(flags, frec->feature_id); } } DBGMSF(debug, "Returning Bit_Set_256: %s", bs256_to_string_t(flags, "x", ", ") ); return flags; } /** Checks if a monitor supports table features. * * @param pcaps pointer to #Parsed_Capabilities (may be null) * * @return **true** if a command segment was parsed and both * Table Read Request and Table Read Reply are declared * **false** otherwise */ bool parsed_capabilities_supports_table_commands(Parsed_Capabilities * pcaps) { bool result = false; if (pcaps && pcaps->raw_cmds_segment_seen && pcaps->commands && bva_contains(pcaps->commands, 0xe2) && // Table Read Request bva_contains(pcaps->commands, 0xe4) // Table Read Reply ) { result = false; } return result; } // // *** TESTS *** // #ifdef CAPABILITIES_TESTS // // Tests // #ifdef OLD void test_segment(char * text) { char * start = text; int len = strlen(text); Capabilities_Segment * capseg = next_capabilities_segment(start, len); free(capseg); // it's just a test function, but avoid coverity flagging memory leak } void test_segments() { test_segment("vcp(10 20)"); test_segment("vcp(10 20)abc"); test_segment("vcp(10 20 30( asdf ))x"); } #endif void test_parse_caps() { Parsed_Capabilities * pcaps = parse_capabilities_string("(alpha(adsf)vcp(10 20 30(31 32) ))"); dbgrpt_parsed_capabilities(pcaps,0); free_parsed_capabilities(pcaps); } #endif /** Module initialization */ void init_parse_capabilities() { RTTI_ADD_FUNC(parse_capabilities); } ddcutil-2.2.0/src/vcp/parsed_capabilities_feature.c0000644000175000001440000001200614754153540016054 /** \file parsed_capabilities_feature.c * Describes one VCP feature in a capabilities string. * * The functions in this file are used only in parse_capabilities.c, * but were extracted for clarity. */ // Copyright (C) 2014-2020 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include #include "util/data_structures.h" #include "util/report_util.h" #include "util/string_util.h" /** \endcond */ #include "vcp/vcp_feature_codes.h" #include "vcp/parsed_capabilities_feature.h" // Trace class for this file // static TraceGroup TRACE_GROUP = TRC_DDC; // currently unused, commented out to avoid warning void dbgrpt_capabilities_feature_record( Capabilities_Feature_Record * vfr, int depth) { int d1 = depth+1; rpt_structure_loc("Capabilities_Feature_Record", vfr, depth); rpt_vstring(d1, "marker: %.4s", vfr->marker); rpt_vstring(d1, "feature_ide: 0x%02x", vfr->feature_id); if (vfr->values) { char * s = bva_as_string(vfr->values, true, " "); rpt_vstring(d1, "values: %s", s); free(s); } else rpt_vstring(d1, "values: None"); rpt_vstring(d1, "value_string: %s", vfr->value_string); rpt_vstring(d1, "valid_values: %s", sbool(vfr->valid_values)); } /** Given a feature code and the unparenthesized value string extracted * from a capabilities string, parses the value string and creates * a #Capabilities_Feature_Record. * * \param feature_id * \param value_string_start start of value string, NULL if no values string * \param value_string_len length of value string * \return newly allocated #Capabilities_Feature_Record */ Capabilities_Feature_Record * parse_capabilities_feature( Byte feature_id, char * value_string_start, int value_string_len, GPtrArray * error_messages) { bool debug = false; if (debug) { DBGMSG("Starting. Feature: 0x%02x", feature_id); if (value_string_start) DBGMSG("value string: |%.*s|", value_string_len, value_string_start); else DBGMSG("value_string_start = NULL"); } Capabilities_Feature_Record * vfr = (Capabilities_Feature_Record *) calloc(1,sizeof(Capabilities_Feature_Record)); memcpy(vfr->marker, CAPABILITIES_FEATURE_MARKER, 4); vfr->feature_id = feature_id; // relying on calloc to 0 all other fields if (value_string_start) { vfr->value_string = (char *) malloc( value_string_len+1); memcpy(vfr->value_string, value_string_start, value_string_len); vfr->value_string[value_string_len] = '\0'; #if !defined(CFR_BVA) && !defined(CFR_BBF) // sanity check assert(false); #endif #ifdef CFR_BVA Byte_Value_Array bva_values = bva_create(); bool ok1 = store_bytehex_list(value_string_start, value_string_len, bva_values, bva_appender); if (!ok1) { char * s = g_strdup_printf("Invalid VCP value in list for feature x%02x: %.*s", feature_id, value_string_len, value_string_start); g_ptr_array_add(error_messages, s); } if (debug) { DBGMSG("store_bytehex_list for bva returned %s", sbool(ok1)); bva_report(vfr->values, "Feature values (array):"); } vfr->valid_values = ok1; vfr->values = bva_values; #endif #ifdef CFR_BBF Byte_Bit_Flags bbf_values = bbf_create(); bool ok2 = store_bytehex_list(value_string_start, value_string_len, bbf_values, bbf_appender); if (!ok2) { char * s = g_strdup_printf("Invalid VCP value in list for feature x%02x: %.*s", feature_id, value_string_len, value_string_start); g_ptr_array_add(error_messages, s); } if (debug) { DBGMSG("store_bytehex_list for bbf returned %s", sbool(ok2)); char buf[768]; DBGMSG("ByteBitFlags as list: %s", bbf_to_string(bbf_values,buf,768)); } vfr->bbflags = bbf_values; // if not testing exactly 1 of CFR_BBF and CFR_BVA will be set vfr->valid_values = ok2; #endif #if defined(CFR_BVA) && defined(CFR_BBF) if (ok1 && ok2) { DBGMSF(debug, "Comparing Byte_value_Array vs ByteBitFlags"); assert(bva_bbf_same_values(bva_values, bbf_values)); } #endif } // value_string_start not NULL return vfr; } /** Frees a #Capabilities_Feature_Record instance. * * \param pfeat pointer to #Capabilities_Feature_Record to free.\n * If null, do nothing */ void free_capabilities_feature_record( Capabilities_Feature_Record * pfeat) { // DBGMSG("Starting. pfeat=%p", pfeat); if (pfeat) { assert(memcmp(pfeat->marker, CAPABILITIES_FEATURE_MARKER, 4) == 0); if (pfeat->value_string) free(pfeat->value_string); if (pfeat->values) bva_free(pfeat->values); #ifdef BBF if (pfeat->bbflags) bbf_free(pfeat->bbflags); #endif pfeat->marker[3] = 'x'; free(pfeat); } // DBGMSG("Done."); } ddcutil-2.2.0/src/vcp/persistent_capabilities.c0000644000175000001440000003277314754153540015300 /** @file persistent_capabilities.c */ // Copyright (C) 2021-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include #include #include "public/ddcutil_types.h" #include "public/ddcutil_status_codes.h" #include "util/error_info.h" #include "util/file_util.h" #include "util/report_util.h" #include "util/string_util.h" #include "util/xdg_util.h" #include "base/core.h" #include "base/monitor_model_key.h" #include "base/parms.h" #include "base/rtti.h" #include "persistent_capabilities.h" static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_VCP; static bool capabilities_cache_enabled = false; // default set in parser static GHashTable * capabilities_hash = NULL; static GMutex persistent_capabilities_mutex; static void dbgrpt_capabilities_hash0(int depth, const char * msg) { int d = depth; if (msg) { rpt_label(depth, msg); d = depth+1; } if (!capabilities_hash) rpt_label(d, "No capabilities hash table"); else { if (g_hash_table_size(capabilities_hash) == 0) rpt_label(d, "Empty capabilities hash table"); else { // rpt_label(depth, "capabilities_hash hash table:"); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, capabilities_hash); while (g_hash_table_iter_next(&iter, &key, &value)) { rpt_vstring(d, "%s : (%p -> |%s|)", (char *) key, value, (char*) value); } } // rpt_nl(); } } /** Deletes the capabilities cache file if it exists. */ void delete_capabilities_file() { bool debug = false; char * fn = capabilities_cache_file_name(); if (fn && regular_file_exists(fn)) { DBGMSF(debug, "Deleting file: %s", fn); int rc = unlink(fn); if (rc < 0) { // should never occur SEVEREMSG("Unexpected error deleting file %s: %s", fn, strerror(errno)); fprintf(fout(), "Unexpected error deleting file %s: %s\n", fn, strerror(errno)); } } else { DBGMSF(debug, "File does not exist: %s", fn); } free(fn); } /** If capabilities caching is enabled and the capabilities cache file * exists, load the cache file. * * @param capabilities_hash_loc points to in-memory capabilities hash table * @return Error_Info struct if errors, NULL if no errors * * If *capabilities_cache_loc != NULL, the capabilities file has already * been loaded. Do nothing. * * Otherwise, creates a hash table and sets *capabilities_hash_loc. * If capabilities caching enabled, attempt to load it from the cache file. */ static Error_Info * load_persistent_capabilities_file(GHashTable** capabilities_hash_loc) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "capabilities_hash:"); if ( IS_DBGTRC(debug, TRACE_GROUP) ) dbgrpt_capabilities_hash0(2,NULL); Error_Info * errs = NULL; if (!*capabilities_hash_loc) { *capabilities_hash_loc = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); if (capabilities_cache_enabled) { char * data_file_name = capabilities_cache_file_name(); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "data_file_name: %s", data_file_name); if (!data_file_name) { SEVEREMSG("Unable to determine capabilities cache file name"); SYSLOG2(DDCA_SYSLOG_ERROR, "Unable to determine capabilities cache file name"); errs = ERRINFO_NEW(-ENOENT, "Unable to determine capabilities cache file name"); goto bye; } GPtrArray * linearray = g_ptr_array_new_with_free_func(g_free); errs = file_getlines_errinfo(data_file_name, linearray); free(data_file_name); if (!errs) { for (int ndx = 0; ndx < linearray->len; ndx++) { char * aline = strtrim(g_ptr_array_index(linearray, ndx)); // DBGMSF(debug, "Processing line %d: %s", ndx+1, aline); if (strlen(aline) > 0 && aline[0] != '*' && aline[0] != '#') { char * colon = strchr(aline, ':'); if (!colon) { if (!errs) errs = errinfo_new(DDCRC_BAD_DATA, __func__, "Invalid capabilities file"); errinfo_add_cause(errs, errinfo_new(DDCRC_BAD_DATA, __func__, "Line %d, No colon in %s", ndx+1, aline)); } else { *colon = '\0'; g_hash_table_insert(capabilities_hash, g_strdup(aline), g_strdup(colon+1)); } } free(aline); } g_ptr_array_free(linearray, true); } if (errs) { delete_capabilities_file(); g_hash_table_remove_all(*capabilities_hash_loc); } } } assert(*capabilities_hash_loc); bye: DBGTRC_RET_ERRINFO(debug, TRACE_GROUP, errs, "capabilities_hash:"); if (IS_DBGTRC(debug, TRACE_GROUP) ) dbgrpt_capabilities_hash0(2, NULL); return errs; } static void save_persistent_capabilities_file() { bool debug = false; char * data_file_name = xdg_cache_home_file("ddcutil", "capabilities"); DBGTRC_STARTING(debug, TRACE_GROUP, "capabilities_cache_enabled: %s, data_file_name=%s", sbool(capabilities_cache_enabled), data_file_name); if (capabilities_cache_enabled) { if (!data_file_name) { SEVEREMSG("Cannot determine capabilities cache file name"); SYSLOG2(DDCA_SYSLOG_ERROR, "Cannot determine capabilities cache file name"); goto bye1; } FILE * fp = NULL; fopen_mkdir(data_file_name, "w", ferr(), &fp); if (!fp) { // SEVEREMSG("Error opening %s: %s", data_file_name, strerror(errno)); // handled by fopen_mdkr() goto bye; } if (capabilities_hash) { GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, capabilities_hash); for (int line_ctr=1; g_hash_table_iter_next(&iter, &key, &value); line_ctr++) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Writing line %d: %s:%s", line_ctr, key, value); int ct = fprintf(fp, "%s:%s\n", (char *) key, (char*) value); if (ct < 0) { SEVEREMSG("Error writing to file %s:%s", data_file_name, strerror(errno) ); SYSLOG2(DDCA_SYSLOG_ERROR, "Error writing to file %s:%s", data_file_name, strerror(errno) ); break; } } } fclose(fp); } bye: free(data_file_name); bye1: DBGTRC_DONE(debug, TRACE_GROUP, ""); } static inline bool generic_model_name(char * model_name) { char * generic_names[] = { "LG IPS FULLHD", "LG UltraFine", "LG Ultrawide", "LG UltraWide", "Samsung Syncmaster"}; int namect = ARRAY_SIZE(generic_names); bool result = false; for (int ndx = 0; ndx < namect; ndx++) { if ( streq(model_name, generic_names[ndx]) ) { result = true; break; } } return result; } /** Some manufacturers use generic model names and don't set a product code. * (LG is a particularly bad offender.) In that case a #DDCA_Monitor_Model_Key * is unsuitable for identifying a capabilities string. * * \param mmk #Monitor_Model_Key value to check * \return true if **mmk** does not uniquely identify a monitor model, * false if it does */ static inline bool non_unique_model_id(Monitor_Model_Key* mmk) { return ( generic_model_name(mmk->model_name) && ( mmk->product_code == 0 || mmk->product_code == 0x0101) ); } // Publicly visible functions /** Emit a debug report of the capabilities hash table * * \param depth logical indentation depth * \param msg if non-null, emit this message before the report * * \remark * This operation is protected by the persistent capabilities mutex */ void dbgrpt_capabilities_hash(int depth, const char * msg) { g_mutex_lock(&persistent_capabilities_mutex); dbgrpt_capabilities_hash0(depth, msg); g_mutex_unlock(&persistent_capabilities_mutex); } /** Returns the name of the file that stores persistent capabilities * * \return name of file, normally $HOME/.cache/ddcutil/capabilities */ /* caller is responsible for freeing returned value */ char * capabilities_cache_file_name() { return xdg_cache_home_file("ddcutil", CAPABILITIES_CACHE_FILENAME); } /** Enable saving capabilities strings in a file. * * \param newval true to enable, false to disable * \return old setting */ bool enable_capabilities_cache(bool newval) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "newval=%s", sbool(newval)); g_mutex_lock(&persistent_capabilities_mutex); bool old = capabilities_cache_enabled; if (newval) { capabilities_cache_enabled = true; } else { capabilities_cache_enabled = false; // if (capabilities_hash) { // g_hash_table_destroy(capabilities_hash); // capabilities_hash = NULL; // } // delete_capabilities_file(); } g_mutex_unlock(&persistent_capabilities_mutex); DBGTRC_RET_BOOL(debug, TRACE_GROUP, old, "capabilities_cache_enabled has been set = %s", sbool(capabilities_cache_enabled)); return old; } /** Look up the capabilities string for a monitor model. * * The returned value is owned by the persistent capabilities * hash table and should not be freed. * * \param mmk monitor model key * \return capabilities string, NULL if not found or capabilities * caching disabled * * \remark * Returns NULL in case of a potentially ambiguous Monitor_Model_Key */ char * get_persistent_capabilities(Monitor_Model_Key* mmk) { assert(mmk); bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "mmk -> %s, capabilities_cache_enabled=%s", mmk_repr(*mmk), sbool(capabilities_cache_enabled)); char * result = NULL; if (capabilities_cache_enabled) { if (non_unique_model_id(mmk)) { SYSLOG2(DDCA_SYSLOG_WARNING, "Non unique Monitor_Model_Key %s", mmk_repr(*mmk)); DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Non unique Monitor_Model_Key. Returning NULL"); } else { g_mutex_lock(&persistent_capabilities_mutex); Error_Info * load_errs = NULL; DBGMSF(debug, "capabilities_hash = %p", capabilities_hash); if (!capabilities_hash) { // if not yet loaded load_errs = load_persistent_capabilities_file(&capabilities_hash); if (load_errs) { if (ERRINFO_STATUS(load_errs) == -ENOENT) errinfo_free(load_errs); else { char * data_file_name = capabilities_cache_file_name(); SEVEREMSG("Error(s) loading persistent capabilities file %s", data_file_name); free(data_file_name); for (int ndx =0; ndx < load_errs->cause_ct; ndx++) { Error_Info * cur = load_errs->causes[ndx]; SEVEREMSG(" %s", cur->detail); } BASE_ERRINFO_FREE_WITH_REPORT(load_errs,false); } } } assert(capabilities_hash); char * mms = g_strdup(mmk_string(mmk)); if (debug) { DBGMSG("Hash table before lookup:"); dbgrpt_capabilities_hash0(2, NULL); DBGMSG("Looking for key: mms -> |%s|", mms); } result = g_hash_table_lookup (capabilities_hash, mms); free(mms); } g_mutex_unlock(&persistent_capabilities_mutex); } DBGTRC_DONE(debug, TRACE_GROUP, "Returning: %s", result); return result; } /** Saves a capabilities string in the capabilities lookup table and, * if persistent capabilities are enabled, writes the string and its * key to the table on the file system. * * \param mmk monitor model key * \param capabilities capabilities string * * \remark * The string arguments are copied into the hash table. */ void set_persistent_capabilites( Monitor_Model_Key * mmk, const char * capabilities) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "capabilities_cache_enabled=%s. mmk->%s, capabilities = %s", sbool(capabilities_cache_enabled), mmk_string(mmk), capabilities); g_mutex_lock(&persistent_capabilities_mutex); if (capabilities_cache_enabled) { if (non_unique_model_id(mmk)) { DBGTRC_NOPREFIX(debug, TRACE_GROUP, "Not saving capabilities for non-unique Monitor_Model_Key."); SYSLOG2(DDCA_SYSLOG_WARNING, "Not saving capabilities for non-unique Monitor_Model_Key: %s", mmk_string(mmk)); } else { char * mms = g_strdup(mmk_string(mmk)); g_hash_table_insert(capabilities_hash, mms, g_strdup(capabilities)); if (debug || IS_TRACING()) dbgrpt_capabilities_hash0(2, "Capabilities hash after insert and before saving"); save_persistent_capabilities_file(); } } g_mutex_unlock(&persistent_capabilities_mutex); DBGTRC_DONE(debug, TRACE_GROUP, ""); } void terminate_persistent_capabilities() { if (capabilities_hash) g_hash_table_destroy(capabilities_hash); } void init_persistent_capabilities() { RTTI_ADD_FUNC(enable_capabilities_cache); RTTI_ADD_FUNC(load_persistent_capabilities_file); RTTI_ADD_FUNC(save_persistent_capabilities_file); RTTI_ADD_FUNC(get_persistent_capabilities); RTTI_ADD_FUNC(set_persistent_capabilites); } ddcutil-2.2.0/src/vcp/vcp_feature_codes.c0000644000175000001440000050417214754153540014044 /** @file vcp_feature_codes.c * * VCP Feature Code Table and related functions */ // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later /** \cond */ #include #include #include #include #include "util/data_structures.h" #include "util/debug_util.h" #include "util/report_util.h" #include "util/string_util.h" /** \cond */ #include "base/ddc_errno.h" #include "base/feature_metadata.h" #include "base/rtti.h" #include "base/vcp_version.h" #include "vcp/vcp_feature_codes.h" // Direct writes to stdout,stderr: // in table validation functions (Benign) static DDCA_Trace_Group TRACE_GROUP = DDCA_TRC_VCP; // Forward references int vcp_feature_code_count; VCP_Feature_Table_Entry vcp_code_table[]; static DDCA_Feature_Value_Entry x14_color_preset_absolute_values[]; static DDCA_Feature_Value_Entry x14_color_preset_tolerances[]; DDCA_Feature_Value_Entry xc8_display_controller_type_values[]; static DDCA_Feature_Value_Entry x8d_tv_audio_mute_source_values[]; static DDCA_Feature_Value_Entry x8d_sh_blank_screen_values[]; static DDCA_Feature_Value_Entry xca_osd_values[]; static DDCA_Feature_Value_Entry xca_v22_osd_button_sl_values[]; static DDCA_Feature_Value_Entry xca_v22_osd_button_sh_values[]; static bool vcp_feature_codes_initialized = false; // // Functions implementing the VCPINFO command // /* Appends a string to an existing string in a buffer. * If the length of the existing string is greater than 0, * append ", " first. * * Arguments: * val value to append * buf start of buffer * bufsz buffer size * * Returns: buf * * Note: No check is made that buf contains a valid string. */ static char * str_comma_cat_r(char * val, char * buf, int bufsz) { size_t cursz = strlen(buf); assert(cursz + 2 + strlen(val) + 1 <= bufsz); if (cursz > 0) strcat(buf, ", "); strcat(buf, val); return buf; } char * spec_group_names_r(VCP_Feature_Table_Entry * pentry, char * buf, int bufsz) { *buf = '\0'; if (pentry->vcp_spec_groups & VCP_SPEC_PRESET) str_comma_cat_r("Preset", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_IMAGE) str_comma_cat_r("Image", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_CONTROL) str_comma_cat_r("Control", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_GEOMETRY) str_comma_cat_r("Geometry", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_MISC) str_comma_cat_r("Miscellaneous", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_AUDIO) str_comma_cat_r("Audio", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_DPVL) str_comma_cat_r("DPVL", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_MFG) str_comma_cat_r("Manufacturer specific", buf, bufsz); if (pentry->vcp_spec_groups & VCP_SPEC_WINDOW) str_comma_cat_r("Window", buf, bufsz); return buf; } char * vcp_interpret_global_feature_flags( DDCA_Global_Feature_Flags flags, char* buf, int buflen) { // DBGMSG("flags: 0x%04x", flags); char * synmsg = ""; if (flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) synmsg = "Synthetic VCP Feature Table Entry"; char * synmsg2 = ""; // if (flags & DDCA_SYNTHETIC_DDCA_FEATURE_METADATA) // synmsg = "Fully-Synthetic "; if (flags & DDCA_SYNTHETIC) // should not occur for a VCP feature table entry synmsg = "Synthetic "; char * synmsg3 = ""; // should not occur for a VCP feature table entry if (flags & DDCA_PERSISTENT_METADATA) synmsg = "Persistent "; char * dynmsg = ""; if (flags & DDCA_USER_DEFINED) // should not occur for a VCP feature table entry dynmsg = "Dynamic "; g_snprintf(buf, buflen, "%s%s%s%s", synmsg, synmsg2, synmsg3, dynmsg); return buf; } // End of VCPINFO related functions // // Miscellaneous VCP_Feature_Table lookup functions // char * get_feature_name_by_id_only(Byte feature_id) { char * result = NULL; VCP_Feature_Table_Entry * vcp_entry = vcp_find_feature_by_hexid(feature_id); if (vcp_entry) result = get_non_version_specific_feature_name(vcp_entry); else if (0xe0 <= feature_id && feature_id <= 0xff) result = "manufacturer specific feature"; else result = "unrecognized feature"; return result; } char * get_feature_name_by_id_and_vcp_version(Byte feature_id, DDCA_MCCS_Version_Spec vspec) { bool debug = false; char * result = NULL; VCP_Feature_Table_Entry * vcp_entry = vcp_find_feature_by_hexid(feature_id); if (vcp_entry) { result = get_version_sensitive_feature_name(vcp_entry, vspec); if (!result) result = get_non_version_specific_feature_name(vcp_entry); // fallback } else if (0xe0 <= feature_id && feature_id <= 0xff) result = "Manufacturer specific feature"; else result = "Unrecognized feature"; DBGMSF(debug, "feature_id=0x%02x, vspec=%d.%d, returning: %s", feature_id, vspec.major, vspec.minor, result); return result; } int vcp_get_feature_code_count() { return vcp_feature_code_count; } /* Gets the appropriate VCP flags value for a feature, given * the VCP version for the monitor. * * Arguments: * pvft_entry vcp_feature_table entry * vcp_version VCP version for monitor * * Returns: * flags, 0 if feature is not defined for version */ DDCA_Version_Feature_Flags get_version_specific_feature_flags( VCP_Feature_Table_Entry * pvft_entry, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; DDCA_Version_Feature_Flags result = 0; if (vcp_version.major >= 3) result = pvft_entry->v30_flags; else if (vcp_version.major == 2 && vcp_version.minor >= 2) result = pvft_entry->v22_flags; if (!result && (vcp_version.major >= 3 || (vcp_version.major == 2 && vcp_version.minor >= 1)) ) result = pvft_entry->v21_flags; if (!result) result = pvft_entry->v20_flags; #ifdef NO // this is what get_version_sensisitve_feature_flags() is for if (!result) { DDCA_MCCS_Version_Spec version_used = {0,0}; result = pvft_entry->v21_flags; if (result) { version_used.major = 2; version_used.minor = 1; } else { result = pvft_entry->v22_flags; if (result) { version_used.major = 2; version_used.minor = 2; } else { result = pvft_entry->v30_flags; assert(result); version_used.major = 3; version_used.minor = 0; } } char buf[20]; if (vcp_version.major < 1) strcpy(buf, "Undefined"); else snprintf(buf, 20, "%d.%d", vcp_version.major, vcp_version.minor); DBGTRC(true, TRACE_GROUP, "Monitor version %s is less than earliest MCCS version for which VCP feature code %02x is defined.", buf, pvft_entry->code); DBGTRC(true, TRACE_GROUP, "Using definition for MCCS version %d.%d", version_used.major, version_used.minor); } #endif DBGMSF(debug, "Feature = 0x%02x, vcp version=%d.%d, returning 0x%02x", pvft_entry->code, vcp_version.major, vcp_version.minor, result); return result; } bool is_feature_supported_in_version( VCP_Feature_Table_Entry * pvft_entry, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; bool result = false; DDCA_Version_Feature_Flags vflags = get_version_specific_feature_flags(pvft_entry, vcp_version); result = (vflags && !(vflags&DDCA_DEPRECATED)); DBGMSF(debug, "Feature = 0x%02x, vcp versinon=%d.%d, returning %s", pvft_entry->code, vcp_version.major, vcp_version.minor, sbool(result) ); return result; } /* Gets appropriate VCP flags value for a feature, given * the VCP version for the monitor. If the VCP version specified is less than * the first version for which the feature is defined, returns the flags for the * first version for which the feature is defined. This situation can arise when scanning * all possible VCP codes. * * Arguments: * pvft_entry vcp_feature_table entry * vcp_version VCP version for monitor * * Returns: * flags */ DDCA_Version_Feature_Flags get_version_sensitive_feature_flags( VCP_Feature_Table_Entry * pvft_entry, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; DDCA_Version_Feature_Flags result = get_version_specific_feature_flags(pvft_entry, vcp_version); if (!result) { // vcp_version is lower than the first version level at which the field // was defined. This can occur e.g. if scanning. Pick the best // possible flags by scanning up in versions. if (pvft_entry->v21_flags) result = pvft_entry->v21_flags; else if (pvft_entry->v30_flags) result = pvft_entry->v30_flags; else if (pvft_entry->v22_flags) result = pvft_entry->v22_flags; if (!result) { PROGRAM_LOGIC_ERROR( "Feature = 0x%02x, Version=%d.%d: No version sensitive feature flags found", pvft_entry->code, vcp_version.major, vcp_version.minor); assert(false); } } DBGMSF(debug, "Feature = 0x%02x, vcp version=%d.%d, returning 0x%02x", pvft_entry->code, vcp_version.major, vcp_version.minor, result); return result; } bool has_version_specific_features(VCP_Feature_Table_Entry * pentry) { int ct = 0; if (pentry->v20_flags) ct++; if (pentry->v21_flags) ct++; if (pentry->v30_flags) ct++; if (pentry->v22_flags) ct++; return (ct > 1); } /* Returns the highest version number for which a feature is not deprecated */ DDCA_MCCS_Version_Spec get_highest_non_deprecated_version( VCP_Feature_Table_Entry * vfte) { DDCA_MCCS_Version_Spec vspec = {0,0}; if ( vfte->v22_flags && !(vfte->v22_flags & DDCA_DEPRECATED) ) { vspec.major = 2; vspec.minor = 2; } else if ( vfte->v30_flags && !(vfte->v30_flags & DDCA_DEPRECATED) ) { vspec.major = 3; vspec.minor = 0; } else if ( vfte->v21_flags && !(vfte->v21_flags & DDCA_DEPRECATED) ) { vspec.major = 2; vspec.minor = 1; } else if ( vfte->v20_flags && !(vfte->v20_flags & DDCA_DEPRECATED) ) { vspec.major = 2; vspec.minor = 0; } else { PROGRAM_LOGIC_ERROR("Feature 0x%02x is deprecated for all versions", vfte->code); assert(false); } return vspec; } // convenience function bool is_feature_readable_by_vcp_version( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; bool result = (get_version_sensitive_feature_flags(vfte, vcp_version) & DDCA_READABLE ); DBGMSF(debug, "code=0x%02x, vcp_version=%d.%d, returning %d", vfte->code, vcp_version.major, vcp_version.minor, result); return result; } // convenience function bool is_feature_writable_by_vcp_version( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { return (get_version_sensitive_feature_flags(vfte, vcp_version) & DDCA_WRITABLE ); } // convenience function bool is_table_feature_by_vcp_version( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { return (get_version_sensitive_feature_flags(vfte, vcp_version) & DDCA_NORMAL_TABLE ); } // Checks if the table/non-table choice for a feature is version sensitive bool is_version_conditional_vcp_type(VCP_Feature_Table_Entry * vfte) { bool result = false; Byte allflags = vfte->v30_flags | vfte->v22_flags | vfte->v21_flags | vfte->v20_flags; bool some_nontable = allflags & (DDCA_CONT | DDCA_NC); bool some_table = allflags & DDCA_NORMAL_TABLE; result = some_nontable && some_table; return result; } DDCA_Feature_Value_Entry * get_version_specific_sl_values( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; DBGMSF(debug, "feature= 0x%02x, vcp_version = %d.%d", vfte->code, vcp_version.major, vcp_version.minor); DDCA_Feature_Value_Entry * result = NULL; if (vcp_version.major >= 3) result = vfte->v30_sl_values; else if (vcp_version.major == 2 && vcp_version.minor >= 2) result = vfte->v22_sl_values; if (!result && (vcp_version.major >= 3 || (vcp_version.major == 2 && vcp_version.minor == 1)) ) result = vfte->v21_sl_values; if (!result) result = vfte->default_sl_values; DBGMSF(debug, "Feature = 0x%02x, vcp version=%d.%d, returning %p", vfte->code, vcp_version.major, vcp_version.minor, result); return result; } DDCA_Feature_Value_Entry * get_version_sensitive_sl_values( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; DDCA_Feature_Value_Entry * result = get_version_specific_sl_values(vfte, vcp_version); if (!result) { // vcp_version is lower than the first version level at which the field // was defined. This can occur e.g. if scanning. Pick the best // possible flags by scanning up in versions. if (vfte->v21_sl_values) result = vfte->v21_sl_values; else if (vfte->v30_sl_values) result = vfte->v30_sl_values; else if (vfte->v22_sl_values) result = vfte->v22_sl_values; // should it be a fatal error if not found? // if (!result) { // PROGRAM_LOGIC_ERROR( // "Feature = 0x%02x, Version=%d.%d: No version sensitive sl values", // pvft_entry->code, vcp_version.major, vcp_version.minor); // } } DBGMSF(debug, "Feature = 0x%02x, vcp version=%d.%d, returning %p", vfte->code, vcp_version.major, vcp_version.minor, result); return result; } #ifdef UNUSED DDCA_Feature_Value_Entry * get_highest_version_sl_values( VCP_Feature_Table_Entry * vfte) { bool debug = false; DDCA_MCCS_Version_Id version_found = DDCA_MCCS_VNONE; DDCA_Feature_Value_Entry * result = vfte->v22_sl_values; if (result) version_found = DDCA_MCCS_V22; else { result = vfte->v30_sl_values; if (result) version_found = DDCA_MCCS_V30; else { result = vfte->v21_sl_values; if (result) version_found = DDCA_MCCS_V21; else { result = vfte->default_sl_values; if (result) version_found = DDCA_MCCS_V20; } } } if (debug) { if (result) DBGMSG("Feature = 0x%02x, Returning sl value list for version %s", vfte->code, format_vcp_version_id(version_found)); else DBGMSG("Feature = 0x%02x, No SL value table found", vfte->code); } return result; } #endif /** Returns the version specific feature name from a feature table entry. * * @param vfte feature table entry * @param vcp_version VCP feature version * @return feature name * * @remark * Returns a pointer into an internal data structure. Caller should not free. */ char * get_version_specific_feature_name( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; char * result = NULL; if (vcp_version.major >= 3) result = vfte->v30_name; else if (vcp_version.major == 2 && vcp_version.minor >= 2) result = vfte->v22_name; if (!result && (vcp_version.major >= 3 || (vcp_version.major == 2 && vcp_version.minor >= 1)) ) result = vfte->v21_name; if (!result) result = vfte->v20_name; DBGMSF(debug, "Feature = 0x%02x, vcp version=%d.%d, returning %s", vfte->code, vcp_version.major, vcp_version.minor, result); return result; } /** Returns a version sensitive feature name from a feature table entry. * * @param vfte feature table entry * @param vcp_version VCP feature version * @return feature name * * @remark * Returns a pointer into an internal data structure. Caller should not free. */ char * get_version_sensitive_feature_name( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; char * result = get_version_specific_feature_name(vfte, vcp_version); if (!result) { // DBGMSG("Using original name field"); // result = pvft_entry->name; // vcp_version is lower than the first version level at which the field // was defined. This can occur e.g. if scanning. Pick the best // possible name by scanning up in versions. if (vfte->v21_name) result = vfte->v21_name; else if (vfte->v30_name) result = vfte->v30_name; else if (vfte->v22_name) result = vfte->v22_name; if (!result) DBGMSG("Feature = 0x%02x, Version=%d.%d: No version sensitive feature name found", vfte->code, vcp_version.major, vcp_version.minor); } DBGMSF(debug, "Feature = 0x%02x, vcp version=%d.%d, returning %s", vfte->code, vcp_version.major, vcp_version.minor, result); return result; } /** Returns a feature name from a feature table entry without specifying the VCP version. * * For use when we don't know the version or just need a generic * name, as in the vcpinfo command. * * @param vfte feature table entry * @return feature name * * @remark * Returns a pointer into an internal data structure. Caller should not free. */ char * get_non_version_specific_feature_name( VCP_Feature_Table_Entry * vfte) { DDCA_MCCS_Version_Spec vspec = {2,2}; return get_version_sensitive_feature_name(vfte, vspec); } /** Given a #VCP_Feature_Table_Entry, creates a VCP-version specific * #Display_Feature_Metadata. * * @param vfte feature table entry * @param vspec VCP version * @param version_sensitive if true, creation is version sensitive, * if false, version specific * @return newly allocated #Display_Feature_Metadata, caller must free */ Display_Feature_Metadata * extract_version_feature_info_from_feature_table_entry( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vspec, bool version_sensitive) { bool debug = false; DBGTRC_STARTING(debug, DDCA_TRC_NONE, "vspec=%d.%d, version_sensitive=%s", vspec.major, vspec.minor, sbool(version_sensitive)); assert(vfte); // DDCA_MCCS_Version_Id version_id = mccs_version_spec_to_id(vspec); // if (debug) // dbgrpt_vcp_entry(vfte, 2); Display_Feature_Metadata * dfm = dfm_new(vfte->code); dfm->vcp_subsets = vfte->vcp_subsets; dfm->vcp_spec_groups = vfte->vcp_spec_groups; // redundant, for now // info->version_id = mccs_version_spec_to_id(vspec); dfm->vcp_version = vspec; dfm->version_feature_flags = (version_sensitive) ? get_version_sensitive_feature_flags(vfte, vspec) : get_version_specific_feature_flags(vfte, vspec); dfm->feature_desc = (dfm->feature_desc) ? g_strdup(vfte->desc) : NULL; char * feature_name = (version_sensitive) ? get_version_sensitive_feature_name(vfte, vspec) : get_version_specific_feature_name(vfte, vspec); dfm->feature_name = g_strdup(feature_name); dfm->global_feature_flags |= vfte->vcp_global_flags; DDCA_Feature_Value_Entry * sl_values = (version_sensitive) ? get_version_sensitive_sl_values(vfte, vspec) // ? get_highest_version_sl_values(vfte) : get_version_specific_sl_values(vfte, vspec); dfm->sl_values = copy_sl_value_table(sl_values); // dfm->latest_sl_values = copy_sl_value_table(get_highest_version_sl_values(vfte)); DBGTRC_RET_STRUCT(debug, DDCA_TRC_NONE, Display_Feature_Metadata, dbgrpt_display_feature_metadata, dfm); return dfm; } #ifdef MCCS_VERSION_ID /** Gets information about a VCP feature. * * @param feature_code * @param mccs_version_id * @param with_default if feature code not recognized, return dummy information, * otherwise return NULL * @param version_sensitive * * @retval pointer to DDCA_Version_Feature_Info * @retval NULL if feature not found and with_default == false */ Display_Feature_Metadata * get_version_feature_info_by_version_id_dfm( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Id mccs_version_id, bool with_default, bool version_sensitive) { bool debug = false; DBGMSF(debug, "feature_code=0x%02x, mccs_version_id=%d(%s), with_default=%s, version_sensitive=%s", feature_code, mccs_version_id, vcp_version_id_name(mccs_version_id), sbool(with_default), sbool(version_sensitive)); DDCA_MCCS_Version_Spec vspec = mccs_version_id_to_spec(mccs_version_id); return get_version_feature_info_by_vspec_dfm(feature_code, vspec, with_default, version_sensitive); } #endif /** Given a VCP feature code and VCP version, creates a VCP-version specific * #Display_Feature_Metadata. * * @param feature_code VCP feature code * @param vspec VCP version * @param with_default synthesize an entry if no feature table entry * found for the feature code * @param version_sensitive if true, creation is version sensitive, * if false, version specific * @return newly allocated #Display_Feature_Metadata, caller must free */ Display_Feature_Metadata * get_version_feature_info_by_vspec_dfm( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, bool with_default, bool version_sensitive) { bool debug = false; DBGMSF(debug, "feature_code=0x%02x, mccs_version=%d.%d, with_default=%s, version_sensitive=%s", feature_code, vspec.major, vspec.minor, sbool(with_default), sbool(version_sensitive)); Display_Feature_Metadata * dfm = NULL; VCP_Feature_Table_Entry * pentry = (with_default) ? vcp_find_feature_by_hexid_w_default(feature_code) : vcp_find_feature_by_hexid(feature_code); if (pentry) { dfm = extract_version_feature_info_from_feature_table_entry(pentry, vspec, version_sensitive); if (pentry->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) free_synthetic_vcp_entry(pentry); } if (debug) { if (dfm) { DBGMSG("Success. feature info:"); dbgrpt_display_feature_metadata(dfm, 1); } DBGMSG("Returning: %p", dfm); } return dfm; } // // Functions that return a function for formatting a feature value // // Functions that lookup a value contained in a VCP_Feature_Table_Entry, // returning a default if the value is not set for that entry. Format_Normal_Feature_Detail_Function get_nontable_feature_detail_function( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { assert(vfte); bool debug = false; DBGMSF(debug, "Starting. feature = 0x%02x, vcp_version = %d.%d", vfte->code, vcp_version.major, vcp_version.minor); DDCA_Version_Feature_Flags version_specific_flags = get_version_sensitive_feature_flags(vfte, vcp_version); DBGMSF(debug, "version_specific_flags = 0x%04x = %s", version_specific_flags, interpret_ddca_version_feature_flags_symbolic_t(version_specific_flags)); assert(version_specific_flags); assert(version_specific_flags & DDCA_NON_TABLE); Format_Normal_Feature_Detail_Function func = NULL; if (version_specific_flags & DDCA_STD_CONT) func = format_feature_detail_standard_continuous; else if (version_specific_flags & DDCA_SIMPLE_NC) func = format_feature_detail_sl_lookup; else if (version_specific_flags & DDCA_EXTENDED_NC) func = format_feature_detail_sl_lookup_with_sh; else if (version_specific_flags & DDCA_WO_NC) func = NULL; // but should never be called for this case else { assert(version_specific_flags & (DDCA_COMPLEX_CONT | DDCA_COMPLEX_NC | DDCA_NC_CONT)); func = vfte->nontable_formatter; assert(func); } DBGMSF(debug, "Returning: %p", func); return func; } Format_Table_Feature_Detail_Function get_table_feature_detail_function( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version) { assert(vfte); // TODO: REVIEW COMMENT // if VCP_V2NC_V3T, then get version id // based on version id, choose .formatter or .formatter_v3 // NO - test needs to be set in caller, this must return a Format_Feature_Detail_Function, which is not for Table Format_Table_Feature_Detail_Function func = vfte->table_formatter; if (!func) func = default_table_feature_detail_function; return func; } // Functions that apply formatting /** Obtains the formatting function from a feature table entry * based on the VCP version of the monitor, then applies that * function to a non-table value to return that value as a * string. * * @param vfte feature table entry * @param vcp_version VCP version of monitor * @param code_info non-table feature value * @param buffer address of buffer in which to return formatted value * @param bufsz buffer string * * @return true if successful, false if not */ bool vcp_format_nontable_feature_detail( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version, Nontable_Vcp_Value * code_info, char * buffer, int bufsz) { bool debug = false; DBGMSF(debug, "Starting. Code=0x%02x, vcp_version=%d.%d", vfte->code, vcp_version.major, vcp_version.minor); Format_Normal_Feature_Detail_Function ffd_func = get_nontable_feature_detail_function(vfte, vcp_version); bool ok = ffd_func(code_info, vcp_version, buffer, bufsz); return ok; } bool vcp_format_table_feature_detail( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version, Buffer * accumulated_value, char * * aformatted_data ) { Format_Table_Feature_Detail_Function ffd_func = get_table_feature_detail_function(vfte, vcp_version); bool ok = ffd_func(accumulated_value, vcp_version, aformatted_data); return ok; } // Used only in deprecated API function ddca_get_formatted_vcp_value() // to be iftested out once that function is deleted. /* Given a feature table entry and a raw feature value, * return a formatted string interpretation of the value. * * Arguments: * vcp_entry vcp_feature_table_entry * vcp_version monitor VCP version * valrec feature value * aformatted_data location where to return formatted string value * * Returns: * true if formatting successful, false if not * * It is the caller's responsibility to free the returned string. */ bool vcp_format_feature_detail( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version, DDCA_Any_Vcp_Value * valrec, char * * aformatted_data ) { bool debug = false; DBGMSF(debug, "Starting"); bool ok = true; *aformatted_data = NULL; DBGMSF(debug, "valrec->value_type = %d", valrec->value_type); char * formatted_data = NULL; if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { DBGMSF(debug, "DDCA_NON_TABLE_VCP_VALUE"); Nontable_Vcp_Value* nontable_value = single_vcp_value_to_nontable_vcp_value(valrec); char workbuf[200]; ok = vcp_format_nontable_feature_detail( vfte, vcp_version, nontable_value, workbuf, 200); free(nontable_value); if (ok) formatted_data = g_strdup(workbuf); } else { // TABLE_VCP_CALL DBGMSF(debug, "DDCA_TABLE_VCP_VALUE"); ok = vcp_format_table_feature_detail( vfte, vcp_version, buffer_new_with_value(valrec->val.t.bytes, valrec->val.t.bytect, __func__), &formatted_data); } if (ok) { *aformatted_data = formatted_data; assert(*aformatted_data); } else { if (formatted_data) free(formatted_data); assert(!*aformatted_data); } DBGMSF(debug, "Done. Returning %d, *aformatted_data=%p", ok, *aformatted_data); return ok; } // // Functions that return or destroy a VCP_Feature_Table_Entry // /* Free a dynamically created VCP_Feature_Table_Entry.. * Does nothing if the entry is in the permanently allocated * vcp_code_table. */ void free_synthetic_vcp_entry(VCP_Feature_Table_Entry * pfte) { // DBGMSG("pfte = %p", pfte); assert(memcmp(pfte->marker, VCP_FEATURE_TABLE_ENTRY_MARKER, 4) == 0); // DBGMSG("code=0x%02x", pfte->code); // report_vcp_feature_table_entry(pfte, 1); if (pfte->vcp_global_flags & DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY) { #ifdef NO // if synthetic, strings were not malloced DBGMSG("pfte->desc=%p", pfte->desc); DBGMSG("pfte->v20_name=%p", pfte->v20_name); DBGMSG("pfte->v21_name=%p", pfte->v21_name); DBGMSG("pfte->v30_name=%p", pfte->v30_name); DBGMSG("pfte->v22_name=%p", pfte->v22_name); if (pfte->desc) free(pfte->desc); if (pfte->v20_name) free(pfte->v20_name); if (pfte->v21_name) free(pfte->v21_name); if (pfte->v30_name) free(pfte->v30_name); if (pfte->v22_name) free(pfte->v22_name); #endif free(pfte); } } static VCP_Feature_Table_Entry * vcp_new_feature_table_entry(DDCA_Vcp_Feature_Code id) { VCP_Feature_Table_Entry* pentry = calloc(1, sizeof(VCP_Feature_Table_Entry) ); pentry->code = id; memcpy(pentry->marker, VCP_FEATURE_TABLE_ENTRY_MARKER, 4); // DBGMSG("id=0x%02x. Returning: %p", id, pentry); return pentry; } /* Returns an entry in the VCP feature table based on its index in the table. * * Arguments: * ndx table index * * Returns: * VCP_Feature_Table_Entry */ VCP_Feature_Table_Entry * vcp_get_feature_table_entry(int ndx) { // DBGMSG("ndx=%d, vcp_code_count=%d ", ndx, vcp_code_count ); assert( 0 <= ndx && ndx < vcp_feature_code_count); return &vcp_code_table[ndx]; } #ifdef UNUSED VCP_Feature_Table_Entry * vcp_create_dynamic_feature( DDCA_Vcp_Feature_Code id, DDCA_Feature_Metadata * dynamic_metadata) { bool debug = false; DBGMSF(debug, "Starting. id=0x%02x", id); VCP_Feature_Table_Entry * pentry = vcp_new_feature_table_entry(id); pentry->v20_name = dynamic_metadata->feature_name; pentry->desc = dynamic_metadata->feature_desc; pentry->v20_flags = dynamic_metadata->feature_flags; if (pentry->v20_flags & DDCA_SIMPLE_NC) { if (dynamic_metadata->sl_values) { // WRONG needs to a function that can find the lookup table pentry->nontable_formatter = format_feature_detail_sl_lookup; // dyn_format_nontable_feature_detail pentry->default_sl_values = dynamic_metadata->sl_values; // need to copy? } else { pentry->nontable_formatter = format_feature_detail_sl_byte; } } else if (pentry->v20_flags & DDCA_STD_CONT) { pentry->nontable_formatter = format_feature_detail_standard_continuous; } else { // 3/2018: complex cont may not work for API callers pentry->nontable_formatter = format_feature_detail_debug_bytes; } pentry->vcp_global_flags = DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY; // indicates caller should free pentry->vcp_global_flags |= DDCA_USER_DEFINED; DBGMSF(debug, "Done"); return pentry; } #endif /* Creates a dummy VCP feature table entry for a feature code. * It is the responsibility of the caller to free this memory. * * Arguments: * id feature id * * Returns: * created VCP_Feature_Table_Entry */ VCP_Feature_Table_Entry * vcp_create_dummy_feature_for_hexid(DDCA_Vcp_Feature_Code id) { // DBGMSG("Starting. id=0x%02x", id); VCP_Feature_Table_Entry * pentry = vcp_new_feature_table_entry(id); if (id >= 0xe0) { pentry->v20_name = "Manufacturer Specific"; pentry->desc = "Feature code reserved for manufacturer use"; } else { pentry->v20_name = "Unknown feature"; pentry->desc = "Undefined feature code"; } // 3/2018: complex cont may not work for API callers pentry->nontable_formatter = format_feature_detail_debug_bytes; pentry->v20_flags = DDCA_RW | DDCA_COMPLEX_NC; pentry->vcp_global_flags = DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY; // indicates caller should free pentry->vcp_global_flags |= DDCA_SYNTHETIC; // indicates generated feature metadata return pentry; } /* Creates a table type dummy VCP_Feature_Table_Entry for a feature code. * It is the responsibility of the caller to free this memory. * * Arguments: * id feature id * * Returns: * created VCP_Feature_Table_Entry */ VCP_Feature_Table_Entry * vcp_create_table_dummy_feature_for_hexid(DDCA_Vcp_Feature_Code id) { VCP_Feature_Table_Entry * pentry = vcp_new_feature_table_entry(id); if (id >= 0xe0) { pentry->v20_name = "Manufacturer Specific"; } else { pentry->v20_name = "Unknown feature"; } pentry->table_formatter = default_table_feature_detail_function, pentry->v20_flags = DDCA_RW | DDCA_NORMAL_TABLE; pentry->vcp_global_flags = DDCA_SYNTHETIC_VCP_FEATURE_TABLE_ENTRY; // indicates caller should free pentry->vcp_global_flags |= DDCA_SYNTHETIC; // indicates generated feature metadata return pentry; } /* Returns an entry in the VCP feature table based on the hex value * of its feature code. * * Arguments: * id feature id * * Returns: * VCP_Feature_Table_Entry, NULL if not found * Note this is a pointer into the VCP feature data structures. * It should NOT be freed by the caller. */ VCP_Feature_Table_Entry * vcp_find_feature_by_hexid(DDCA_Vcp_Feature_Code id) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "id=0x%02x", id); int ndx = 0; VCP_Feature_Table_Entry * result = NULL; for (;ndx < vcp_feature_code_count; ndx++) { if (id == vcp_code_table[ndx].code) { result = &vcp_code_table[ndx]; break; } } // DBGMSG("ndx= %d", ndx); DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "ndx=%d", ndx); DBGTRC_RET_STRUCT(debug, TRACE_GROUP, "VCP_Feature_Table_Entry", dbgrpt_vcp_entry, result); return result; } /* Returns an entry in the VCP feature table based on the hex value * of its feature code. If the entry is not found, a synthetic entry * is generated. It is the responsibility of the caller to free this * entry. * * Arguments: * id feature id * * Returns: * VCP_Feature_Table_Entry */ VCP_Feature_Table_Entry * vcp_find_feature_by_hexid_w_default(DDCA_Vcp_Feature_Code id) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, "id=0x%02x", id); VCP_Feature_Table_Entry * result = vcp_find_feature_by_hexid(id); if (!result) { DBGTRC_NOPREFIX(debug, DDCA_TRC_NONE, "Creating dummy feature"); result = vcp_create_dummy_feature_for_hexid(id); } DBGTRC_DONE(debug, TRACE_GROUP, "returning %p", result); if (IS_DBGTRC(debug, TRACE_GROUP)) dbgrpt_vcp_entry(result, 1); return result; } //////////////////////////////////////////////////////////////////////// // // Functions to format Table values // /////////////////////////////////////////////////////////////////////// /* Value formatting function for use with table features when we don't * understand how to interpret the values. * * Arguments: * data byte buffer * vcp_version VCP Version spec * presult where to return formatted value * * Returns: * Newly allocated formatted string. It is the responsiblity of the * caller to free this string. */ bool default_table_feature_detail_function( Buffer * data, DDCA_MCCS_Version_Spec vcp_version, char ** presult) { *presult = hexstring2(data->bytes, data->len, " " /*spacer*/, false /* upper case */, NULL, 0); return true; } // // Functions applicable to multiple Table feature codes // // none so far // // Functions to format specific Table feature values // // x73 bool format_feature_detail_x73_lut_size( Buffer * data_bytes, DDCA_MCCS_Version_Spec vcp_version, char ** pformatted_result) { bool ok = true; if (data_bytes->len != 9) { DBGMSG("Expected 9 byte response. Actual response:"); hex_dump(data_bytes->bytes, data_bytes->len); ok = default_table_feature_detail_function(data_bytes, vcp_version, pformatted_result); } else { Byte * bytes = data_bytes->bytes; gushort red_entry_ct = bytes[0] << 8 | bytes[1]; gushort green_entry_ct = bytes[2] << 8 | bytes[3]; gushort blue_entry_ct = bytes[4] << 8 | bytes[5]; int red_bits_per_entry = bytes[6]; int green_bits_per_entry = bytes[7]; int blue_bits_per_entry = bytes[8]; char buf[200]; snprintf(buf, sizeof(buf), "Number of entries: %d red, %d green, %d blue, Bits per entry: %d red, %d green, %d blue", red_entry_ct, green_entry_ct, blue_entry_ct, red_bits_per_entry, green_bits_per_entry, blue_bits_per_entry); *pformatted_result = g_strdup(buf); } return ok; } // // Functions for interpreting non-continuous features whose values are // stored in the SL byte // /* Returns the feature value table for a feature. In a few cases, the table * is VCP version sensitive. * * Arguments: * feature_code VCP feature id * vcp_version VCP version of monitor * * Returns: * pointer to feature value table, NULL if not found */ static DDCA_Feature_Value_Entry * find_feature_value_table( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; DBGMSF(debug, "Starting. feature_code=0x%02x, vcp_version=%d.%d", feature_code, vcp_version.major, vcp_version.minor); DDCA_Feature_Value_Entry * result = NULL; VCP_Feature_Table_Entry * pentry = vcp_find_feature_by_hexid(feature_code); // may not be found if called for capabilities and it's a mfg specific code if (pentry) { if (debug) dbgrpt_vcp_entry(pentry, 1); DDCA_Version_Feature_Flags feature_flags = get_version_sensitive_feature_flags(pentry, vcp_version); // if (feature_code == 0x66) // *** TEMP *** // feature_flags = DDCA_RW | VCP2_SIMPLE_NC; assert(feature_flags); // feature 0xca is of type DDCA_COMPLEX_NC when vcp version = 2.2, // it uses the sl byte for one lookup table, and the sh byte for another // This hack lets capabilities interpretation look up the sl byte // Normal interpretation of function xca uses dedicated function if ( (feature_flags & (DDCA_SIMPLE_NC|DDCA_EXTENDED_NC)) || feature_code == 0xca) { result = get_version_specific_sl_values(pentry, vcp_version); } } DBGMSF(debug, "Done. feature_code=0x%02x. Returning feature value table at: %p", feature_code, result); return result; } // hack to handle x14, where the sl values are not stored in the vcp feature table // used by CAPABILITIES command DDCA_Feature_Value_Entry * find_feature_values_for_capabilities( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vcp_version) { bool debug = false; if (debug) DBGMSG("Starting. feature_code=0x%02x", feature_code); // ugh .. need to know the version number here // for now just assume vcp version < 3, return the table for v2 DDCA_Feature_Value_Entry * result = NULL; if (feature_code == 0x14) { if (vcp_version.major < 3) result = x14_color_preset_absolute_values; else { SEVEREMSG("Unimplemented: x14 lookup when vcp version >= 3"); } } else { // returns NULL if feature_code not found, which would be the case, e.g., for a // manufacturer specific code result = find_feature_value_table(feature_code, vcp_version); } if (debug) DBGMSG("Starting. feature_code=0x%02x. Returning: %p", feature_code, result); return result; } /* Given the ids for a feature code and a SL byte value, * return the explanation string for value. * * The VCP version is also passed, given that for a few * features the version 3 values are not a strict superset * of the version 2 values. * * Arguments: * feature_code VCP feature code * vcp_version VCP version * value_id value to look up * * Returns: * explanation string, or "Invalid value" if value_id not found */ static char * lookup_value_name( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vcp_version, Byte sl_value) { bool debug = false; DBGMSF(debug, "feature_code=0x%02x, vcp_version=%d.%d, sl_value=-0x%02x", feature_code, vcp_version.major, vcp_version.minor, sl_value); DDCA_Feature_Value_Entry * values_for_feature = find_feature_value_table(feature_code, vcp_version); assert(values_for_feature); char * name = sl_value_table_lookup(values_for_feature, sl_value); if (!name) name = "Invalid value"; DBGMSF(debug, "Done. Returning: %s", name); return name; } //////////////////////////////////////////////////////////////////////// // // Functions to format Non-Table values // /////////////////////////////////////////////////////////////////////// // // Value formatting functions for use with non-table features when we don't // understand how to interpret the values for a feature. // // used when the value is calculated using the SL and SH bytes, but we haven't // written a full interpretation function bool format_feature_detail_debug_sl_sh( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { snprintf(buffer, bufsz, "SL: 0x%02x , SH: 0x%02x", code_info->sl, code_info->sh); return true; } // For debugging features marked as Continuous // Outputs both the byte fields and calculated cur and max values bool format_feature_detail_debug_continuous( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { snprintf(buffer, bufsz, "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x, max value = %5d, cur value = %5d", code_info->mh, code_info->ml, code_info->sh, code_info->sl, code_info->max_value, code_info->cur_value); return true; } bool format_feature_detail_debug_bytes( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { snprintf(buffer, bufsz, "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", code_info->mh, code_info->ml, code_info->sh, code_info->sl); return true; } // // Functions applicable to multiple non-table feature codes // // used when the value is just the SL byte, but we haven't // written a full interpretation function bool format_feature_detail_sl_byte( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { bool debug = false; DBGMSF(debug, "vcp_code=0x%02x, sl=0x%02x", code_info->vcp_code, code_info->sl); snprintf(buffer, bufsz, "Value: 0x%02x", code_info->sl); DBGMSF(debug, "Returning true, buffer=%s", buffer); return true; } bool format_feature_detail_sh_sl_bytes( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { bool debug = false; DBGMSF(debug, "vcp_code=0x%02x, sh=0x%02x, sl=0x%02x", code_info->vcp_code, code_info->sh, code_info->sl); g_snprintf(buffer, bufsz, "Value: sh=0x%02x sl=0x%02x", code_info->sh, code_info->sl); DBGMSF(debug, "Returning true, buffer=%s", buffer); return true; } /* Formats the value of a non-continuous feature whose value is returned in byte SL. * The names of possible values is stored in a value list in the feature table entry * for the feature. * * Arguments: * code_info parsed feature data * vcp_version VCP version * buffer buffer in which to store output * bufsz buffer size * * Returns: * true if formatting successful, false if not */ bool format_feature_detail_sl_lookup( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { // TODO: lookup feature code in dynamic_sl_value_table char * s = lookup_value_name(code_info->vcp_code, vcp_version, code_info->sl); snprintf(buffer, bufsz,"%s (sl=0x%02x)", s, code_info->sl); return true; } /* Formats the value of a non-continuous feature whose value is returned in byte SL, * and which also uses byte SH. * The names of possible values is stored in a value list in the feature table entry * for the feature. * * Arguments: * code_info parsed feature data * vcp_version VCP version * buffer buffer in which to store output * bufsz buffer size * * Returns: * true if formatting successful, false if not */ bool format_feature_detail_sl_lookup_with_sh( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { // TODO: lookup feature code in dynamic_sl_value_table char * s = lookup_value_name(code_info->vcp_code, vcp_version, code_info->sl); snprintf(buffer, bufsz,"sh=0x%02x, sl=0x%02x=%s", code_info->sh, code_info->sl, s); return true; } // wrong, needs to be per-display void register_dynamic_sl_values( DDCA_Vcp_Feature_Code feature_code, DDCA_Feature_Value_Entry * table) { } /* Standard feature detail formatting function for a feature marked * as Continuous. * * Arguments: * code_info * vcp_version * buffer location where to return formatted value * bufsz size of buffer * * Returns: * true */ bool format_feature_detail_standard_continuous( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { // TODO: calculate cv, mv here from bytes int cv = code_info->cur_value; int mv = code_info->max_value; // if (msgLevel == TERSE) // printf("VCP %02X %5d\n", vcp_code, cv); // else snprintf(buffer, bufsz, "current value = %5d, max value = %5d", cv, mv); // code_info->cur_value, code_info->max_value);) return true; } /* Standard feature detail formatting function for a feature marked * as Continuous for which the Sh/Sl bytes represent an integer in * the range 0..65535 and max value is not relevant. * * Arguments: * code_info * vcp_version * buffer location where to return formatted value * bufsz size of buffer * * Returns: * true */ bool format_feature_detail_ushort( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { int cv = code_info->cur_value; snprintf(buffer, bufsz, "%5d (0x%04x)", cv, cv); return true; } // // Custom functions for specific non-table VCP Feature Codes // // 0x02 static bool format_feature_detail_x02_new_control_value( // 0x02 Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { char * name = NULL; switch(code_info->sl) { case 0x01: name = "No new control values"; break; case 0x02: name = "One or more new control values have been saved"; break; case 0xff: name = "No user controls are present"; break; default: name = ""; } snprintf(buffer, bufsz, "%s (0x%02x)" , name, code_info->sl); // perhaps set to false if a reserved code return true; } // 0x0b static bool format_feature_detail_x0b_color_temperature_increment( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { if (code_info->cur_value == 0 || code_info->cur_value > 5000 ) snprintf(buffer, bufsz, "Invalid value: %d", code_info->cur_value); else snprintf(buffer, bufsz, "%d degree(s) Kelvin", code_info->cur_value); return true; // or should it be false if invalid value? } // 0x0c static bool format_feature_detail_x0c_color_temperature_request( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { // int increments = code_info->cur_value; snprintf(buffer, bufsz, "3000 + %d * (feature 0B color temp increment) degree(s) Kelvin", code_info->cur_value); return true; } // 0x14 static bool format_feature_detail_x14_select_color_preset( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { bool debug = false; if (debug) DBGMSG("vcp_version=%d.%d", vcp_version.major, vcp_version.minor); bool ok = true; // char buf2[100]; char * sl_msg = NULL; Byte sl = code_info->sl; if (sl == 0x00 || sl >= 0xe0) { sl_msg = "Invalid SL value."; ok = false; } // In 3.0 and 2.2, MH indicates the tolerance, with MH = 0x00 indicating no // tolerance specified. Per the spec, if MH = 0x00, then SL values 0x03..0x0a // indicate relative adjustments from warmer to cooler. If MH != 0x00, // i.e. a tolerance is specified, the SL byte indicates color temperature as usual. // However, on the one v2.2 monitor that has been seen, // an HP Z22i, the SL values listed in the capabilities string // are clearly those for the usual color temperatures. // Therefore, we always treat the SL byte as absolute temperatures, // and for v3.0 and v2.2, we report the ML byte for tolerance. (10/2019) // as observed: else { sl_msg = sl_value_table_lookup(x14_color_preset_absolute_values, code_info->sl); if (!sl_msg) { sl_msg = "Invalid SL value"; ok = false; } } #ifdef PER_THE_SPEC else if (vcp_version.major < 3 || code_info->mh == 0x00) { sl_msg = sl_value_table_lookup(x14_color_preset_absolute_values, code_info->sl); if (!sl_msg) { sl_msg = "Invalid SL value"; ok = false; } #ifdef OLD switch (code_info->sl) { case 0x01: sl_msg = "sRGB"; break; case 0x02: sl_msg = "Display Native"; break; case 0x03: sl_msg = "4000 K"; break; case 0x04: sl_msg = "5000 K"; break; case 0x05: sl_msg = "6500 K"; break; case 0x06: sl_msg = "7500 K"; break; case 0x07: sl_msg = "8200 K"; break; case 0x08: sl_msg = "9300 K"; break; case 0x09: sl_msg = "10000 K"; break; case 0x0a: sl_msg = "11500 K"; break; case 0x0b: sl_msg = "User 1"; break; case 0x0c: sl_msg = "User 2"; break; case 0x0d: sl_msg = "User 3"; break; default: sl_msg = "Invalid SL value"; ok = false; #endif } else { switch (code_info->sl) { case 0x01: sl_msg = "sRGB"; break; case 0x02: sl_msg = "Display Native"; break; case 0x03: sl_msg = "-4 relative warmer"; break; case 0x04: sl_msg = "-3 relative warmer"; break; case 0x05: sl_msg = "-2 relative warmer"; break; case 0x06: sl_msg = "-1 relative warmer"; break; case 0x07: sl_msg = "+1 relative cooler"; break; case 0x08: sl_msg = "+2 relative cooler"; break; case 0x09: sl_msg = "+3 relative cooler"; break; case 0x0a: sl_msg = "+4 relative cooler"; break; case 0x0b: sl_msg = "User 1"; break; case 0x0c: sl_msg = "User 2"; break; case 0x0d: sl_msg = "User 3"; break; default: sl_msg = "Invalid SL value"; ok = false; } } #endif if ( vcp_version_le(vcp_version, DDCA_VSPEC_V21) ) { snprintf(buffer, bufsz, "%s (0x%02x)", sl_msg, sl); } else { char * mh_msg = NULL; #ifdef ALT Byte mh = code_info->mh; char buf0[100]; if (mh == 0x00) mh_msg = "No tolerance specified"; else if (mh >= 0x0b) { mh_msg = "Invalid tolerance"; ok = false; } else { snprintf(buf0, 100, "Tolerance: %d%%", code_info->mh); mh_msg = buf0; } #endif mh_msg = sl_value_table_lookup(x14_color_preset_tolerances, code_info->mh); if (!mh_msg) { mh_msg = "Invalid MH value"; ok = false; } snprintf(buffer, bufsz, "%s (0x%02x), Tolerance: %s (0x%02x)", sl_msg, sl, mh_msg, code_info->mh); } return ok; } // 0x62 static bool format_feature_detail_x62_audio_speaker_volume( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0x62); // Continuous in 2.0, assume 2.1 is same // v2.2: doc lists as both C and NC, but documents special values, treat as NC // v3.0: NC with special x00 and xff values if (vcp_version_le(vcp_version,DDCA_VSPEC_V21)) { snprintf(buffer, bufsz, "%d", code_info->sl); } else { if (code_info->sl == 0x00) snprintf(buffer, bufsz, "Fixed (default) level (0x00)" ); else if (code_info->sl == 0xff) snprintf(buffer, bufsz, "Mute (0xff)"); else snprintf(buffer, bufsz, "Volume level: %d (00x%02x)", code_info->sl, code_info->sl); } return true; } // 0x72 static bool format_feature_detail_x72_gamma( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0x72); char formatted_sh_sl[20]; g_snprintf(formatted_sh_sl, 20, "0x%02x%02x", code_info->sh, code_info->sl); char * ssl = NULL; switch(code_info->sl) { case 0x00: ssl = "White absolute adjustment"; break; case 0x01: ssl = "Red absolute adjustment"; break; case 0x02: ssl = "Green absolute adjustment"; break; case 0x03: ssl = "Blue absolute adjustment"; break; case 0x04: ssl = "White relative adjustment"; break; case 0x05: ssl = "Disable all gamma correction in display"; break; default: ssl = "Reserved, ignored"; } // if absolute adjustment if (code_info->sl == 0x00 || code_info->sl == 0x01 || code_info->sl == 0x02 || code_info->sl == 0x03 ) { int igamma = code_info->sh + 100; char sgamma[10]; char sgamma2[10]; g_snprintf (sgamma, 10, "%d", igamma); uint slen = strlen(sgamma); char * a = substr(sgamma, 0, slen-2); char * b = substr(sgamma, slen-2, 2); g_snprintf(sgamma2, 10, "%s.%s",a, b); free(a); free(b); g_snprintf(buffer, bufsz, "%s - Mode: %s (sl=0x%02x), gamma=%s (sh=0x%02x)", formatted_sh_sl, ssl, code_info->sl, sgamma2, code_info->sh); } else if (code_info->sl == 0x04) { // relative adjustment char * ssh = NULL; switch(code_info->sh) { case 0x00: ssh = "Display default gamma"; break; case 0x01: ssh = "Default gamma - 0.1"; break; case 0x02: ssh = "Default gamma - 0.2"; break; case 0x03: ssh = "Default gamma - 0.3"; break; case 0x04: ssh = "Default gamma - 0.4"; break; case 0x05: ssh = "Default gamma - 0.5"; break; case 0x06: ssh = "Default gamma - 0.6"; break; case 0x07: ssh = "Default gamma - 0.7"; break; case 0x08: ssh = "Default gamma - 0.8"; break; case 0x09: ssh = "Default gamma - 0.9"; break; case 0x0a: ssh = "Default gamma - 1.0"; break; case 0x11: ssh = "Default gamma + 0.1"; break; case 0x12: ssh = "Default gamma + 0.2"; break; case 0x13: ssh = "Default gamma + 0.3"; break; case 0x14: ssh = "Default gamma + 0.4"; break; case 0x15: ssh = "Default gamma + 0.5"; break; case 0x16: ssh = "Default gamma + 0.6"; break; case 0x17: ssh = "Default gamma + 0.7"; break; case 0x18: ssh = "Default gamma + 0.8"; break; case 0x19: ssh = "Default gamma + 0.9"; break; case 0x1a: ssh = "Default gamma + 1.0"; break; case 0x20: ssh = "Disable all gamma correction"; break; default: ssh = "Invalid SH value"; } g_snprintf(buffer, bufsz, "%s - %s (sl=0x%02x) %s (sh=0x%02x)", formatted_sh_sl, ssl, code_info->sl, ssh, code_info->sh); } else if (code_info->sl == 0x05) { g_snprintf(buffer, bufsz, "%s - Mode: gamma correction disabled (sl=0x%02x), sh=0x%02x", formatted_sh_sl, code_info->sl, code_info->sh); } else { g_snprintf(buffer, bufsz, "%s - Invalid sl value. sl=0x%02x, sh=0x%02x", formatted_sh_sl, code_info->sl, code_info->sh); } return true; } // 0x8d static bool format_feature_detail_x8d_mute_audio_blank_screen( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0x8d); // As of v2.2, SH byte contains screen blank settings DDCA_Feature_Value_Entry * sl_values = x8d_tv_audio_mute_source_values; DDCA_Feature_Value_Entry * sh_values = x8d_sh_blank_screen_values; char * sl_name = sl_value_table_lookup(sl_values, code_info->sl); if (!sl_name) sl_name = "Invalid value"; if (vcp_version_eq(vcp_version, DDCA_VSPEC_V22)) { char * sh_name = sl_value_table_lookup(sh_values, code_info->sh); if (!sh_name) sh_name = "Invalid value"; snprintf(buffer, bufsz,"%s (sl=0x%02x), %s (sh=0x%02x)", sl_name, code_info->sl, sh_name, code_info->sh); } else { snprintf(buffer, bufsz,"%s (sl=0x%02x)", sl_name, code_info->sl); } return true; } // 0x8f, 0x91 static bool format_feature_detail_x8f_x91_audio_treble_bass( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0x8f || code_info->vcp_code == 0x91); // Continuous in 2.0, assume 2.1 same as 2.0, // NC with reserved values x00 and xff values reserved in VCP 3.0, 2.2 // This function should not be called if VCP2_STD_CONT // This function should not be called for VCP 2.0, 2.1 // Standard continuous processing should be applied. // But as documentation, handle the C case as well. assert ( vcp_version_gt(vcp_version, DDCA_VSPEC_V21) ); bool ok = true; if ( vcp_version_le(vcp_version, DDCA_VSPEC_V21)) { snprintf(buffer, bufsz, "%d", code_info->sl); } else { if (code_info->sl == 0x00 || code_info->sl == 0xff) { snprintf(buffer, bufsz, "Invalid value: 0x%02x", code_info->sl ); ok = false; } else if (code_info->sl < 0x80) snprintf(buffer, bufsz, "%d: Decreased (0x%02x = neutral - %d)", code_info->sl, code_info->sl, 0x80 - code_info->sl); else if (code_info->sl == 0x80) snprintf(buffer, bufsz, "%d: Neutral (0x%02x)", code_info->sl, code_info->sl); else snprintf(buffer, bufsz, "%d: Increased (0x%02x = neutral + %d)", code_info->sl, code_info->sl, code_info->sl - 0x80); } return ok; } // 0x93 static bool format_feature_detail_x93_audio_balance( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0x93); // Continuous in 2.0, NC in 3.0, 2.2, assume 2.1 same as 2.0 // NC with reserved x00 and special xff values in 3.0, // This function should not be called if VCP_STD_CONT, // but leave v2 code in for completeness assert ( vcp_version_gt(vcp_version, DDCA_VSPEC_V21) ); bool ok = true; if ( vcp_version_le(vcp_version, DDCA_VSPEC_V21)) { snprintf(buffer, bufsz, "%d", code_info->sl); } else { if (code_info->sl == 0x00 || // WTF: in VCP 2.2, value xff is reserved, in 3.0 it's part of the continuous range (code_info->sl == 0xff && vcp_version_eq(vcp_version, DDCA_VSPEC_V22) ) ) { snprintf(buffer, bufsz, "Invalid value: 0x%02x", code_info->sl ); ok = false; } else if (code_info->sl < 0x80) snprintf(buffer, bufsz, "%d: Left channel dominates (0x%02x = centered - %d)", code_info->sl, code_info->sl, 0x80-code_info->sl); else if (code_info->sl == 0x80) snprintf(buffer, bufsz, "%d: Centered (0x%02x)", code_info->sl, code_info->sl); else snprintf(buffer, bufsz, "%d Right channel dominates (0x%02x = centered + %d)", code_info->sl, code_info->sl, code_info->sl-0x80); } return ok; } // 0xac static bool format_feature_detail_xac_horizontal_frequency( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0xac); // this is R/O field, so max value is irrelevant if (code_info->mh == 0xff && code_info->ml == 0xff && code_info->sh == 0xff && code_info->sl == 0xff) { snprintf(buffer, bufsz, "Cannot determine frequency or out of range"); } else { // this is R/O field, so max value is irrelevant // int khz = code_info->cur_value/1000; // int dec = code_info->cur_value % 1000; // snprintf(buffer, bufsz, "%d.%03d Khz", khz, dec); snprintf(buffer, bufsz, "%d hz", code_info->cur_value); } return true; } // This function implements the MCCS interpretation in MCCS 2.0 and 3.0. // However, the Dell U3011 returns a "nominal" value of 50 and a max // value of 100. Therefore, this function is not used. Instead, the // 6-axis hue values are interpreted as standard continuous values. // 0x9b..0xa0 static bool format_feature_detail_6_axis_hue( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { Byte vcp_code = code_info->vcp_code; Byte sl = code_info->sl; assert (0x9b <= vcp_code && vcp_code <= 0xa0); struct Names { Byte id; char * hue_name; char * more_name; char * less_name; }; struct Names names[] = { {0x9b, "red", "yellow", "magenta"}, {0x9c, "yellow", "green", "red"}, {0x9d, "green", "cyan", "yellow"}, {0x9e, "cyan", "blue", "green"}, {0x9f, "blue", "magenta", "cyan"}, {0xa0, "magenta", "red", "blue"}, }; struct Names curnames = names[vcp_code-0x9b]; if (sl < 0x7f) snprintf(buffer, bufsz, "%d: Shift towards %s (0x%02x, nominal-%d)", sl, curnames.less_name, sl, 0x7f-sl); else if (sl == 0x7f) snprintf(buffer, bufsz, "%d: Nominal (default) value (0x%02x)", sl, sl); else snprintf(buffer, bufsz, "%d Shift towards %s (0x%02x, nominal+%d)", sl, curnames.more_name, sl, sl-0x7f); return true; } // 0xae static bool format_feature_detail_xae_vertical_frequency( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0xae); if (code_info->mh == 0xff && code_info->ml == 0xff && code_info->sh == 0xff && code_info->sl == 0xff) { snprintf(buffer, bufsz, "Cannot determine frequency or out of range"); } else { // this is R/O field, so max value is irrelevant // code_info->cur_value; // vert frequency, in .01 hz int hz = code_info->cur_value/100; int dec = code_info->cur_value % 100; snprintf(buffer, bufsz, "%d.%02d hz", hz, dec); } return true; } // 0xbe static bool format_feature_detail_xbe_link_control( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { // test bit 0 // but in MCCS spec is bit 0 the high order bit or the low order bit?, // i.e. 0x80 or 0x01? // since spec refers to "Bits 7..1 reserved", implies that 0 is least // significant bit char * s = (code_info->sl & 0x01) ? "enabled" : "disabled"; snprintf(buffer, bufsz, "Link shutdown is %s (0x%02x)", s, code_info->sl); return true; } // 0xc0 static bool format_feature_detail_xc0_display_usage_time( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0xc0); guint usage_time; // DBGMSG("vcp_version=%d.%d", vcp_version.major, vcp_version.minor); // TODO: Control with Output_Level // v2 spec says this is a 2 byte value, says nothing about mh, ml if (vcp_version.major >= 3) { if (code_info->mh != 0x00) { SEVEREMSG("Data error. Mh byte = 0x%02x, should be 0x00 for display usage time", code_info->mh ); } usage_time = (code_info->ml << 16) | (code_info->sh << 8) | (code_info->sl); } else usage_time = (code_info->sh << 8) | (code_info->sl); snprintf(buffer, bufsz, "Usage time (hours) = %d (0x%06x) mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", usage_time, usage_time, code_info->mh, code_info->ml, code_info->sh, code_info->sl); return true; } // 0xc6 static bool format_feature_detail_x6c_application_enable_key( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0xc6); snprintf(buffer, bufsz, "0x%02x%02x", code_info->sh, code_info->sl); return true; } // 0xc8 static bool format_feature_detail_xc8_display_controller_type( Nontable_Vcp_Value * info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { bool debug = false; DBGTRC_STARTING(debug, TRACE_GROUP, ""); assert(info->vcp_code == 0xc8); bool ok = true; Byte mfg_id = info->sl; char *sl_msg = NULL; sl_msg = sl_value_table_lookup(xc8_display_controller_type_values, info->sl); if (!sl_msg) { sl_msg = "Unrecognized"; ok = true; } // gushort controller_number = info->ml << 8 | info->sh; // spec is inconsistent, controller number can either be ML/SH or MH/ML // observation suggests it's ml and sh snprintf(buffer, bufsz, "Mfg: %s (sl=0x%02x), controller number: mh=0x%02x, ml=0x%02x, sh=0x%02x", sl_msg, mfg_id, info->mh, info->ml, info->sh); DBGTRC_RET_BOOL(debug, TRACE_GROUP, ok, "buffer = |%s|", buffer); return ok; } // xc9, xdf static bool format_feature_detail_xc9_xdf_version( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { int version_number = code_info->sh; int revision_number = code_info->sl; snprintf(buffer, bufsz, "%d.%d", version_number, revision_number); return true; } // 0xca static bool format_feature_detail_xca_osd_button_control( Nontable_Vcp_Value * info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { if (vcp_version_eq(vcp_version, DDCA_VSPEC_V22)) { char * sl_name = sl_value_table_lookup(xca_v22_osd_button_sl_values, info->sl); if (!sl_name) sl_name = "Invalid value"; char * sh_name = sl_value_table_lookup(xca_v22_osd_button_sh_values, info->sh); if (!sh_name) sh_name = "Invalid value"; g_snprintf(buffer, bufsz,"%s (sl=0x%02x), %s (sh=0x%02x)", sl_name, info->sl, sh_name, info->sh); } else { char * sl_name = sl_value_table_lookup(xca_osd_values, info->sl); if (!sl_name) sl_name = "Invalid value"; g_snprintf(buffer, bufsz,"%s (sl=0x%02x)", sl_name, info->sl); } return true; } // 0xce static bool format_feature_detail_xce_aux_display_size( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz) { assert (code_info->vcp_code == 0xce); int rows = (code_info->sl & 0xc0) >> 6; int chars_per_row = code_info->sl & 0x3f; snprintf(buffer, bufsz, "Rows=%d, characters/row=%d (sl=0x%02x)", rows, chars_per_row, code_info->sl); return true; } ///////////////////////////////////////////////////////////////////////// // // Feature_Value_Entry tables (SL byte value lookup) // Used for Simple NC features // ///////////////////////////////////////////////////////////////////////// // {0x00,NULL} is the end of list marker. 0x00 might be a valid value, but NULL never is // 0x02 static DDCA_Feature_Value_Entry x02_new_control_values[] = { // values identical in 2.0, 3.0, 2.2 specs {0x01, "No new control values"}, {0x02, "One or more new control values have been saved"}, {0xff, "No user controls are present"}, {0x00, NULL} }; static DDCA_Feature_Value_Entry x03_soft_controls_values[] = { // values identical in 2.0, 3.0, 2.2 specs {0x00, "No button active"}, {0x01, "Button 1 active"}, {0x02, "Button 2 active"}, {0x03, "Button 3 active"}, {0x04, "Button 4 active"}, {0x05, "Button 5 active"}, {0x06, "Button 6 active"}, {0x07, "Button 7 active"}, {0xff, "No user controls are present"}, {0x00, NULL} }; // 0x14 static DDCA_Feature_Value_Entry x14_color_preset_absolute_values[] = { {0x01, "sRGB"}, {0x02, "Display Native"}, {0x03, "4000 K"}, {0x04, "5000 K"}, {0x05, "6500 K"}, {0x06, "7500 K"}, {0x07, "8200 K"}, {0x08, "9300 K"}, {0x09, "10000 K"}, {0x0a, "11500 K"}, {0x0b, "User 1"}, {0x0c, "User 2"}, {0x0d, "User 3"}, {0x00, NULL} // end of list marker }; // MH byte for V2.2, V3.0 static DDCA_Feature_Value_Entry x14_color_preset_tolerances[] = { {0x00, "Unspecified"}, {0x01, "1%"}, {0x02, "2%"}, {0x03, "3%"}, {0x04, "4%"}, {0x05, "5%"}, {0x06, "6%"}, {0x07, "7%"}, {0x08, "8%"}, {0x09, "9%"}, {0x0a, "10%"}, {0x00, NULL} // end of list marker }; // 0x1e, 0x1f static DDCA_Feature_Value_Entry x1e_x1f_auto_setup_values[] = { {0x00, "Auto setup not active"}, {0x01, "Performing auto setup"}, // end of values for 0x1e, v2.0 {0x02, "Enable continuous/periodic auto setup"}, {0x00, NULL} // end of list marker }; // 0x60: These are MCCS V2 values. In V3, x60 is type table. // see also EloView Remote Mgt Local Cmd Set document DDCA_Feature_Value_Entry x60_v2_input_source_values[] = { {0x01, "VGA-1"}, // aka Analog video (R/G/B) 1 {0x02, "VGA-2"}, {0x03, "DVI-1"}, {0x04, "DVI-2"}, {0x05, "Composite video 1"}, {0x06, "Composite video 2"}, {0x07, "S-Video-1"}, {0x08, "S-Video-2"}, {0x09, "Tuner-1"}, {0x0a, "Tuner-2"}, {0x0b, "Tuner-3"}, {0x0c, "Component video (YPrPb/YCrCb) 1"}, {0x0d, "Component video (YPrPb/YCrCb) 2"}, {0x0e, "Component video (YPrPb/YCrCb) 3"}, // end of v2.0 values // remaining values in v2.2 spec, assume also valid for v2.1 {0x0f, "DisplayPort-1"}, {0x10, "DisplayPort-2"}, {0x11, "HDMI-1"}, {0x12, "HDMI-2"}, {0x00, NULL} }; // 0x63 DDCA_Feature_Value_Entry x63_speaker_select_values[] = { {0x00, "Front L/R"}, {0x01, "Side L/R"}, {0x02, "Rear L/R"}, {0x03, "Center/Subwoofer"}, {0x00, NULL} }; // 0x66 DDCA_Feature_Value_Entry x66_ambient_light_sensor_values[] = { {0x01, "Disabled"}, {0x02, "Enabled"}, {0x00, NULL} }; // 0x82: Horizontal Mirror DDCA_Feature_Value_Entry x82_horizontal_flip_values[] = { {0x00, "Normal mode"}, {0x01, "Mirrored horizontally mode"}, {0x00, NULL} }; // 0x84: Horizontal Mirror DDCA_Feature_Value_Entry x84_vertical_flip_values[] = { {0x00, "Normal mode"}, {0x01, "Mirrored vertically mode"}, {0x00, NULL} }; // 0x8b DDCA_Feature_Value_Entry x8b_tv_channel_values[] = { {0x01, "Increment channel"}, {0x02, "Decrement channel"}, {0x00, NULL} }; // 0x8d: Audio Mute static DDCA_Feature_Value_Entry x8d_tv_audio_mute_source_values[] = { {0x01, "Mute the audio"}, {0x02, "Unmute the audio"}, {0x00, NULL} }; // 0x8d: SH byte values only apply in v2.2 static DDCA_Feature_Value_Entry x8d_sh_blank_screen_values[] = { {0x01, "Blank the screen"}, {0x02, "Unblank the screen"}, {0x00, NULL} }; // 0x86: Display Scaling DDCA_Feature_Value_Entry x86_display_scaling_values[] = { {0x01, "No scaling"}, {0x02, "Max image, no aspect ration distortion"}, {0x03, "Max vertical image, no aspect ratio distortion"}, {0x04, "Max horizontal image, no aspect ratio distortion"}, // v 2.0 spec values end here {0x05, "Max vertical image with aspect ratio distortion"}, {0x06, "Max horizontal image with aspect ratio distortion"}, {0x07, "Linear expansion (compression) on horizontal axis"}, // Full mode {0x08, "Linear expansion (compression) on h and v axes"}, // Zoom mode {0x09, "Squeeze mode"}, {0x0a, "Non-linear expansion"}, // Variable {0x00, NULL} }; // 0x87: Sharpness algorithm - used only for v2.0 DDCA_Feature_Value_Entry x87_sharpness_values[] = { {0x01, "Filter function 1"}, {0x02, "Filter function 2"}, {0x03, "Filter function 3"}, {0x04, "Filter function 4"}, {0x00, NULL} }; // 0x94 DDCA_Feature_Value_Entry x94_audio_stereo_mode_values[] = { {0x00, "Speaker off/Audio not supported"}, {0x01, "Mono"}, {0x02, "Stereo"}, {0x03, "Stereo expanded"}, // end of v20 values // 3.0 values: {0x11, "SRS 2.0"}, {0x12, "SRS 2.1"}, {0x13, "SRS 3.1"}, {0x14, "SRS 4.1"}, {0x15, "SRS 5.1"}, {0x16, "SRS 6.1"}, {0x17, "SRS 7.1"}, {0x21, "Dolby 2.0"}, {0x22, "Dolby 2.1"}, {0x23, "Dolby 3.1"}, {0x24, "Dolby 4.1"}, {0x25, "Dolby 5.1"}, {0x26, "Dolby 6.1"}, {0x27, "Dolby 7.1"}, {0x31, "THX 2.0"}, {0x32, "THX 2.1"}, {0x33, "THX 3.1"}, {0x34, "THX 4.1"}, {0x35, "THX 5.1"}, {0x36, "THX 6.1"}, {0x37, "THX 7.1"}, // end of v3.0 values {0x00, NULL} }; // 0x99 DDCA_Feature_Value_Entry x99_window_control_values[] = { {0x00, "No effect"}, {0x01, "Off"}, {0x02, "On"}, {0x00, NULL} }; // 0xa2 DDCA_Feature_Value_Entry xa2_auto_setup_values[] = { {0x01, "Off"}, {0x02, "On"}, {0x00, NULL} }; // 0xa5 static DDCA_Feature_Value_Entry xa5_window_select_values[] = { {0x00, "Full display image area selected except active windows"}, {0x01, "Window 1 selected"}, {0x02, "Window 2 selected"}, {0x03, "Window 3 selected"}, {0x04, "Window 4 selected"}, {0x05, "Window 5 selected"}, {0x06, "Window 6 selected"}, {0x07, "Window 7 selected"}, {0x00, NULL} // terminator }; // 0xaa static DDCA_Feature_Value_Entry xaa_screen_orientation_values[] = { {0x01, "0 degrees"}, {0x02, "90 degrees"}, {0x03, "180 degrees"}, {0x04, "270 degrees"}, {0xff, "Display cannot supply orientation"}, {0x00, NULL} // terminator }; // 0xb0 static DDCA_Feature_Value_Entry xb0_settings_values[] = { {0x01, "Store current settings in the monitor"}, {0x02, "Restore factory defaults for current mode"}, {0x00, NULL} // termination entry }; // 0xb2 static DDCA_Feature_Value_Entry xb2_flat_panel_subpixel_layout_values[] = { {0x00, "Sub-pixel layout not defined"}, {0x01, "Red/Green/Blue vertical stripe"}, {0x02, "Red/Green/Blue horizontal stripe"}, {0x03, "Blue/Green/Red vertical stripe"}, {0x04, "Blue/Green/Red horizontal stripe"}, {0x05, "Quad pixel, red at top left"}, {0x06, "Quad pixel, red at bottom left"}, {0x07, "Delta (triad)"}, {0x08, "Mosaic"}, // end of v2.0 values {0x00, NULL} // terminator }; // 0xb6 static DDCA_Feature_Value_Entry xb6_v20_display_technology_type_values[] = { { 0x01, "CRT (shadow mask)"}, { 0x02, "CRT (aperture grill)"}, { 0x03, "LCD (active matrix)"}, // TFT in 2.0 { 0x04, "LCos"}, { 0x05, "Plasma"}, { 0x06, "OLED"}, { 0x07, "EL"}, { 0x08, "MEM"}, // MEM in 2.0 {0x00, NULL} // terminator }; // 0xb6 static DDCA_Feature_Value_Entry xb6_display_technology_type_values[] = { { 0x01, "CRT (shadow mask)"}, { 0x02, "CRT (aperture grill)"}, { 0x03, "LCD (active matrix)"}, // TFT in 2.0 { 0x04, "LCos"}, { 0x05, "Plasma"}, { 0x06, "OLED"}, { 0x07, "EL"}, { 0x08, "Dynamic MEM"}, // MEM in 2.0 { 0x09, "Static MEM"}, // not in 2.0 {0x00, NULL} // terminator }; // 0xc8 DDCA_Feature_Value_Entry xc8_display_controller_type_values[] = { {0x01, "Conexant"}, {0x02, "Genesis"}, {0x03, "Macronix"}, {0x04, "IDT"}, // was MRT, 2.2a and 3.0 update have IDT {0x05, "Mstar"}, {0x06, "Myson"}, {0x07, "Phillips"}, {0x08, "PixelWorks"}, {0x09, "RealTek"}, {0x0a, "Sage"}, {0x0b, "Silicon Image"}, {0x0c, "SmartASIC"}, {0x0d, "STMicroelectronics"}, {0x0e, "Topro"}, {0x0f, "Trumpion"}, {0x10, "Welltrend"}, {0x11, "Samsung"}, {0x12, "Novatek"}, {0x13, "STK"}, {0x14, "Silicon Optics"}, // added in 3.0 Update Document 3/20/2007 // end of MCCS 3.0 values, beginning of values added in 2.2: {0x15, "Texas Instruments"}, {0x16, "Analogix"}, {0x17, "Quantum Data"}, {0x18, "NXP Semiconductors"}, {0x19, "Chrontel"}, {0x1a, "Parade Technologies"}, {0x1b, "THine Electronics"}, {0x1c, "Trident"}, {0x1d, "Micros"}, // end of values added in MCCS 2.2 {0xff, "Not defined - a manufacturer designed controller"}, {0x00, NULL} // terminator }; DDCA_Feature_Value_Entry * pxc8_display_controller_type_values = xc8_display_controller_type_values; // 0xca static DDCA_Feature_Value_Entry xca_osd_values[] = { {0x01, "OSD Disabled"}, {0x02, "OSD Enabled"}, {0xff, "Display cannot supply this information"}, {0x00, NULL} // terminator }; // 0xca, v2.2 static DDCA_Feature_Value_Entry xca_v22_osd_button_sl_values[] = { {0x00, "Host OSD control unsupported"}, {0x01, "OSD disabled, button events enabled"}, {0x02, "OSD enabled, button events enabled"}, {0x03, "OSD disabled, button events disabled"}, {0xff, "Display cannot supply this information"}, {0x00, NULL} // terminator }; // 0xca, v2.2 static DDCA_Feature_Value_Entry xca_v22_osd_button_sh_values[] = { {0x00, "Host control of power unsupported"}, {0x01, "Power button disabled, power button events enabled"}, {0x02, "Power button enabled, power button events enabled"}, {0x03, "Power button disabled, power button events disabled"}, {0x00, NULL} // terminator }; // 0xcc // Note in v2.2 spec: // Typo in Version 2.1. 10h should read 0Ah. If a parser // encounters a display with MCCS v2.1 using 10h it should // auto-correct to 0Ah. static DDCA_Feature_Value_Entry xcc_osd_language_values[] = { {0x00, "Reserved value, must be ignored"}, {0x01, "Chinese (traditional, Hantai)"}, {0x02, "English"}, {0x03, "French"}, {0x04, "German"}, {0x05, "Italian"}, {0x06, "Japanese"}, {0x07, "Korean"}, {0x08, "Portuguese (Portugal)"}, {0x09, "Russian"}, {0x0a, "Spanish"}, // end of MCCS v2.0 values {0x0b, "Swedish"}, {0x0c, "Turkish"}, {0x0d, "Chinese (simplified / Kantai)"}, {0x0e, "Portuguese (Brazil)"}, {0x0f, "Arabic"}, {0x10, "Bulgarian "}, {0x11, "Croatian"}, {0x12, "Czech"}, {0x13, "Danish"}, {0x14, "Dutch"}, {0x15, "Estonian"}, {0x16, "Finnish"}, {0x17, "Greek"}, {0x18, "Hebrew"}, {0x19, "Hindi"}, {0x1a, "Hungarian"}, {0x1b, "Latvian"}, {0x1c, "Lithuanian"}, {0x1d, "Norwegian "}, {0x1e, "Polish"}, {0x1f, "Romanian "}, {0x20, "Serbian"}, {0x21, "Slovak"}, {0x22, "Slovenian"}, {0x23, "Thai"}, {0x24, "Ukranian"}, {0x25, "Vietnamese"}, {0x00, NULL} // end of list marker }; // TODO: consolidate with x60_v2_input_source_values // 0xd0: These are MCCS V2 values. need to check V3 DDCA_Feature_Value_Entry xd0_v2_output_select_values[] = { {0x01, "Analog video (R/G/B) 1"}, {0x02, "Analog video (R/G/B) 2"}, {0x03, "Digital video (TDMS) 1"}, {0x04, "Digital video (TDMS) 22"}, {0x05, "Composite video 1"}, {0x06, "Composite video 2"}, {0x07, "S-Video-1"}, {0x08, "S-Video-2"}, {0x09, "Tuner-1"}, {0x0a, "Tuner-2"}, {0x0b, "Tuner-3"}, {0x0c, "Component video (YPrPb/YCrCb) 1"}, {0x0d, "Component video (YPrPb/YCrCb) 2"}, {0x0e, "Component video (YPrPb/YCrCb) 3"}, // end of v2.0 values // remaining values in v2.2 spec, assume also valid for v2.1 // TODO: CHECK {0x0f, "DisplayPort-1"}, {0x10, "DisplayPort-2"}, {0x11, "HDMI-1"}, {0x12, "HDMI-2"}, {0x00, NULL} }; // 0xd6 static DDCA_Feature_Value_Entry xd6_power_mode_values[] = { {0x01, "DPM: On, DPMS: Off"}, {0x02, "DPM: Off, DPMS: Standby"}, {0x03, "DPM: Off, DPMS: Suspend"}, {0x04, "DPM: Off, DPMS: Off" }, {0x05, "Write only value to turn off display"}, {0x00, NULL} // termination entry }; // 0xd7 static DDCA_Feature_Value_Entry xd7_aux_power_output_values[] = { {0x01, "Disable auxiliary power"}, {0x02, "Enable Auxiliary power"}, {0x00, NULL} // termination entry }; // 0xda static DDCA_Feature_Value_Entry xda_scan_mode_values[] = { {0x00, "Normal operation"}, {0x01, "Underscan"}, {0x02, "Overscan"}, {0x03, "Widescreen" }, // in 2.0 spec, not in 3.0 {0x00, NULL} // termination entry }; // 0xdb static DDCA_Feature_Value_Entry xdb_image_mode_values[] = { {0x00, "No effect"}, {0x01, "Full mode"}, {0x02, "Zoom mode"}, {0x03, "Squeeze mode" }, {0x04, "Variable"}, {0x00, NULL} // termination entry }; static DDCA_Feature_Value_Entry xdc_display_application_values[] = { {0x00, "Standard/Default mode"}, {0x01, "Productivity"}, {0x02, "Mixed"}, {0x03, "Movie"}, {0x04, "User defined"}, {0x05, "Games"}, {0x06, "Sports"}, {0x07, "Professional (all signal processing disabled)"}, {0x08, "Standard/Default mode with intermediate power consumption"}, {0x09, "Standard/Default mode with low power consumption"}, {0x0a, "Demonstration"}, {0xf0, "Dynamic contrast"}, {0x00, NULL} // terminator }; #pragma GCC diagnostic push // not suppressing warning, why?, but removing static does avoid warning #pragma GCC diagnostic ignored "-Wunused-variable" // 0xde // write-only feature DDCA_Feature_Value_Entry xde_wo_operation_mode_values[] = { {0x01, "Stand alone"}, {0x02, "Slave (full PC control)"}, {0x00, NULL} // termination entry }; #pragma GCC diagnostic pop //////////////////////////////////////////////////////////////////////// // // Virtual Control Panel (VCP) Feature Code Master Table // //////////////////////////////////////////////////////////////////////// //TODO: // In 2.0 spec, only the first letter of the first word of a name is capitalized // In 3.0/2.2, the first letter of each word of a name is capitalized // Need to make this consistent throughout the table /** Feature Code Master Table */ VCP_Feature_Table_Entry vcp_code_table[] = { { .code=0x01, // defined in 2.0, identical in 3.0 .vcp_spec_groups = VCP_SPEC_MISC, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Causes a CRT to perform a degauss cycle", .v20_flags = DDCA_WO |DDCA_WO_NC, .v20_name = "Degauss", }, { .code=0x02, .vcp_spec_groups = VCP_SPEC_MISC, // defined in 2.0, identical in 3.0, 2.2 .nontable_formatter = format_feature_detail_x02_new_control_value, // ?? .default_sl_values = x02_new_control_values, // ignored, hardcoded in nontable_formatter .desc = "Indicates that a display user control (other than power) has been " "used to change and save (or autosave) a new value.", .v20_flags = DDCA_RW | DDCA_COMPLEX_NC, .v20_name = "New control value", }, { .code=0x03, // defined in 2.0, identical in 3.0 .vcp_spec_groups = VCP_SPEC_MISC, .default_sl_values = x03_soft_controls_values, .desc = "Allows display controls to be used as soft keys", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Soft controls", }, { .code=0x04, // Defined in 2.0, identical in 3.0 .vcp_spec_groups = VCP_SPEC_PRESET, .desc = "Restore all factory presets including brightness/contrast, " "geometry, color, and TV defaults.", .vcp_subsets = VCP_SUBSET_COLOR, // but note WO .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Restore factory defaults", }, { .code=0x05, // Defined in 2.0, identical in 3.0 .vcp_spec_groups = VCP_SPEC_PRESET, .vcp_subsets = VCP_SUBSET_COLOR, // but note WO .desc = "Restore factory defaults for brightness and contrast", .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Restore factory brightness/contrast defaults", }, { .code=0x06, // Defined in 2.0, identical in 3.0 .vcp_spec_groups = VCP_SPEC_PRESET, .desc = "Restore factory defaults for geometry adjustments", .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Restore factory geometry defaults", }, { .code=0x08, // Defined in 2.0, identical in 3.0 .vcp_spec_groups = VCP_SPEC_PRESET, .vcp_subsets = VCP_SUBSET_COLOR, // but note WO .desc = "Restore factory defaults for color settings.", .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Restore color defaults", }, { .code=0x0A, // Defined in 2.0, identical in 3.0 .vcp_spec_groups = VCP_SPEC_PRESET, .vcp_subsets = VCP_SUBSET_TV, .desc = "Restore factory defaults for TV functions.", .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Restore factory TV defaults", }, { .code=0x0b, .vcp_spec_groups = VCP_SPEC_IMAGE, // Defined in 2.0 .nontable_formatter=format_feature_detail_x0b_color_temperature_increment, // from 2.0 spec: // .desc="Allows the display to specify the minimum increment in which it can " // "adjust the color temperature.", // simpler: .desc="Color temperature increment used by feature 0Ch Color Temperature Request", .vcp_subsets = VCP_SUBSET_COLOR, .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .v20_name="Color temperature increment", }, { .code=0x0c, //.name="Color temperature request", .vcp_spec_groups = VCP_SPEC_IMAGE, // Defined in 2.0 .nontable_formatter=format_feature_detail_x0c_color_temperature_request, .desc="Specifies a color temperature (degrees Kelvin)", // my desc .vcp_subsets = VCP_SUBSET_COLOR, .v20_flags = DDCA_RW | DDCA_COMPLEX_CONT, .v20_name="Color temperature request", }, { .code=0x0e, // Defined in 2.0 .vcp_spec_groups = VCP_SPEC_IMAGE, .desc="Increase/decrease the sampling clock frequency.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Clock", }, { .code=0x10, .vcp_spec_groups = VCP_SPEC_IMAGE, // Defined in 2.0, name changed in 3.0, what is it in 2.1? //.name="Luminosity", .desc="Increase/decrease the brightness of the image.", .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Brightness", .v30_name = "Luminosity", }, { .code=0x11, // not in 2.0, is in 3.0, assume introduced in 2.1 .vcp_spec_groups = VCP_SPEC_IMAGE, .nontable_formatter=format_feature_detail_debug_bytes, .desc = "Select contrast enhancement algorithm respecting flesh tone region", .vcp_subsets = VCP_SUBSET_COLOR, .v21_flags = DDCA_RW | DDCA_COMPLEX_NC, .v21_name = "Flesh tone enhancement", }, { .code=0x12, .vcp_spec_groups = VCP_SPEC_IMAGE, // Defined in 2.0, identical in 3.0 .desc="Increase/decrease the contrast of the image.", .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Contrast", }, { .code=0x13, .vcp_spec_groups = VCP_SPEC_IMAGE, // not in 2.0, is in 3.0, assume first defined in 2.1 // deprecated in 2.2 .nontable_formatter=format_feature_detail_debug_bytes, .desc = "Increase/decrease the specified backlight control value", .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v21_flags = DDCA_RW | DDCA_COMPLEX_CONT, .v21_name = "Backlight control", // DDCA_RW | DDCA_COMPLEX_CONT included in v22 flags so that // information is available in ddcui to display, also in // case the feature is implemented on a V22 monitor, even though // it is deprecated .v22_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_COMPLEX_CONT, }, { .code=0x14, .vcp_spec_groups = VCP_SPEC_IMAGE, // Defined in 2.0, different in 3.0, 2.2 // what is appropriate choice for 2.1 ? // interpretation varies depending on VCP version .nontable_formatter=format_feature_detail_x14_select_color_preset, .default_sl_values= x14_color_preset_absolute_values, // ignored, referenced in nontable_formatter .desc="Select a specified color temperature", .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Select color preset", .v30_flags = DDCA_RW | DDCA_COMPLEX_NC, .v22_flags = DDCA_RW | DDCA_COMPLEX_NC, }, { .code=0x16, .vcp_spec_groups = VCP_SPEC_IMAGE, .desc="Increase/decrease the luminesence of red pixels", // my simplification .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Video gain: Red", }, { .code=0x17, .vcp_spec_groups = VCP_SPEC_IMAGE, // not in 2.0, is in 3.0 and 2.2, assume valid for 2.1 .desc="Increase/decrease the degree of compensation", // my simplification .vcp_subsets = VCP_SUBSET_COLOR, .v21_flags = DDCA_RW | DDCA_STD_CONT, .v21_name = "User color vision compensation", }, { .code=0x18, .vcp_spec_groups = VCP_SPEC_IMAGE, .desc="Increase/decrease the luminesence of green pixels", // my simplification .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Video gain: Green", }, { .code=0x1a, .vcp_spec_groups = VCP_SPEC_IMAGE, .desc="Increase/decrease the luminesence of blue pixels", // my simplification .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Video gain: Blue", }, { .code=0x1c, .vcp_spec_groups = VCP_SPEC_IMAGE, // defined in 2.0, identical in 3.0 .desc="Increase/decrease the focus of the image", // my simplification .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Focus", }, { .code=0x1e, // Done .vcp_spec_groups = VCP_SPEC_IMAGE, // 2.0, 3.0, 2.2 // Defined in 2.0, additional value in 3.0, 2.2 .default_sl_values = x1e_x1f_auto_setup_values, .desc="Perform autosetup function (H/V position, clock, clock phase, " "A/D converter, etc.", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Auto setup", }, { .code=0x1f, // Done // not defined in 2.0, is defined in 3.0, 2.2, assume introduced in 2.1 .vcp_spec_groups = VCP_SPEC_IMAGE, // 3.0 .default_sl_values = x1e_x1f_auto_setup_values, .desc="Perform color autosetup function (R/G/B gain and offset, A/D setup, etc. ", .vcp_subsets = VCP_SUBSET_COLOR, .v21_flags = DDCA_RW | DDCA_SIMPLE_NC, .v21_name = "Auto color setup", }, { .code=0x20, // Done // Group 8.4 Geometry, identical in 2.0, 3.0, 2.2 except for name // When did name change to include "(phase)"? Assuming 2.1 .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increasing (decreasing) this value moves the image toward " "the right (left) of the display.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Horizontal Position", .v21_name="Horizontal Position (Phase)", }, { .code=0x22, // Done // Group 8.4 Geometry, identical in 2.0, 3.0, 2.2 .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increase/decrease the width of the image.", .v20_name="Horizontal Size", .v20_flags = DDCA_RW | DDCA_STD_CONT, }, { .code=0x24, // Done // Group 8.4 Geometry, identical in 2.0, 3.0, 2.2 .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increasing (decreasing) this value causes the right and left " "sides of the image to become more (less) convex.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Horizontal Pincushion", }, { .code=0x26, // Done // Group 8.4 Geometry, identical in 2.0, 3.0, 2.2 .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increasing (decreasing) this value moves the center section " "of the image toward the right (left) side of the display.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Horizontal Pincushion Balance", }, { .code=0x28, // Done // Group 8.4 Geometry, name changed in 3.0 & 2.2 vs 2.0 what should it be for 2.1? // assume it changed in 2.1 .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // description identical in 3.0, 2.0 even though name changed .desc = "Increasing (decreasing) this value shifts the red pixels to " "the right (left) and the blue pixels left (right) across the " "image with respect to the green pixels.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Horizontal Convergence", .v21_name="Horizontal Convergence R/B", }, { .code=0x29, // Done // not in 2.0, when was this added? 2.1 or 3.0? assuming 2.1 .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increasing (decreasing) this value shifts the magenta pixels to " "the right (left) and the green pixels left (right) across the " "image with respect to the magenta (sic) pixels.", .v21_name="Horizontal Convergence M/G", .v21_flags=DDCA_RW | DDCA_STD_CONT, }, { .code = 0x2a, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry, identical in 3.0, 2.2 .desc = "Increase/decrease the density of pixels in the image center.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Horizontal Linearity", }, { .code = 0x2c, // Done // Group 8.4 Geometry .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increasing (decreasing) this value shifts the density of pixels " "from the left (right) side to the right (left) side of the image.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Horizontal Linearity Balance", }, { .code=0x2e, .vcp_spec_groups = VCP_SPEC_IMAGE, // not defined in 2.0, is defined in 3.0 // assume new in 2.1 .vcp_subsets = VCP_SUBSET_COLOR, .nontable_formatter=format_feature_detail_debug_bytes, .desc = "Gray Scale Expansion", .v21_flags = DDCA_RW | DDCA_COMPLEX_NC, .v21_name = "Gray scale expansion", }, { .code=0x30, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increasing (decreasing) this value moves the image toward " "the top (bottom) edge of the display.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Vertical Position", .v21_name="Vertical Position (Phase)", }, { .code=0x32, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry. Did name change with 2.1 or 3.0/2.2? - assuming 2.1 .desc = "Increase/decreasing the height of the image.", .v20_flags=DDCA_RW | DDCA_STD_CONT, .v20_name="Vertical Size", }, { .code=0x34, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry. Identical in 2.0, 3.0, 2.2 .desc = "Increasing (decreasing) this value will cause the top and " "bottom edges of the image to become more (less) convex.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Vertical Pincushion", }, { .code=0x36, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, .desc = "Increasing (decreasing) this value will move the center " "section of the image toward the top (bottom) edge of the display.", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Vertical Pincushion Balance", }, { .code=0x38, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry. Assume name changed with 2.1 .desc = "Increasing (decreasing) this value shifts the red pixels up (down) " "across the image and the blue pixels down (up) across the image " "with respect to the green pixels.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Vertical Convergence", .v21_name="Vertical Convergence R/B", }, { .code=0x39, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry. Not in 2.0. Assume added in 2.1 .desc = "Increasing (decreasing) this value shifts the magenta pixels up (down) " "across the image and the green pixels down (up) across the image " "with respect to the magenta (sic) pixels.", .v21_name="Vertical Convergence M/G", .v21_flags= DDCA_RW | DDCA_STD_CONT, }, { .code=0x3a, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry .desc = "Increase/decease the density of scan lines in the image center.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name = "Vertical Linearity", }, { .code=0x3c, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry .desc = "Increase/decrease the density of scan lines in the image center.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name = "Vertical Linearity Balance", }, { .code=0x3e, .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_MISC, // 2.0: MISC // Defined in 2.0, identical in 3.0 .desc="Increase/decrease the sampling clock phase shift", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Clock phase", }, { .code=0x40, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // When did name change from 2.0? assume 2.1 //.name="Horizontal Parallelogram", .desc = "Increasing (decreasing) this value shifts the top section of " "the image to the right (left) with respect to the bottom section " "of the image.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Key Balance", // 2.0 .v21_name="Horizontal Parallelogram", }, { .code=0x41, .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // not defined in 2.0, assume defined in 2.1 // 3.0 doc has same description for x41 as x40, is this right? // 2.2 spec has the same identical description in x41 and x40 .desc = "Increasing (decreasing) this value shifts the top section of " "the image to the right (left) with respect to the bottom section " "of the image. (sic)", .v21_flags= DDCA_RW | DDCA_STD_CONT, .v21_name="Vertical Parallelogram", }, { .code=0x42, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // When did name change from 2.0? assume 2.1 .desc = "Increasing (decreasing) this value will increase (decrease) the " "ratio between the horizontal size at the top of the image and the " "horizontal size at the bottom of the image.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Horizontal Trapezoid", .v21_name="Horizontal Keystone", // ?? }, { .code=0x43, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry // When did name change from 2.0? assume 2.1 .desc = "Increasing (decreasing) this value will increase (decrease) the " "ratio between the vertical size at the left of the image and the " "vertical size at the right of the image.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Vertical Trapezoid", .v21_name="Vertical Keystone", // ?? }, { .code=0x44, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry // When did name change from 2.0? assume 2.1 .desc = "Increasing (decreasing) this value rotates the image (counter) " "clockwise around the center point of the screen.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Tilt (rotation)", .v21_name="Rotation", // ?? }, { .code=0x46, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry // When did name change from 2.0? assume 2.1 .desc = "Increase/decrease the distance between the left and right sides " "at the top of the image.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Top Corner", .v21_name="Top Corner Flare", // ?? }, { .code=0x48, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // name is different in 3.0, assume changed in 2.1 //.name="Placeholder", //.flags=VCP_RW | VCP_CONTINUOUS, // .nontable_formatter=format_feature_detail_standard_continuous, .desc = "Increasing (decreasing) this value moves the top of the " "image to the right (left).", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Top Corner Balance", .v21_name="Top Corner Hook", }, { .code=0x4a, //Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // Group 8.4 Geometry // When did name change from 2.0? assume 2.1 .desc = "Increase/decrease the distance between the left " "and right sides at the bottom of the image.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Bottom Corner", .v21_name="Bottom Corner Flare", // ?? }, { .code=0x4c, // Done .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // name is different in 3.0, assume changed in 2.1 .desc = "Increasing (decreasing) this value moves the bottom end of the " "image to the right (left).", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Bottom Corner Balance", .v21_name="Bottom Corner Hook", }, // code 0x4e: // what is going on with 0x4e? // In 2.0 spec, the cross ref lists it as Trapezoid, in Table Geometry // However, the Geometry table lists 7E as Trapezoid // In 3.0 and 2.2, neither 4E or 7E are defined // code: 0x50 // listed as Keystone, table GEOMETRY in 2.0 // But Geometry table lists 0x80 as being keystone, not 0x4e // In 3.0 and 2.2, neither x50 nor x80 are defined { .code=0x52, .vcp_spec_groups = VCP_SPEC_MISC, // defined in 2.0, 3.0 has extended consistent explanation .nontable_formatter = format_feature_detail_sl_byte, // TODO: write proper function .desc= "Read id of one feature that has changed, 0x00 indicates no more", // my desc .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .v20_name = "Active control", }, { .code= 0x54, .vcp_spec_groups = VCP_SPEC_MISC, // not defined in 2.0, defined in 3.0, 2.2 identical to 3.0, assume new in 2.1 .nontable_formatter=format_feature_detail_debug_bytes, // TODO: write formatter .desc = "Controls features aimed at preserving display performance", .v21_flags = DDCA_RW | DDCA_COMPLEX_NC, .v21_name = "Performance Preservation", }, { .code=0x56, .vcp_spec_groups = VCP_SPEC_IMAGE, // defined in 2.0 //.name="Horizontal Moire", //.flags=VCP_RW | VCP_CONTINUOUS, // .nontable_formatter=format_feature_detail_standard_continuous, .desc="Increase/decrease horizontal moire cancellation.", // my simplification //.global_flags = VCP_RW, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Horizontal Moire", }, { .code=0x58, .vcp_spec_groups = VCP_SPEC_IMAGE, // defined in 2.0 .desc="Increase/decrease vertical moire cancellation.", // my simplification .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name="Vertical Moire", }, { .code=0x59, // DONE .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR, // not in 2.0, defined in 3.0, assume new as of 2.1 // observed in Dell U3011, which is VCP 2.1 // .nontable_formatter=format_feature_detail_sl_byte, // Per spec, values range from x00..xff // On U3011 monitor, values range from 0..100, returned max value is 100 // Change the .desc to fit observed reality // Same comments apply to other saturation codes //.desc = "Value < 127 decreases red saturation, 127 nominal (default) value, " // "> 127 increases red saturation", .desc="Increase/decrease red saturation", .v21_flags = DDCA_RW | DDCA_STD_CONT, .v21_name = "6 axis saturation: Red", }, { .code=0x5a, // DONE .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR, // not in 2.0, defined in 3.0, assume new as of 2.1 // .nontable_formatter=format_feature_detail_sl_byte, // .desc = "Value < 127 decreases yellow saturation, 127 nominal (default) value, " // "> 127 increases yellow saturation", .desc="Increase/decrease yellow saturation", .v21_flags = DDCA_RW | DDCA_STD_CONT, .v21_name = "6 axis saturation: Yellow", }, { .code=0x5b, // DONE .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR, // not in 2.0, defined in 3.0, assume new as of 2.1 // .nontable_formatter=format_feature_detail_sl_byte, // .desc = "Value < 127 decreases green saturation, 127 nominal (default) value, " // "> 127 increases green saturation", .desc="Increase/decrease green saturation", .v21_flags = DDCA_RW | DDCA_STD_CONT, .v21_name = "6 axis saturation: Green", }, { .code=0x5c, // DONE .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR, // not in 2.0, defined in 3.0, assume new as of 2.1 // .nontable_formatter=format_feature_detail_sl_byte, // .desc = "Value < 127 decreases cyan saturation, 127 nominal (default) value, " // "> 127 increases cyan saturation", .desc="Increase/decrease cyan saturation", .v21_flags = DDCA_RW | DDCA_STD_CONT, .v21_name = "6 axis saturation: Cyan", }, { .code=0x5d, // DONE .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR, // not in 2.0, defined in 3.0, assume new as of 2.1 // .nontable_formatter=format_feature_detail_sl_byte, // .desc = "Value < 127 decreases blue saturation, 127 nominal (default) value, " // "> 127 increases blue saturation", .desc="Increase/decrease blue saturation", .v21_flags = DDCA_RW | DDCA_STD_CONT, .v21_name = "6 axis saturation: Blue", }, { .code=0x5e, // DONE .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR, // not in 2.0, defined in 3.0, assume new as of 2.1 // .nontable_formatter=format_feature_detail_sl_byte, // .desc = "Value < 127 decreases magenta saturation, 127 nominal (default) value, " // "> 127 increases magenta saturation", .desc="Increase/decrease magenta saturation", .v21_flags = DDCA_RW | DDCA_STD_CONT, .v21_name = "6 axis saturation: Magenta", }, { .code=0x60, .vcp_spec_groups = VCP_SPEC_MISC, // MCCS 2.0, 2.2: NC, MCCS 3.0: T .default_sl_values = x60_v2_input_source_values, // used for all but v3.0 .desc = "Selects active video source", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Input Source", .v30_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v22_flags = DDCA_RW | DDCA_SIMPLE_NC }, { .code=0x62, .vcp_spec_groups = VCP_SPEC_AUDIO, .vcp_subsets = VCP_SUBSET_AUDIO, // is in 2.0, special coding as of 3.0 assume changed as of 3.0 // In MCCS spec v2.2a, summary table 7.4 Audio Adjustments lists this // feature as type C, but detailed documentation in section // 8.6 Audio Adjustments lists it as type NC and documents // reserved values. Treat as NC. // .nontable_formatter=format_feature_detail_standard_continuous, .nontable_formatter=format_feature_detail_x62_audio_speaker_volume, // requires special handling for V3, mix of C and NC, SL byte only .desc = "Adjusts speaker volume", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v30_flags = DDCA_RW | DDCA_NC_CONT, .v22_flags = DDCA_RW | DDCA_NC_CONT, .v20_name = "Audio speaker volume", }, { .code=0x63, .vcp_spec_groups = VCP_SPEC_AUDIO, // not in 2.0, is in 3.0, assume new as of 2.1 .vcp_subsets = VCP_SUBSET_AUDIO, .desc="Selects a group of speakers", .v21_flags = DDCA_RW | DDCA_SIMPLE_NC, .default_sl_values = x63_speaker_select_values, .v21_name = "Speaker Select", }, { .code=0x64, .vcp_spec_groups = VCP_SPEC_AUDIO, // is in 2.0, n. unlike x62, this code is identically defined in 2.0, 30 .vcp_subsets = VCP_SUBSET_AUDIO, .desc = "Increase/decrease microphone gain", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Audio: Microphone Volume", }, { .code=0x66, .vcp_spec_groups = VCP_SPEC_MISC, // not in 2.0, assume new in 2.1 // however, seen on NEC PA241W, which reports VCP version as 2.0 .nontable_formatter=format_feature_detail_debug_bytes, .desc = "Enable/Disable ambient light sensor", .v21_flags = DDCA_RW | DDCA_SIMPLE_NC, .v21_name = "Ambient light sensor", .default_sl_values = x66_ambient_light_sensor_values, }, { .code=0x6b, // First defined in MCCS 2.2, .vcp_spec_groups=VCP_SPEC_IMAGE, .desc="Increase/decrease the white backlight level", .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v22_name = "Backlight Level: White", .v22_flags = DDCA_RW | DDCA_STD_CONT, }, { .code=0x6c, .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // Defined in 2.0, name change in ? //.name="Video black level: Red", // .nontable_formatter=format_feature_detail_standard_continuous, .desc="Increase/decrease the black level of red pixels", // my simplification .v20_flags = DDCA_RW |DDCA_STD_CONT, .v20_name = "Video black level: Red", }, { .code=0x6d, // First defined in MCCS 2.2, .vcp_spec_groups=VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .desc="Increase/decrease the red backlight level", .v22_name = "Backlight Level: Red", .v22_flags = DDCA_RW | DDCA_STD_CONT, }, { .code=0x6e, .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // Defined in 2.0, name change in ? .desc="Increase/decrease the black level of green pixels", // my simplification .v20_flags = DDCA_RW |DDCA_STD_CONT, .v20_name = "Video black level: Green", }, { .code=0x6f, // First defined in MCCS 2.2, .vcp_spec_groups=VCP_SPEC_IMAGE, .desc="Increase/decrease the green backlight level", // .nontable_formatter=format_feature_detail_standard_continuous, .v22_name = "Backlight Level: Green", .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v22_flags = DDCA_RW | DDCA_STD_CONT, }, { .code=0x70, .vcp_spec_groups = VCP_SPEC_IMAGE, // Defined in 2.0, name change in ? .desc="Increase/decrease the black level of blue pixels", // my simplification .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v20_flags = DDCA_RW |DDCA_STD_CONT, .v20_name = "Video black level: Blue", }, { .code=0x71, // First defined in MCCS 2.2, .vcp_spec_groups=VCP_SPEC_IMAGE, .desc="Increase/decrease the blue backlight level", .v22_name = "Backlight Level: Blue", .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, .v22_flags = DDCA_RW | DDCA_STD_CONT, }, { .code=0x72, // 2.0: undefined, 3.0 & 2.2: defined, assume defined in 2.1 .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_COLOR, .desc="Select relative or absolute gamma", // .nontable_formatter=format_feature_detail_debug_sl_sh, // TODO implement function .nontable_formatter=format_feature_detail_x72_gamma, .v21_flags = DDCA_RW | DDCA_COMPLEX_NC, .v21_name = "Gamma", }, { .code=0x73, .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_LUT, // VCP_SPEC_MISC in 2.0, VCP_SPEC_IMAGE in 3.0, 2.1? 2.2 .table_formatter=format_feature_detail_x73_lut_size, .desc = "Provides the size (number of entries and number of bits/entry) " "for the Red, Green, and Blue LUT in the display.", .v20_flags = DDCA_RO| DDCA_NORMAL_TABLE, .v20_name = "LUT Size", }, { .code=0x74, // VCP_SPEC_MISC in 2.0, VCP_SPEC_IMAGE in 3.0, 2.2 .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_LUT, .table_formatter = default_table_feature_detail_function, .desc = "Writes a single point within the display's LUT, reads a single point from the LUT", .v20_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v20_name = "Single point LUT operation", }, { .code=0x75, // VCP_SPEC_MISC in 2.0, VCP_SPEC_IMAGE in 3.0, 2.2 .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_LUT, .table_formatter = default_table_feature_detail_function, .desc = "Load (read) multiple values into (from) the display's LUT", .v20_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v20_name = "Block LUT operation", }, { .code=0x76, // defined in 2.0, 3.0 .vcp_spec_groups = VCP_SPEC_MISC, .vcp_subsets = VCP_SUBSET_LUT, .desc = "Initiates a routine resident in the display", .v20_flags = DDCA_WO | DDCA_WO_TABLE, .v20_name = "Remote Procedure Call", }, { .code=0x78, .vcp_spec_groups = VCP_SPEC_MISC, // Not in 2.0 // defined in 3.0, 2.2 - name and description vary, but content identical // what to do about 2.1? assume it's defined in 2.1 and identical to 3.0 .desc = "Causes a selected 128 byte block of Display Identification Data " "(EDID or Display ID) to be read", .v21_flags = DDCA_RO | DDCA_NORMAL_TABLE, .v21_name = "EDID operation", .v30_flags = DDCA_RO | DDCA_NORMAL_TABLE, .v30_name = "EDID operation", .v22_flags = DDCA_RO | DDCA_NORMAL_TABLE, .v22_name = "Display Identification Operation", }, { .code=0x7a, .vcp_spec_groups = VCP_SPEC_IMAGE, // v2.0 // defined in 2.0, not in 3.0 or 2.2, what to do for 2.1? .desc="Increase/decrease the distance to the focal plane of the image", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Adjust Focal Plane", .v30_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_STD_CONT, .v22_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_STD_CONT, }, { .code=0x7c, .vcp_spec_groups = VCP_SPEC_IMAGE, // defined in 2.0, is in 3.0 // my simplification, merger of 2.0 and 3.0 descriptions: .desc="Increase/decrease the distance to the zoom function of the projection lens (optics)", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Adjust Zoom", }, { .code=0x7e, // TODO: CHECK 2.2 SPEC // Is this really a valid v2.0 code? See earlier comments // Is in V2.0 Geometry table, but not cross reference. .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // data from v2.0 spec, not in v3.0 spec // when was it deleted? v3.0 or v2.1? For safety assume 3.0 .desc = "Increase/decrease the trapezoid distortion in the image", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v30_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_STD_CONT, .v22_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_STD_CONT, .v20_name="Trapezoid", }, { .code=0x80, // TODO: CHECK 2.2 SPEC // The v2.0 cross ref lists 0x50 as Keystone, group Geometry // However, the Geometry table lists Keystone as x50, not x80 // Neither x50 nor x80 are defined in v3.0 .vcp_spec_groups = VCP_SPEC_GEOMETRY, .vcp_subsets = VCP_SUBSET_CRT, // in 2.0 spec, not in 3.0, or 2.2 // assume not in 2.1 .desc="Increase/decrease the keystone distortion in the image.", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Keystone", .v21_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_STD_CONT, }, { .code=0x82, .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_GEOMETRY, // 2.0: Image, 3.0: Geometry .default_sl_values = x82_horizontal_flip_values, .desc="Flip picture horizontally", // DESIGN ISSUE!!! // This feature is WO in 2.0 spec, RW in 3.0, what is it in 2.2 // implies cannot use global_flags to store RO/RW/WO .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "HorFlip", .v21_name = "Horizontal Mirror (Flip)", .v21_flags = DDCA_RW | DDCA_SIMPLE_NC, .v21_sl_values = x82_horizontal_flip_values, }, { .code=0x84, .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_GEOMETRY, // 2.0: Image, 3.0: Geometry .default_sl_values = x84_vertical_flip_values, // DESIGN ISSUE!!! // This feature is WO in 2.0 spec, RW in 3.0, what is it in 2.2 // implies cannot use global_flags to store RO/RW/WO .desc="Flip picture vertically", .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "VertFlip", .v21_name = "Vertical Mirror (Flip)", .v21_flags = DDCA_RW | DDCA_SIMPLE_NC, .v21_sl_values = x84_vertical_flip_values, }, { .code=0x86, // Done // v2.0 spec cross ref lists as MISC, but defined in IMAGE table, assume IMAGE .vcp_spec_groups = VCP_SPEC_IMAGE, // 2.0: IMAGE //.name="DisplayScaling", //.flags = VCP_RW | VCP_NON_CONT, .default_sl_values = x86_display_scaling_values, .desc = "Control the scaling (input vs output) of the display", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Display Scaling", }, { .code=0x87, // Done .vcp_spec_groups = VCP_SPEC_IMAGE , // 2.0 IMAGE, 3.0 Image, 2.2 Image // defined in 2.0, is C in 3.0 and 2.2, assume 2.1 is C as well .default_sl_values = x87_sharpness_values, // .desc = "Specifies one of a range of algorithms", .desc = "Selects one of a range of algorithms. " "Increasing (decreasing) the value must increase (decrease) " "the edge sharpness of image features.", .v20_flags=DDCA_RW | DDCA_SIMPLE_NC, .v20_name="Sharpness", .v21_flags=DDCA_RW | DDCA_STD_CONT, }, { .code=0x88, // 2.0 cross ref lists this as IMAGE, but defined in MISC table // 2.2: Image .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_CRT, // ??? .desc = "Increase (decrease) the velocity modulation of the horizontal " "scan as a function of the change in luminescence level", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Velocity Scan Modulation", }, { .code=0x8a, .vcp_spec_groups = VCP_SPEC_IMAGE, // 2.0, 2.2, 3.0 // Name differs in 3.0 vs 2.0, assume 2.1 same as 2.0 .vcp_subsets = VCP_SUBSET_TV | VCP_SUBSET_COLOR, .desc = "Increase/decrease the amplitude of the color difference " "components of the video signal", .v20_flags =DDCA_RW | DDCA_STD_CONT, .v20_name = "TV Color Saturation", .v21_name = "Color Saturation", }, { .code=0x8b, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .vcp_subsets = VCP_SUBSET_TV, .desc = "Increment (1) or decrement (2) television channel", .v20_flags=DDCA_WO | DDCA_WO_NC, .v20_name="TV Channel Up/Down", .default_sl_values=x8b_tv_channel_values, }, { .code = 0x8c, .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_IMAGE, // 2.0: SPEC, 2.2: IMAGE .vcp_subsets = VCP_SUBSET_TV, .desc = "Increase/decrease the amplitude of the high frequency components " "of the video signal", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "TV Sharpness", }, { .code=0x8d, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 // v3.0 same as v2.0 // v2.2 adds SH byte for screen blank .vcp_subsets = VCP_SUBSET_TV | VCP_SUBSET_AUDIO, .desc = "Mute/unmute audio, and (v2.2) screen blank", .nontable_formatter=format_feature_detail_x8d_mute_audio_blank_screen, .default_sl_values = x8d_tv_audio_mute_source_values, // ignored, table hardcoded in nontable_formatter .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Audio Mute", .v22_flags = DDCA_RW | DDCA_COMPLEX_NC, .v22_name = "Audio mute/Screen blank", }, { .code=0x8e, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .vcp_subsets = VCP_SUBSET_TV, .desc = "Increase/decrease the ratio between blacks and whites in the image", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "TV Contrast", }, { .code=0x8f, .vcp_spec_groups = VCP_SPEC_AUDIO, // v2.0, 2.2, 3.0 .vcp_subsets = VCP_SUBSET_AUDIO, .desc="Emphasize/de-emphasize high frequency audio", // n. for v2.0 name in spec is "TV-audio treble". "TV" prefix is // dropped in 2.2, 3.0. just use the more generic term for all versions // similar comments apply to x91, x93 // In MCCS spec v2.2a, summary table 7.4 Audio Adjustments lists this // feature as type C, but detailed documentation in section // 8.6 Audio Adjustments lists it as type NC and documents // reserved values. Treat as NC. .v20_name="Audio Treble", // requires special handling for V3, mix of C and NC, SL byte only .nontable_formatter=format_feature_detail_x8f_x91_audio_treble_bass, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v30_flags = DDCA_RW | DDCA_NC_CONT, .v22_flags = DDCA_RW | DDCA_NC_CONT, }, { .code=0x90, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .vcp_subsets = VCP_SUBSET_TV | VCP_SUBSET_COLOR, .desc = "Increase/decrease the wavelength of the color component of the video signal. " "AKA tint. Applies to currently active interface", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "Hue", }, { .code=0x91, .vcp_spec_groups = VCP_SPEC_AUDIO, // v2.0, 2.2, 3.0 .vcp_subsets = VCP_SUBSET_AUDIO, .desc="Emphasize/de-emphasize low frequency audio", .v20_name="Audio Bass", // requires special handling for V3.0 and v2.2: mix of C and NC, SL byte only // In MCCS spec v2.2a, summary table 7.4 Audio Adjustments lists this // feature as type C, but detailed documentation in section // 8.6 Audio Adjustments lists it as type NC and documents // reserved values. Treat as NC. .nontable_formatter=format_feature_detail_x8f_x91_audio_treble_bass, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v30_flags = DDCA_RW | DDCA_NC_CONT, .v22_flags = DDCA_RW | DDCA_NC_CONT, }, { .code=0x92, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .vcp_subsets = VCP_SUBSET_TV, .desc = "Increase/decrease the black level of the video", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "TV Black level/Brightness", .v21_name = "TV Black level/Luminesence", }, { .code=0x93, .vcp_spec_groups = VCP_SPEC_AUDIO, // v2.0, 2.2, 3.0 .vcp_subsets = VCP_SUBSET_AUDIO, .desc="Controls left/right audio balance", .v20_name="Audio Balance L/R", // requires special handling for V3 and v2.2, mix of C and NC, SL byte only .nontable_formatter=format_feature_detail_x93_audio_balance, .v20_flags = DDCA_RW | DDCA_STD_CONT, .v30_flags = DDCA_RW | DDCA_NC_CONT, .v22_flags = DDCA_RW | DDCA_NC_CONT, }, { .code=0x94, .vcp_spec_groups = VCP_SPEC_AUDIO, // v2.0 // name changed in 3.0, assume applies to 2.1 .vcp_subsets = VCP_SUBSET_TV | VCP_SUBSET_AUDIO, .desc="Select audio mode", .v20_name="Audio Stereo Mode", .v21_name="Audio Processor Mode", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .default_sl_values=x94_audio_stereo_mode_values, }, { .code=0x95, // Done .vcp_spec_groups = VCP_SPEC_WINDOW | VCP_SPEC_GEOMETRY, // 2.0: WINDOW, 3.0: GEOMETRY .vcp_subsets = VCP_SUBSET_WINDOW, .desc="Top left X pixel of an area of the image", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Window Position(TL_X)", }, { .code=0x96, // Done .vcp_spec_groups = VCP_SPEC_WINDOW | VCP_SPEC_GEOMETRY, // 2.0: WINDOW, 3.0: GEOMETRY .vcp_subsets = VCP_SUBSET_WINDOW, .desc="Top left Y pixel of an area of the image", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Window Position(TL_Y)", }, { .code=0x97, // Done .vcp_spec_groups = VCP_SPEC_WINDOW | VCP_SPEC_GEOMETRY, // 2.0: WINDOW, 3.0: GEOMETRY .vcp_subsets = VCP_SUBSET_WINDOW, .desc="Bottom right X pixel of an area of the image", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Window Position(BR_X)", }, { .code=0x98, // Done .vcp_spec_groups = VCP_SPEC_WINDOW | VCP_SPEC_GEOMETRY, // 2.0: WINDOW, 3.0: GEOMETRY .vcp_subsets = VCP_SUBSET_WINDOW, .desc="Bottom right Y pixel of an area of the image", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Window Position(BR_Y)", }, { .code=0x99, .vcp_spec_groups = VCP_SPEC_WINDOW, // 2.0: WINDOW // in 2.0, not in 3.0 or 2.2, what is correct choice for 2.1? .vcp_subsets = VCP_SUBSET_WINDOW, .default_sl_values = x99_window_control_values, .desc="Enables the brightness and color within a window to be different " "from the desktop.", .v20_flags= DDCA_RW | DDCA_SIMPLE_NC, .v20_name="Window control on/off", .v22_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_SIMPLE_NC, .v30_flags = DDCA_DEPRECATED | DDCA_RW | DDCA_SIMPLE_NC, }, { .code=0x9a, .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, // 2.0: WINDOW, 3.0, 2.2: IMAGE .vcp_subsets = VCP_SUBSET_WINDOW, // VCP_SUBSET_COLOR? // 2.2 spec notes: // 1) should be used in conjunction with VCP 99h // 2) Not recommended for new designs, see A5h for alternate .desc="Changes the contrast ratio between the area of the window and the " "rest of the desktop", .v20_flags= DDCA_RW | DDCA_STD_CONT, .v20_name="Window background", }, { .code=0x9b, // in 2.0, same in 3.0 .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, // 2.0: WINDOW, 3.0: IMAGE .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // U3011 doesn't implement the spec that puts the midpoint at 127, // Just interpret this and the other hue fields as standard continuous // .desc = "Value < 127 shifts toward magenta, 127 no effect, " // "> 127 shifts toward yellow", // .nontable_formatter=format_feature_detail_6_axis_hue, // .v20_flags =DDCA_RW | VCP2_COMPLEX_CONT, .desc = "Decrease shifts toward magenta, " "increase shifts toward yellow", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "6 axis hue control: Red", }, { .code=0x9c, // in 2.0, same in 3.0 .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, // 2.0: WINDOW, 3.0: IMAGE .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // .nontable_formatter=format_feature_detail_6_axis_hue, // .desc = "Value < 127 shifts toward green, 127 no effect, " // "> 127 shifts toward red", // .v20_flags = DDCA_RW | VCP2_COMPLEX_CONT, .desc = "Decrease shifts toward green, " "increase shifts toward red", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "6 axis hue control: Yellow", }, { .code=0x9d, // in 2.0, same in 3.0 .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, // 2.0: WINDOW, 3.0: IMAGE .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // .nontable_formatter=format_feature_detail_6_axis_hue, // .desc = "Value < 127 shifts toward yellow, 127 no effect, " // "> 127 shifts toward cyan", // .v20_flags =DDCA_RW | VCP2_COMPLEX_CONT, .desc = "Decrease shifts toward yellow, " "increase shifts toward cyan", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "6 axis hue control: Green", }, { .code=0x9e, // in 2.0, same in 3.0 .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, // 2.0: WINDOW, 3.0: IMAGE .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // .nontable_formatter=format_feature_detail_6_axis_hue, // .desc = "Value < 127 shifts toward green, 127 no effect, " // "> 127 shifts toward blue", // .v20_flags = DDCA_RW | VCP2_COMPLEX_CONT, // VCP_SUBSET_COLORMGT? .desc = "Decrease shifts toward green, " "increase shifts toward blue", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "6 axis hue control: Cyan", }, { .code=0x9f, .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // .nontable_formatter=format_feature_detail_6_axis_hue, // .desc = "Value < 127 shifts toward cyan, 127 no effect, " // "> 127 shifts toward magenta", // .v20_flags =DDCA_RW | VCP2_COMPLEX_CONT, .desc = "Decrease shifts toward cyan, " "increase shifts toward magenta", .v20_flags = DDCA_RW | DDCA_STD_CONT, .v20_name = "6 axis hue control: Blue", }, { .code=0xa0, .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, .vcp_subsets = VCP_SUBSET_COLOR | VCP_SUBSET_PROFILE, // .nontable_formatter=format_feature_detail_6_axis_hue, // .desc = "Value < 127 shifts toward blue, 127 no effect, " // "> 127 shifts toward red", // .v20_flags = DDCA_RW | VCP2_COMPLEX_CONT, .v20_flags = DDCA_RW | DDCA_STD_CONT, .desc = "Decrease shifts toward blue, 127 no effect, " "increase shifts toward red", .v20_name = "6 axis hue control: Magenta", }, { .code=0xa2, // Defined in 2.0, same in 3.0 .vcp_spec_groups = VCP_SPEC_IMAGE, .desc="Turn on/off an auto setup function", .default_sl_values=xa2_auto_setup_values, .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Auto setup on/off", }, { .code=0xa4, // Complex interpretation, to be implemented .vcp_spec_groups = VCP_SPEC_IMAGE, .vcp_subsets = VCP_SUBSET_WINDOW, // 2.0 spec says: "This command structure is recommended, in conjunction with VCP A5h // for all new designs" // type NC in 2.0, type T in 3.0, 2.2, what is correct choice for 2.1? //.name="Window control on/off", //.flags = VCP_RW | VCP_NON_CONT, .nontable_formatter = format_feature_detail_debug_sl_sh, // TODO: write proper function .table_formatter = default_table_feature_detail_function, // TODO: write proper function .desc = "Turn selected window operation on/off, window mask", .v20_flags = DDCA_RW | DDCA_COMPLEX_NC, .v30_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v22_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v20_name = "Turn the selected window operation on/off", .v30_name = "Window mask control", .v22_name = "Window mask control", }, { .code=0xa5, .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_WINDOW, .vcp_subsets = VCP_SUBSET_WINDOW, // 2.0 spec says: "This command structure is recommended, in conjunction with VCP A4h // for all new designs // designated as C, but only takes specific values // v3.0 appears to be identical .default_sl_values = xa5_window_select_values, .desc = "Change selected window (as defined by 95h..98h)", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Change the selected window", }, { .code=0xaa, // Done .vcp_spec_groups = VCP_SPEC_IMAGE | VCP_SPEC_GEOMETRY, // 3.0: IMAGE, 2.0: GEOMETRY .default_sl_values=xaa_screen_orientation_values, .desc="Indicates screen orientation", .v20_flags=DDCA_RO | DDCA_SIMPLE_NC, .v20_name="Screen Orientation", }, { .code=0xac, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .nontable_formatter=format_feature_detail_xac_horizontal_frequency, .desc = "Horizontal sync signal frequency as determined by the display", // 2.0: 0xff 0xff 0xff indicates the display cannot supply this info .v20_flags = DDCA_RO | DDCA_COMPLEX_CONT, .v20_name = "Horizontal frequency", }, { .code=0xae, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .nontable_formatter=format_feature_detail_xae_vertical_frequency, .desc = "Vertical sync signal frequency as determined by the display, " "in .01 hz", // 2.0: 0xff 0xff indicates the display cannot supply this info .v20_flags =DDCA_RO | DDCA_COMPLEX_CONT, .v20_name = "Vertical frequency", }, { .code=0xb0, .vcp_spec_groups = VCP_SPEC_PRESET, // Defined in 2.0, v3.0 spec clarifies that value to be set is in SL byte //.name="(Re)Store user saved values for cur mode", // this was my name from the explanation .default_sl_values = xb0_settings_values, .desc = "Store/restore the user saved values for the current mode.", .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Settings", }, { .code=0xb2, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .default_sl_values=xb2_flat_panel_subpixel_layout_values, .desc = "LCD sub-pixel structure", .v20_flags = DDCA_RO | DDCA_SIMPLE_NC, .v20_name = "Flat panel sub-pixel layout", }, { .code = 0xb4, .vcp_spec_groups = VCP_SPEC_CONTROL, // 3.0 .desc = "Indicates timing mode being sent by host", // not defined in 2.0, is defined in 3.0 and 2.2 as T // seen on U3011 which is v2.1 // should this be seen as T or NC for 2.1? // if set T for 2.1, monitor returns NULL response, which // ddcutil interprets as unsupported. // if set NC for 2.1, response looks valid, // supported opcode is set .v21_name = "Source Timing Mode", .nontable_formatter = format_feature_detail_debug_bytes, .v21_flags = DDCA_RW | DDCA_COMPLEX_NC, .v30_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v22_flags = DDCA_RW | DDCA_NORMAL_TABLE, }, { .code=0xb6, // DONE .vcp_spec_groups = VCP_SPEC_MISC, // 2.0, 3.0 // v3.0 table not upward compatible w 2.0, assume changed as of 2.1 .desc = "Indicates the base technology type", .default_sl_values=xb6_v20_display_technology_type_values, .v21_sl_values = xb6_display_technology_type_values, .v20_flags = DDCA_RO | DDCA_SIMPLE_NC, .v20_name = "Display technology type", }, { .code=0xb7, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .desc = "Video mode and status of a DPVL capable monitor", .v20_name = "Monitor status", .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .nontable_formatter = format_feature_detail_sl_byte, //TODO: implement proper function }, { .code=0xb8, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .v20_name = "Packet count", .desc = "Counter for DPVL packets received", .v20_flags = DDCA_RW | DDCA_COMPLEX_CONT, .nontable_formatter = format_feature_detail_ushort, }, { .code=0xb9, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .v20_name = "Monitor X origin", .desc = "X origin of the monitor in the vertical screen", .v20_flags = DDCA_RW | DDCA_COMPLEX_CONT, .nontable_formatter = format_feature_detail_ushort, }, { .code=0xba, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .v20_name = "Monitor Y origin", .desc = "Y origin of the monitor in the vertical screen", .v20_flags = DDCA_RW | DDCA_COMPLEX_CONT, .nontable_formatter = format_feature_detail_ushort, }, { .code=0xbb, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .desc = "Error counter for the DPVL header", .v20_name = "Header error count", .v20_flags = DDCA_RW | DDCA_COMPLEX_CONT, .nontable_formatter = format_feature_detail_ushort, }, { .code=0xbc, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .desc = "CRC error counter for the DPVL body", .v20_name = "Body CRC error count", .v20_flags = DDCA_RW | DDCA_COMPLEX_CONT, .nontable_formatter = format_feature_detail_ushort, }, { .code=0xbd, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .desc = "Assigned identification number for the monitor", .v20_name = "Client ID", .v20_flags = DDCA_RW | DDCA_COMPLEX_CONT, .nontable_formatter = format_feature_detail_ushort, }, { .code=0xbe, .vcp_spec_groups = VCP_SPEC_DPVL, .vcp_subsets = VCP_SUBSET_DPVL, .desc = "Indicates status of the DVI link", .v20_name = "Link control", .v20_flags = DDCA_RW | DDCA_COMPLEX_NC, .nontable_formatter = format_feature_detail_xbe_link_control, }, { .code=0xc0, .vcp_spec_groups = VCP_SPEC_MISC, .nontable_formatter=format_feature_detail_xc0_display_usage_time, .desc = "Active power on time in hours", .v20_flags =DDCA_RO | DDCA_COMPLEX_CONT, .v20_name = "Display usage time", }, { .code=0xc2, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .desc = "Length in bytes of non-volatile storage in the display available " "for writing a display descriptor, max 256", .v20_flags = DDCA_RO | DDCA_STD_CONT, // should there be a different flag when we know value uses only SL? // or could this value be exactly 256? .v20_name = "Display descriptor length", }, { .code=0xc3, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .table_formatter = default_table_feature_detail_function, .desc="Reads (writes) a display descriptor from (to) non-volatile storage " "in the display.", .v20_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v20_name = "Transmit display descriptor", }, { .code = 0xc4, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .nontable_formatter=format_feature_detail_debug_bytes, .desc = "If enabled, the display descriptor shall be displayed when no video " "is being received.", .v20_flags = DDCA_RW | DDCA_COMPLEX_NC, // need to handle "All other values. The display descriptor shall not be displayed" .v20_name = "Enable display of \'display descriptor\'", }, { .code=0xc6, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .nontable_formatter=format_feature_detail_x6c_application_enable_key, .desc = "A 2 byte value used to allow an application to only operate with known products.", .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .v20_name = "Application enable key", }, { .code=0xc8, .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_CONTROL, // 2.0: MISC, 3.0: CONTROL .nontable_formatter=format_feature_detail_xc8_display_controller_type, .default_sl_values=xc8_display_controller_type_values, // ignored, hardcoded in nontable_formatter .desc = "Mfg id of controller and 2 byte manufacturer-specific controller type", .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .v20_name = "Display controller type", }, { .code=0xc9, .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_CONTROL, // 2.: MISC, 3.0: CONTROL .nontable_formatter=format_feature_detail_xc9_xdf_version, .desc = "2 byte firmware level", .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .v20_name = "Display firmware level", }, { .code=0xca, // Says the v2.2 spec: A new feature added to V3.0 and expanded in V2.2 // BUT: xCA is present in 2.0 spec, defined identically to 3.0 spec .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_CONTROL, // 2.0: MISC, 3.0: CONTROL .default_sl_values=xca_osd_values, // tables specified in nontable_formatter .v22_sl_values=xca_v22_osd_button_sl_values, // .desc = "Indicates whether On Screen Display is enabled", .desc = "Sets and indicates the current operational state of OSD (and buttons in v2.2)", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "OSD", .v22_flags = DDCA_RW | DDCA_COMPLEX_NC, // for v3.0: .nontable_formatter = format_feature_detail_xca_osd_button_control, .v22_name = "OSD/Button Control" }, { .code=0xcc, .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_CONTROL, // 2.0: MISC, 3.0: CONTROL .default_sl_values=xcc_osd_language_values, .desc = "On Screen Display language", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "OSD Language", }, { .code=0xcd, .vcp_spec_groups = VCP_SPEC_MISC, // 3.0: MISC // not in 2.0, is in 3.0, assume exists in 2.1 .desc = "Control up to 16 LED (or similar) indicators to indicate system status", .nontable_formatter = format_feature_detail_debug_sl_sh, .v21_flags = DDCA_RW | DDCA_COMPLEX_NC, .v21_name = "Status Indicators", }, { .code=0xce, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .desc = "Rows and characters/row of auxiliary display", .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .v20_name = "Auxiliary display size", .nontable_formatter = format_feature_detail_xce_aux_display_size, }, { .code=0xcf, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .desc = "Sets contents of auxiliary display device", .v20_flags = DDCA_WO | DDCA_WO_TABLE, .v20_name = "Auxiliary display data", }, { .code=0xd0, .vcp_spec_groups = VCP_SPEC_MISC, .desc = "Selects the active output", .v20_name = "Output select", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .default_sl_values = xd0_v2_output_select_values, .table_formatter = default_table_feature_detail_function, // TODO: implement proper function .v30_flags = DDCA_RW | DDCA_NORMAL_TABLE, .v22_flags = DDCA_RW | DDCA_SIMPLE_NC, }, { .code=0xd2, // exists in 3.0, not in 2.0, assume exists in 2.1 .vcp_spec_groups = VCP_SPEC_MISC, .desc = "Read an Asset Tag to/from the display", .v21_name = "Asset Tag", .v21_flags = DDCA_RW | DDCA_NORMAL_TABLE, .table_formatter = default_table_feature_detail_function, }, { .code=0xd4, .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_IMAGE, // 2.0: MISC, 3.0: IMAGE .desc="Stereo video mode", .v20_name = "Stereo video mode", .v20_flags = DDCA_RW | DDCA_COMPLEX_NC, .nontable_formatter = format_feature_detail_sl_byte, // TODO: implement proper function }, { .code=0xd6, // DONE .vcp_spec_groups = VCP_SPEC_MISC | VCP_SPEC_CONTROL, // 2.0: MISC, 3.0: CONTROL .default_sl_values = xd6_power_mode_values, .desc = "DPM and DPMS status", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Power mode", }, { .code=0xd7, // DONE - identical in 2.0, 3.0, 2.2 .vcp_spec_groups = VCP_SPEC_MISC, // 2.0, 3.0, 2.2 .default_sl_values = xd7_aux_power_output_values, .desc="Controls an auxiliary power output from a display to a host device", .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Auxiliary power output", }, { .code=0xda, // DONE .vcp_spec_groups = VCP_SPEC_GEOMETRY | VCP_SPEC_IMAGE, // 2.0: IMAGE, 3.0: GEOMETRY .vcp_subsets = VCP_SUBSET_CRT, .desc = "Controls scan characteristics (aka format)", .default_sl_values = xda_scan_mode_values, .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Scan format", // name differs in 3.0, assume changed as of 2.1 .v21_name = "Scan mode", }, { .code=0xdb, .vcp_spec_groups = VCP_SPEC_CONTROL, // 3.0 // defined in 3.0, not in 2.0, assume present in 2.1 .vcp_subsets = VCP_SUBSET_TV, .desc = "Controls aspects of the displayed image (TV applications)", .default_sl_values = xdb_image_mode_values, .v21_flags = DDCA_RW | DDCA_SIMPLE_NC, .v21_name = "Image Mode", }, { .code=0xdc, .vcp_spec_groups = VCP_SPEC_IMAGE, // defined in 2.0, 3.0 has different name, more values //.name="Display application", .default_sl_values=xdc_display_application_values, .desc="Type of application used on display", // my desc .vcp_subsets = VCP_SUBSET_COLOR, // observed on U32H750 to interact with color settings .v20_flags = DDCA_RW | DDCA_SIMPLE_NC, .v20_name = "Display Mode", .v30_name = "Display Application", }, { .code=0xde, // code 0xde has a completely different name and definition in v2.0 // vs v3.0/2.2 // 2.0: Operation Mode, W/O single byte value per xde_wo_operation_mode_values // 3.0, 2.2: Scratch Pad: 2 bytes of volatile storage for use of software applications // Did the definition really change so radically, or is the 2.0 spec a typo. // What to do for 2.1? Assume same as 3.0,2.2 .vcp_spec_groups = VCP_SPEC_MISC, // 2.0, 3.0, 2.2 .desc = "Operation mode (2.0) or scratch pad (3.0/2.2)", .nontable_formatter = format_feature_detail_debug_sl_sh, .v20_flags = DDCA_WO | DDCA_WO_NC, .v20_name = "Operation Mode", .v21_flags = DDCA_RW | DDCA_COMPLEX_NC, .v21_name = "Scratch Pad", }, { .code=0xdf, .vcp_spec_groups = VCP_SPEC_MISC, // 2.0 .nontable_formatter=format_feature_detail_xc9_xdf_version, .desc = "MCCS version", .v20_flags = DDCA_RO | DDCA_COMPLEX_NC, .v20_name = "VCP Version", } }; // #pragma GCC diagnostic pop int vcp_feature_code_count = sizeof(vcp_code_table)/sizeof(VCP_Feature_Table_Entry); #ifdef DEVELOPMENT_ONLY // // Functions for validating vcp_code_table[] // // Intended for use only during development // int check_one_version_flags( DDCA_Version_Feature_Flags vflags, char * which_flags, VCP_Feature_Table_Entry * pentry) { int ct = 0; if (vflags && !(vflags & DDCA_DEPRECATED)) { if (vflags & DDCA_STD_CONT) ct++; if (vflags & DDCA_COMPLEX_CONT) ct++; if (vflags & DDCA_SIMPLE_NC) ct++; if (vflags & DDCA_COMPLEX_NC) ct++; if (vflags & DDCA_WO_NC) ct++; if (vflags & DDCA_NORMAL_TABLE) ct++; if (vflags & DDCA_WO_TABLE) ct++; if (ct != 1) { fprintf( stderr, "code: 0x%02x, exactly 1 of VCP2_STD_CONT, VCP2_COMPLEX_CONT, VCP2_SIMPLE_NC, " "VCP2_COMPLEX_NC, VCP2_TABLE, VCP2_WO_TABLE must be set in %s\n", pentry->code, which_flags); ct = -1; } if (vflags & DDCA_SIMPLE_NC) { if (!pentry->default_sl_values) { fprintf( stderr, "code: 0x%02x, .flags: %s, VCP2_SIMPLE_NC set but .default_sl_values == NULL\n", pentry->code, which_flags); ct = -2; } } else if (vflags & DDCA_COMPLEX_NC) { if (!pentry->nontable_formatter) { fprintf( stderr, "code: 0x%02x, .flags: %s, VCP2_COMPLEX_NC set but .nontable_formatter == NULL\n", pentry->code, which_flags); ct = -2; } } else if (vflags & DDCA_COMPLEX_CONT) { if (!pentry->nontable_formatter) { fprintf( stderr, "code: 0x%02x, .flags: %s, VCP2_COMPLEX_CONT set but .nontable_formatter == NULL\n", pentry->code, which_flags); ct = -2; } } // // no longer an error. get_table_feature_detail_function() sets default // else if (vflags & VCP2_TABLE) { // if (!pentry->table_formatter) { // fprintf( // stderr, // "code: 0x%02x, .flags: %s, VCP2_TABLE set but .table_formatter == NULL\n", // pentry->code, which_flags); // ct = -2; // } // } } return ct; } /* If the flags has anything set, and is not deprecated, checks that * exactly 1 of DDCA_RO, DDCA_WO, DDCA_RW is set * * Returns: 1 of a value is set, 0 if no value set, -1 if * more than 1 value set */ int check_version_rw_flags( DDCA_Version_Feature_Flags vflags, char * which_flags, VCP_Feature_Table_Entry * entry) { int ct = 0; if (vflags && !(vflags & DDCA_DEPRECATED)) { if (vflags & DDCA_RO) ct++; if (vflags & DDCA_WO) ct++; if (vflags & DDCA_RW) ct++; if (ct != 1) { fprintf(stderr, "code: 0x%02x, exactly 1 of DDCA_RO, DDCA_WO, DDCA_RW must be set in non-zero %s_flags\n", entry->code, which_flags); ct = -1; } } return ct; } void validate_vcp_feature_table() { bool debug = false; DBGMSF(debug, "Starting"); bool ok = true; bool ok2 = true; int ndx = 0; // return; // *** TEMP *** int total_ct = 0; for (;ndx < vcp_feature_code_count;ndx++) { VCP_Feature_Table_Entry * pentry = &vcp_code_table[ndx]; int cur_ct; cur_ct = check_version_rw_flags(pentry->v20_flags, "v20_flags", pentry); if (cur_ct < 0) ok = false; else total_ct += cur_ct; cur_ct = check_version_rw_flags(pentry->v21_flags, "v21_flags", pentry); if (cur_ct < 0) ok = false; else total_ct += cur_ct; cur_ct = check_version_rw_flags(pentry->v30_flags, "v30_flags", pentry); if (cur_ct < 0) ok = false; else total_ct += cur_ct; cur_ct = check_version_rw_flags(pentry->v22_flags, "v22_flags", pentry); if (cur_ct < 0) ok = false; else total_ct += cur_ct; if (ok && total_ct == 0) { fprintf(stderr, "RW, RO, RW not set in any version specific flags for feature 0x%02x\n", pentry->code); ok = false; } total_ct = 0; cur_ct = check_one_version_flags(pentry->v20_flags, ".v20_flags", pentry); if (cur_ct < 0) ok2 = false; else total_ct += 1; cur_ct = check_one_version_flags(pentry->v21_flags, ".v21_flags", pentry); if (cur_ct < 0) ok2 = false; else total_ct += 1; cur_ct = check_one_version_flags(pentry->v30_flags, ".v30_flags", pentry); if (cur_ct < 0) ok2 = false; else total_ct += 1; cur_ct = check_one_version_flags(pentry->v22_flags, ".v22_flags", pentry); if (cur_ct < 0) ok2 = false; else total_ct += 1; if (total_ct == 0 && ok2) { fprintf(stderr, "code: 0x%02x, Type not specified in any vnn_flags\n", pentry->code); ok2 = false; } } if (!(ok && ok2)) // assert(false); PROGRAM_LOGIC_ERROR(NULL); } // End of functions for validating vcp_code_table #endif #ifdef REF typedef struct { char marker[4]; Byte code; char * desc; Format_Normal_Feature_Detail_Function nontable_formatter; Format_Table_Feature_Detail_Function table_formatter; DDCA_Global_Feature_Flags vcp_global_flags; gushort vcp_spec_groups; VCP_Feature_Subset vcp_subsets; char * v20_name; char * v21_name; char * v30_name; char * v22_name; DDCA_Version_Feature_Flags v20_flags; DDCA_Version_Feature_Flags v21_flags; DDCA_Version_Feature_Flags v30_flags; DDCA_Version_Feature_Flags v22_flags; DDCA_Feature_Value_Entry * default_sl_values; DDCA_Feature_Value_Entry * v21_sl_values; DDCA_Feature_Value_Entry * v30_sl_values; DDCA_Feature_Value_Entry * v22_sl_values; } VCP_Feature_Table_Entry; #endif /** Output a debug report for a specified #VCP_Feature_Table_Entry. * * @param pfte feature table entry * @param depth logical indentation depth */ void dbgrpt_vcp_entry(VCP_Feature_Table_Entry * pfte, int depth) { rpt_vstring(depth, "VCP_Feature_Table_Entry at %p:", pfte); // show_backtrace(2); assert(pfte && memcmp(pfte->marker, VCP_FEATURE_TABLE_ENTRY_MARKER, 4) == 0); int d1 = depth+1; const int bufsz = 100; char buf[bufsz]; rpt_vstring(d1, "code: 0x%02x", pfte->code); rpt_vstring(d1, "desc: %s", pfte->desc); rpt_vstring(d1, "nontable_formatter: %p %s", pfte->nontable_formatter, rtti_get_func_name_by_addr(pfte->nontable_formatter)); rpt_vstring(d1, "table_formatter: %p %s", pfte->table_formatter, rtti_get_func_name_by_addr(pfte->table_formatter)); rpt_vstring(d1, "vcp_global_flags: 0x%02x - %s", pfte->vcp_global_flags, vcp_interpret_global_feature_flags(pfte->vcp_global_flags, buf, bufsz)); rpt_vstring(d1, "vcp_spec_groups: 0x%04x - %s", pfte->vcp_spec_groups, spec_group_names_r(pfte, buf, bufsz)); rpt_vstring(d1, "vcp_subsets: 0x%04x - %s", pfte->vcp_subsets, feature_subset_names(pfte->vcp_subsets)); rpt_vstring(d1, "v20_name: %s", pfte->v20_name); rpt_vstring(d1, "v21_name: %s", pfte->v21_name); rpt_vstring(d1, "v30_name: %s", pfte->v30_name); rpt_vstring(d1, "v22_name: %s", pfte->v22_name); // rpt_vstring(d1, "v20_flags: 0x%04x - %s", // pfte->v20_flags, // vcp_interpret_version_feature_flags(pfte->v20_flags, buf, bufsz)); rpt_vstring(d1, "v20_flags: 0x%04x - %s", pfte->v20_flags, interpret_ddca_version_feature_flags_symbolic_t(pfte->v20_flags)); // rpt_vstring(d1, "v21_flags: 0x%04x - %s", // pfte->v21_flags, // vcp_interpret_version_feature_flags(pfte->v21_flags, buf, bufsz)); rpt_vstring(d1, "v21_flags: 0x%04x - %s", pfte->v21_flags, interpret_ddca_version_feature_flags_symbolic_t(pfte->v21_flags)); // rpt_vstring(d1, "v30_flags: 0x%04x - %s", // pfte->v30_flags, // vcp_interpret_version_feature_flags(pfte->v30_flags, buf, bufsz)); rpt_vstring(d1, "v30_flags: 0x%04x - %s", pfte->v30_flags, interpret_ddca_version_feature_flags_symbolic_t(pfte->v30_flags)); // rpt_vstring(d1, "v22_flags: 0x%04x - %s", // pfte->v22_flags, // vcp_interpret_version_feature_flags(pfte->v22_flags, buf, bufsz)); rpt_vstring(d1, "v22_flags: 0x%04x - %s", pfte->v22_flags, interpret_ddca_version_feature_flags_symbolic_t(pfte->v22_flags)); dbgrpt_sl_value_table(pfte->default_sl_values, "default_sl_values", d1); dbgrpt_sl_value_table(pfte->v21_sl_values, "v21_sl_values", d1); dbgrpt_sl_value_table(pfte->v30_sl_values, "v30_sl_values", d1); dbgrpt_sl_value_table(pfte->v22_sl_values, "v22_sl_values", d1); } static void init_func_name_table() { RTTI_ADD_FUNC(vcp_format_nontable_feature_detail); RTTI_ADD_FUNC(vcp_format_table_feature_detail); RTTI_ADD_FUNC(vcp_format_feature_detail); RTTI_ADD_FUNC(default_table_feature_detail_function); RTTI_ADD_FUNC(extract_version_feature_info_from_feature_table_entry); RTTI_ADD_FUNC(format_feature_detail_x73_lut_size); RTTI_ADD_FUNC(format_feature_detail_debug_sl_sh); RTTI_ADD_FUNC(format_feature_detail_debug_continuous); RTTI_ADD_FUNC(format_feature_detail_debug_bytes ); RTTI_ADD_FUNC(format_feature_detail_sl_byte); RTTI_ADD_FUNC(format_feature_detail_sh_sl_bytes); RTTI_ADD_FUNC(format_feature_detail_sl_lookup); RTTI_ADD_FUNC(format_feature_detail_sl_lookup_with_sh); RTTI_ADD_FUNC(format_feature_detail_standard_continuous); RTTI_ADD_FUNC(format_feature_detail_ushort); RTTI_ADD_FUNC(format_feature_detail_x02_new_control_value); RTTI_ADD_FUNC(format_feature_detail_x0b_color_temperature_increment); RTTI_ADD_FUNC(format_feature_detail_x0c_color_temperature_request); RTTI_ADD_FUNC(format_feature_detail_x14_select_color_preset); RTTI_ADD_FUNC(format_feature_detail_x62_audio_speaker_volume); RTTI_ADD_FUNC(format_feature_detail_x8d_mute_audio_blank_screen); RTTI_ADD_FUNC(format_feature_detail_x8f_x91_audio_treble_bass); RTTI_ADD_FUNC(format_feature_detail_x93_audio_balance); RTTI_ADD_FUNC(format_feature_detail_xac_horizontal_frequency); RTTI_ADD_FUNC(format_feature_detail_6_axis_hue); RTTI_ADD_FUNC(format_feature_detail_xae_vertical_frequency); RTTI_ADD_FUNC(format_feature_detail_xbe_link_control); RTTI_ADD_FUNC(format_feature_detail_xc0_display_usage_time); RTTI_ADD_FUNC(format_feature_detail_xca_osd_button_control); RTTI_ADD_FUNC(format_feature_detail_x6c_application_enable_key); RTTI_ADD_FUNC(format_feature_detail_xc8_display_controller_type); RTTI_ADD_FUNC(format_feature_detail_xc9_xdf_version); RTTI_ADD_FUNC(vcp_find_feature_by_hexid_w_default); RTTI_ADD_FUNC(vcp_find_feature_by_hexid); } /** Initialize the vcp_feature_codes module. * Must be called before any other function in this file. */ void init_vcp_feature_codes() { #ifdef DEVELOPMENT_ONLY validate_vcp_feature_table(); // enable for development #endif for (int ndx=0; ndx < vcp_feature_code_count; ndx++) { memcpy( vcp_code_table[ndx].marker, VCP_FEATURE_TABLE_ENTRY_MARKER, 4); } init_func_name_table(); // dbgrpt_func_name_table(0); vcp_feature_codes_initialized = true; } ddcutil-2.2.0/src/vcp/vcp_feature_values.c0000644000175000001440000003634214634171455014247 // vcp_feature_values.c // Copyright (C) 2014-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #include #include #include #include #include "util/data_structures.h" #include "util/report_util.h" #include "util/string_util.h" #include "base/ddc_packets.h" #include "vcp/vcp_feature_values.h" /** Returns a descriptive name of a #DDCA_Vcp_Value_Type value * * \param value_type * \return name, "Non Table" or "Table" */ char * vcp_value_type_name(DDCA_Vcp_Value_Type value_type) { char * result = NULL; switch (value_type) { case DDCA_NON_TABLE_VCP_VALUE: result = "Non Table"; break; case DDCA_TABLE_VCP_VALUE: result = "Table"; break; } return result; } /** Returns the name of a #DDCA_Vcp_Value_Type value * * \param value_type * \return name, "DDCA_NON_TABLE_VCP_VALUE" or "DDCA_TABLE_VCP_VALUE" */ char * vcp_value_type_id(DDCA_Vcp_Value_Type value_type) { char * result = NULL; switch(value_type) { case DDCA_NON_TABLE_VCP_VALUE: result = "DDCA_NON_TABLE_VCP_VALUE"; break; case DDCA_TABLE_VCP_VALUE: result = "DDCA_TABLE_VCP_VALUE"; break; } return result; } /** Emits a debug report of a #DDCA_Any_Vcp_Value instance * * \param valrec pointer to instance to report * \param depth logical indentation depth */ void dbgrpt_single_vcp_value( DDCA_Any_Vcp_Value * valrec, int depth) { int d0 = depth; int d1 = depth + 1; int d2 = depth + 2; rpt_vstring(d0, "Single_Vcp_Value at %p:", valrec); if (valrec) { rpt_vstring(d1, "Opcode: 0x%02x", valrec->opcode); rpt_vstring(d1, "Value type: %s (0x%02x)", vcp_value_type_id(valrec->value_type), valrec->value_type); if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { rpt_vstring(d1, "max_val: %d - 0x%04x", VALREC_MAX_VAL(valrec), VALREC_MAX_VAL(valrec)); rpt_vstring(d1, "cur_val: %d - 0x%04x", VALREC_CUR_VAL(valrec), VALREC_CUR_VAL(valrec)); rpt_vstring(d1, "mh: 0x%02x", valrec->val.c_nc.mh); rpt_vstring(d1, "ml: 0x%02x", valrec->val.c_nc.ml); rpt_vstring(d1, "sh: 0x%02x", valrec->val.c_nc.sh); rpt_vstring(d1, "sl: 0x%02x", valrec->val.c_nc.sl); } else { assert(valrec->value_type == DDCA_TABLE_VCP_VALUE); rpt_vstring(d1, "Bytes:"); rpt_hex_dump(valrec->val.t.bytes, valrec->val.t.bytect, d2); } } } #ifdef OLD // has been merged into dbgrpt_single_vcp_value() void report_single_vcp_value( Single_Vcp_Value * valrec, int depth) { int d1 = depth+1; rpt_vstring(depth, "Single_Vcp_Value at %p:", valrec); rpt_vstring(d1, "opcode=0x%02x, value_type=%s (0x%02x)", valrec->opcode, vcp_value_type_id(valrec->value_type), valrec->value_type); if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { rpt_vstring(d1, "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x", valrec->val.nc.mh, valrec->val.nc.ml, valrec->val.nc.sh, valrec->val.nc.sl); rpt_vstring(d1, "max_val=%d (0x%04x), cur_val=%d (0x%04x)", valrec->val.c.max_val, valrec->val.c.max_val, valrec->val.c.cur_val, valrec->val.c.cur_val); } else { assert(valrec->value_type == DDCA_TABLE_VCP_VALUE); rpt_hex_dump(valrec->val.t.bytes, valrec->val.t.bytect, d1); } } #endif // must be #define, not const int, since used in buffer declaration #define SUMMARIZE_SINGLE_VCP_VALUE_BUFFER_SIZE 101 // to expose an int rather than a define in the header file const int summarize_single_vcp_value_buffer_size = SUMMARIZE_SINGLE_VCP_VALUE_BUFFER_SIZE; /** Returns a summary of a single vcp value in a buffer provided by the caller * * \param valrec vcp value to summarize * \param buffer pointer to buffer * \param bufsz buffer size * \return buffer */ char * summarize_single_vcp_value_r( DDCA_Any_Vcp_Value * valrec, char * buffer, int bufsz) { bool debug = false; DBGMSF(debug, "Starting. buffer=%p, bufsz=%d", buffer, bufsz); if (buffer) { assert(bufsz >= SUMMARIZE_SINGLE_VCP_VALUE_BUFFER_SIZE); *buffer = '\0'; if (valrec) { if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { snprintf(buffer, bufsz, "opcode=0x%02x, " "mh=0x%02x, ml=0x%02x, sh=0x%02x, sl=0x%02x, " "max_val=%d (0x%04x), cur_val=%d (0x%04x)", valrec->opcode, valrec->val.c_nc.mh, valrec->val.c_nc.ml, valrec->val.c_nc.sh, valrec->val.c_nc.sl, VALREC_MAX_VAL(valrec), VALREC_MAX_VAL(valrec), VALREC_CUR_VAL(valrec), VALREC_CUR_VAL(valrec) ); // should never happen, but in case of string too long buffer[bufsz-1] = '\0'; } else { assert(valrec->value_type == DDCA_TABLE_VCP_VALUE); snprintf(buffer, bufsz, "opcode=0x%02x, value_type=Table, bytect=%d, ...", valrec->opcode, valrec->val.t.bytect ); // easier just to convert the whole byte array then take what can fit char * buf0 = hexstring2( valrec->val.t.bytes, valrec->val.t.bytect, NULL, // sepstr, true, // uppercase, NULL, // allocate buffer, 0); // bufsz int space_remaining = bufsz - strlen(buffer); if ( strlen(buf0) < space_remaining ) strcat(buffer, buf0); else { strncat(buffer, buf0, space_remaining-4); strcat(buffer, "..."); } free(buf0); } } } return buffer; } /** Returns a summary string for a single vcp value * * This function returns a private thread-specific buffer. * The buffer is valid until the next call of this function in the same thread. * * \param valrec vcp value to summarize * \return pointer to summary string */ char * summarize_single_vcp_value(DDCA_Any_Vcp_Value * valrec) { static GPrivate summarize_key = G_PRIVATE_INIT(g_free); static GPrivate summarize_len_key = G_PRIVATE_INIT(g_free); char * buf = get_thread_dynamic_buffer(&summarize_key, &summarize_len_key, SUMMARIZE_SINGLE_VCP_VALUE_BUFFER_SIZE); return summarize_single_vcp_value_r(valrec, buf, SUMMARIZE_SINGLE_VCP_VALUE_BUFFER_SIZE); } /** Frees a single vcp value instance * * \param vcp_value pointer to instance (may be NULL) */ void free_single_vcp_value(DDCA_Any_Vcp_Value * vcp_value) { bool debug = false; if (vcp_value) { DBGMSF(debug, "Starting. vcp_value=%s", summarize_single_vcp_value(vcp_value)); if (vcp_value->value_type == DDCA_TABLE_VCP_VALUE) { if (vcp_value->val.t.bytes) free(vcp_value->val.t.bytes); } free(vcp_value); } else DBGMSF(debug, "Starting. vcp_value == NULL"); DBGMSF(debug, "Done"); } #ifdef UNUSED // wrap free_single_vcp_value() in signature of GDestroyNotify() void free_single_vcp_value_func(gpointer data) { free_single_vcp_value((DDCA_Any_Vcp_Value *) data); } #endif /** Creates a #DDCA_Any_Vcp_Value from the individual field values. * * @param feature_code * @param mh * @param ml * @param sh * @param sl * @return newly allocated #DDCA_Any_Vcp_Value instance * (caller is responsible for freeing) */ DDCA_Any_Vcp_Value * create_nontable_vcp_value( Byte feature_code, Byte mh, Byte ml, Byte sh, Byte sl) { DDCA_Any_Vcp_Value * valrec = calloc(1,sizeof(DDCA_Any_Vcp_Value)); valrec->value_type = DDCA_NON_TABLE_VCP_VALUE; valrec->opcode = feature_code; valrec->val.c_nc.mh = mh; valrec->val.c_nc.ml = ml; valrec->val.c_nc.sh = sh; valrec->val.c_nc.sl = sl; // not needed thanks to overlay // valrec->val.nt.max_val = mh <<8 | ml; // valrec->val.nt.cur_val = sh <<8 | sl; return valrec; } DDCA_Any_Vcp_Value * create_cont_vcp_value( Byte feature_code, gushort max_val, gushort cur_val) { DDCA_Any_Vcp_Value * valrec = calloc(1,sizeof(DDCA_Any_Vcp_Value)); valrec->value_type = DDCA_NON_TABLE_VCP_VALUE; valrec->opcode = feature_code; valrec->val.c_nc.mh = max_val >> 8; valrec->val.c_nc.ml = max_val & 0x0ff; valrec->val.c_nc.sh = cur_val >> 8; valrec->val.c_nc.sl = cur_val & 0xff; return valrec; } DDCA_Any_Vcp_Value * create_table_vcp_value_by_bytes( Byte feature_code, Byte * bytes, gushort bytect) { DDCA_Any_Vcp_Value * valrec = calloc(1,sizeof(DDCA_Any_Vcp_Value)); valrec->value_type = DDCA_TABLE_VCP_VALUE; valrec->opcode = feature_code; valrec->val.t.bytect = bytect; valrec->val.t.bytes = malloc(bytect); memcpy(valrec->val.t.bytes, bytes, bytect); return valrec; } DDCA_Any_Vcp_Value * create_table_vcp_value_by_buffer(Byte feature_code, Buffer * buffer) { return create_table_vcp_value_by_bytes(feature_code, buffer->bytes, buffer->len); } DDCA_Any_Vcp_Value * create_single_vcp_value_by_parsed_vcp_response( Byte feature_id, Parsed_Vcp_Response * presp) { DDCA_Any_Vcp_Value * valrec = NULL; if (presp->response_type == DDCA_NON_TABLE_VCP_VALUE) { assert(presp->non_table_response->valid_response); assert(presp->non_table_response->supported_opcode); assert(feature_id == presp->non_table_response->vcp_code); valrec = create_nontable_vcp_value( feature_id, presp->non_table_response->mh, presp->non_table_response->ml, presp->non_table_response->sh, presp->non_table_response->sl ); // assert(valrec->val.c.max_val == presp->non_table_response->max_value); // assert(valrec->val.c.cur_val == presp->non_table_response->cur_value); } else { assert(presp->response_type == DDCA_TABLE_VCP_VALUE); valrec = create_table_vcp_value_by_buffer(feature_id, presp->table_response); } return valrec; } #ifdef UNUSED // temp for aid in conversion Parsed_Vcp_Response * single_vcp_value_to_parsed_vcp_response( DDCA_Any_Vcp_Value * valrec) { Parsed_Vcp_Response * presp = calloc(1, sizeof(Parsed_Vcp_Response)); presp->response_type = valrec->value_type; if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { presp->non_table_response = calloc(1, sizeof(Parsed_Nontable_Vcp_Response)); // presp->non_table_response->cur_value = VALREC_CUR_VAL(valrec); // presp->non_table_response->max_value = VALREC_MAX_VAL(valrec); presp->non_table_response->mh = valrec->val.c_nc.mh; presp->non_table_response->ml = valrec->val.c_nc.ml; presp->non_table_response->sh = valrec->val.c_nc.sh; presp->non_table_response->sl = valrec->val.c_nc.sl; presp->non_table_response->supported_opcode = true; presp->non_table_response->valid_response = true; presp->non_table_response->vcp_code = valrec->opcode; } else { assert(valrec->value_type == DDCA_TABLE_VCP_VALUE); Buffer * buf2 = buffer_new(valrec->val.t.bytect, __func__); buffer_put(buf2, valrec->val.t.bytes, valrec->val.t.bytect); buffer_free(buf2,__func__); } return presp; } #endif Nontable_Vcp_Value * single_vcp_value_to_nontable_vcp_value(DDCA_Any_Vcp_Value * valrec) { bool debug = false; DBGMSF(debug, "Starting. valrec=%p", valrec); Nontable_Vcp_Value * non_table_response = calloc(1, sizeof(Nontable_Vcp_Value)); assert (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE); non_table_response->cur_value = VALREC_CUR_VAL(valrec); non_table_response->max_value = VALREC_MAX_VAL(valrec); non_table_response->mh = valrec->val.c_nc.mh; non_table_response->ml = valrec->val.c_nc.ml; non_table_response->sh = valrec->val.c_nc.sh; non_table_response->sl = valrec->val.c_nc.sl; non_table_response->vcp_code = valrec->opcode; DBGMSF(debug, "Done. Returning: %p", non_table_response); return non_table_response; } #ifdef SINGLE_VCP_VALUE /** Converts a #Single_Vcp_Value to #DDCA_Any_Vcp_Value * * \param valrec pointer to #Single_Vcp_Value to convert * \return newly allocated converted value * * \remark * If table type, the bytes are copied */ DDCA_Any_Vcp_Value * single_vcp_value_to_any_vcp_value(Single_Vcp_Value * valrec) { DDCA_Any_Vcp_Value * anyval = calloc(1, sizeof(DDCA_Any_Vcp_Value)); anyval->opcode = valrec->opcode; anyval->value_type = valrec->value_type; if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { anyval->val.c_nc.mh = valrec->val.nc.mh; anyval->val.c_nc.ml = valrec->val.nc.ml; anyval->val.c_nc.sh = valrec->val.nc.sh; anyval->val.c_nc.sl = valrec->val.nc.sl; } else { // DDCA_TABLE_VCP_VALUE anyval->val.t.bytect = valrec->val.t.bytect; if (valrec->val.t.bytect > 0 && valrec->val.t.bytes) { anyval->val.t.bytes = malloc(valrec->val.t.bytect); memcpy(anyval->val.t.bytes, valrec->val.t.bytes, valrec->val.t.bytect); } } return anyval; } #endif #ifdef SINGLE_VCP_VALUE /** Converts a #DDCA_Any_Vcp_Value to #Single_Vcp_Value * * \param valrec pointer to #DDCA_Any_Vcp_Value to convert * \return newly allocated converted value * * \remark * If table type, only the pointer to the bytes is copied */ Single_Vcp_Value * any_vcp_value_to_single_vcp_value(DDCA_Any_Vcp_Value * anyval) { Single_Vcp_Value * valrec = calloc(1, sizeof(Single_Vcp_Value)); valrec->opcode = anyval->opcode; valrec->value_type = anyval->value_type; if (valrec->value_type == DDCA_NON_TABLE_VCP_VALUE) { valrec->val.nc.mh = anyval->val.c_nc.mh; valrec->val.nc.ml = anyval->val.c_nc.ml; valrec->val.nc.sh = anyval->val.c_nc.sh; valrec->val.nc.sl = anyval->val.c_nc.sl; } else { // DDCA_TABLE_VCP_VALUE valrec->val.t.bytect = anyval->val.t.bytect; valrec->val.t.bytes = anyval->val.t.bytes; } return valrec; } #endif // // Vcp_Value_Set functions // Vcp_Value_Set vcp_value_set_new(int initial_size){ GPtrArray* ga = g_ptr_array_sized_new(initial_size); g_ptr_array_set_free_func(ga, (GDestroyNotify) free_single_vcp_value); return ga; } void free_vcp_value_set(Vcp_Value_Set vset){ // DBGMSG("Executing."); g_ptr_array_free(vset, true); } void vcp_value_set_add(Vcp_Value_Set vset, DDCA_Any_Vcp_Value * pval){ g_ptr_array_add(vset, pval); } int vcp_value_set_size(Vcp_Value_Set vset){ return vset->len; } DDCA_Any_Vcp_Value * vcp_value_set_get(Vcp_Value_Set vset, int ndx){ assert(0 <= ndx && ndx < vset->len); return g_ptr_array_index(vset, ndx); } void dbgrpt_vcp_value_set(Vcp_Value_Set vset, int depth) { rpt_vstring(depth, "Vcp_Value_Set at %p", vset); rpt_vstring(depth+1, "value count: %d", vset->len); for(int ndx = 0; ndxlen; ndx++) { dbgrpt_single_vcp_value( g_ptr_array_index(vset, ndx), depth+1); } } ddcutil-2.2.0/src/vcp/parse_capabilities.h0000644000175000001440000000375014754576332014220 /** @file parse_capabilities.h */ // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PARSE_CAPABILITIES_H_ #define PARSE_CAPABILITIES_H_ /** \cond */ #include #include "util/data_structures.h" /** \endcond */ #include "base/vcp_version.h" typedef enum { CAPABILITIES_VALID, CAPABILITIES_USABLE, CAPABILITIES_INVALID } Parsed_Capabilities_Validity; #define PARSED_CAPABILITIES_MARKER "CAPA" /** Contains parsed capabilities information */ typedef struct { char marker[4]; // always "CAPA" char * raw_value; bool raw_value_synthesized; char * model; char * mccs_version_string; DDCA_MCCS_Version_Spec parsed_mccs_version; // parsed mccs_version_string, DDCA_VSPEC_UNKNOWN if parsing fails bool raw_cmds_segment_seen; bool raw_cmds_segment_valid; Byte_Value_Array commands; // each stored byte is command id bool raw_vcp_features_seen; GPtrArray * vcp_features; // entries are Capabilities_Feature_Record * Parsed_Capabilities_Validity caps_validity; GPtrArray * messages; } Parsed_Capabilities; Parsed_Capabilities* parse_capabilities_string(char * capabilities); void free_parsed_capabilities(Parsed_Capabilities * pcaps); Bit_Set_256 get_parsed_capabilities_feature_ids(Parsed_Capabilities * pcaps, bool readable_only); bool parsed_capabilities_supports_table_commands(Parsed_Capabilities * pcaps); char * parsed_capabilities_validity_name(Parsed_Capabilities_Validity validity); void dbgrpt_parsed_capabilities(Parsed_Capabilities * pcaps, int depth); void init_parse_capabilities(); // Tests void test_segments(); void test_parse_caps(); #endif /* PARSE_CAPABILITIES_H_ */ ddcutil-2.2.0/src/vcp/parsed_capabilities_feature.h0000644000175000001440000000315214754576332016073 /** \file parsed_capabilitied_feature.h * Parses the description of a VCP feature extracted from a capabilities string. */ // Copyright (C) 2015-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PARSED_CAPABILITIES_FEATURE_H #define PARSED_CAPABILITIES_FEATURE_H #include #include "util/data_structures.h" #include "base/core.h" #include "base/feature_set_ref.h" #include "vcp/vcp_feature_codes.h" // define both for testing #define CFR_BVA // Use Byte_Value_Array for values #undef CFR_BBF // Use Byte_Bit_Flags for values #define CAPABILITIES_FEATURE_MARKER "VCPF" /** Parsed description of a VCP Feature in a capabilities string. */ typedef struct { char marker[4]; ///< always "VCPF" Byte feature_id; ///< VCP feature code Byte_Value_Array values; ///< need unsorted values for feature x72 gamma #ifdef CFR_BBF Byte_Bit_Flags bbflags; // alternative, but sorts values, screws up x72 gamma #endif char * value_string; ///< value substring from capabilities string bool valid_values; ///< string is valid } Capabilities_Feature_Record; Capabilities_Feature_Record * parse_capabilities_feature( Byte feature_id, char * value_string_start, int value_string_len, GPtrArray* error_messages); void free_capabilities_feature_record( Capabilities_Feature_Record * vfr); void dbgrpt_capabilities_feature_record( Capabilities_Feature_Record * vfr, int depth); #endif /* PARSED_CAPABILITIES_FEATURE_H */ ddcutil-2.2.0/src/vcp/persistent_capabilities.h0000644000175000001440000000134614754576332015305 /** \f persistent_capabilities.h */ // Copyright (C) 2021-2023 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef PERSISTENT_CAPABILITIES_H_ #define PERSISTENT_CAPABILITIES_H_ #include "util/error_info.h" #include "base/monitor_model_key.h" bool enable_capabilities_cache(bool onoff); char * capabilities_cache_file_name(); void delete_capabilities_file(); char * get_persistent_capabilities(Monitor_Model_Key* mmk); void set_persistent_capabilites(Monitor_Model_Key* mmk, const char * capabilities); void dbgrpt_capabilities_hash(int depth, const char * msg); void init_persistent_capabilities(); void terminate_persistent_capabilities(); #endif /* PERSISTENT_CAPABILITIES_H_ */ ddcutil-2.2.0/src/vcp/vcp_feature_values.h0000644000175000001440000001011114754576332014244 // vcp_feature_values.h // Copyright (C) 2014-2022 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef VCP_FEATURE_VALUES_H_ #define VCP_FEATURE_VALUES_H_ #include #include "ddcutil_types.h" #include "util/coredefs.h" #include "util/data_structures.h" #include "base/ddc_packets.h" #include "base/feature_metadata.h" #ifdef SINGLE_VCP_VALUE // Removed from API due to complexity. Used only internally. /** Represents a single VCP value of any type */ typedef struct { DDCA_Vcp_Feature_Code opcode; /**< VCP feature code */ DDCA_Vcp_Value_Type value_type; // probably a different type would be better union { struct { uint8_t * bytes; /**< pointer to bytes of table value */ uint16_t bytect; /**< number of bytes in table value */ } t; /**< table value */ struct { uint16_t max_val; /**< maximum value (mh, ml bytes) for continuous value */ uint16_t cur_val; /**< current value (sh, sl bytes) for continuous value */ } c; /**< continuous (C) value */ struct { // __BYTE_ORDER__ ifdef ensures proper overlay of ml/mh on max_val, sl/sh on cur_val #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ uint8_t ml; /**< ML byte for NC value */ uint8_t mh; /**< MH byte for NC value */ uint8_t sl; /**< SL byte for NC value */ uint8_t sh; /**< SH byte for NC value */ #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ uint8_t mh; uint8_t ml; uint8_t sh; uint8_t sl; #else #error "Unexpected byte order value: __BYTE_ORDER__" #endif } nc; /**< non-continuous (NC) value */ } val; } Single_Vcp_Value; #endif char * vcp_value_type_name(DDCA_Vcp_Value_Type value_type); char * vcp_value_type_id(DDCA_Vcp_Value_Type value_type); DDCA_Any_Vcp_Value * create_nontable_vcp_value( Byte feature_code, Byte mh, Byte ml, Byte sh, Byte sl); DDCA_Any_Vcp_Value * create_cont_vcp_value( Byte feature_code, gushort max_val, gushort cur_val); DDCA_Any_Vcp_Value * create_table_vcp_value_by_bytes( Byte feature_code, Byte * bytes, gushort bytect); DDCA_Any_Vcp_Value * create_table_vcp_value_by_buffer( Byte feature_code, Buffer* buffer); DDCA_Any_Vcp_Value * create_single_vcp_value_by_parsed_vcp_response( Byte feature_id, Parsed_Vcp_Response * presp); #ifdef UNUSED Parsed_Vcp_Response * single_vcp_value_to_parsed_vcp_response( DDCA_Any_Vcp_Value * valrec); #endif #ifdef MOVED_TO_FEATURE_METADATA // Simple stripped-down version of Parsed_Nontable_Vcp_Response // for use within vcp_feature_codes.c typedef struct { Byte vcp_code; gushort max_value; gushort cur_value; // for new way Byte mh; Byte ml; Byte sh; Byte sl; } Nontable_Vcp_Value; #endif Nontable_Vcp_Value * single_vcp_value_to_nontable_vcp_value( DDCA_Any_Vcp_Value * valrec); void free_single_vcp_value( DDCA_Any_Vcp_Value * vcp_value); void dbgrpt_single_vcp_value( DDCA_Any_Vcp_Value * valrec, int depth); // void report_any_vcp_value(DDCA_Any_Vcp_Value * valrec, int depth); extern const int summzrize_single_vcp_value_buffer_size; char * summarize_single_vcp_value_r(DDCA_Any_Vcp_Value * valrec, char * buffer, int bufsz); char * summarize_single_vcp_value(DDCA_Any_Vcp_Value * valrec); // Vcp_Value_Set declarations typedef GPtrArray * Vcp_Value_Set; // GPtrArray of DDCA_Single_Vcp_Value Vcp_Value_Set vcp_value_set_new(int initial_size); void free_vcp_value_set(Vcp_Value_Set vset); void vcp_value_set_add(Vcp_Value_Set vset, DDCA_Any_Vcp_Value * pval); int vcp_value_set_size(Vcp_Value_Set vset); DDCA_Any_Vcp_Value * vcp_value_set_get(Vcp_Value_Set vset, int ndx); void dbgrpt_vcp_value_set(Vcp_Value_Set vset, int depth); #endif /* SRC_VCP_VCP_FEATURE_VALUES_H_ */ ddcutil-2.2.0/src/vcp/vcp_feature_codes.h0000644000175000001440000002516514754576332014061 /** @file vcp_feature_codes.h * * Tables describing VCP feature codes and functions to interpret those tables */ // Copyright (C) 2014-2024 Sanford Rockowitz // SPDX-License-Identifier: GPL-2.0-or-later #ifndef VCP_FEATURE_CODES_H_ #define VCP_FEATURE_CODES_H_ /** \cond */ #include #include #include "util/data_structures.h" #include "util/string_util.h" /** \endcond */ #include "public/ddcutil_types.h" #include "base/core.h" #include "base/displays.h" #include "base/ddc_packets.h" #include "base/feature_metadata.h" #include "base/feature_set_ref.h" #include "vcp/vcp_feature_values.h" bool default_table_feature_detail_function( Buffer * data, DDCA_MCCS_Version_Spec vcp_version, char** presult); bool format_feature_detail_debug_continuous( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); bool format_feature_detail_debug_bytes( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); bool format_feature_detail_standard_continuous( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); bool format_feature_detail_sl_lookup( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); bool format_feature_detail_sl_lookup_with_sh( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); bool format_feature_detail_sl_byte( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); bool format_feature_detail_sh_sl_bytes( Nontable_Vcp_Value * code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); // // VCP Feature Interpretation // // Examples of features that create need for complex data structures: // // x62: Audio Volume: // v 2.0: C // v 3.0: NC Values x00 and xff are reserved, x01..xfe are a continuous range // // xdf: VCP Version: // NC, uses both high and low bytes // MCCS specification group to which feature belongs // Note a function can appear in multiple groups, e.g. in different spec versions // Should probably have been made version specific, but it's not worth redoing typedef enum { VCP_SPEC_PRESET = 0x80 , // Section 8.1 Preset Operations VCP_SPEC_IMAGE = 0x40 , // Section 8.2 Image Adjustment VCP_SPEC_CONTROL = 0x20 , // Section 8.3 Display Control VCP_SPEC_GEOMETRY = 0x10 , // Section 8.4 Geometry VCP_SPEC_MISC = 0x08 , // Section 8.5 Miscellaneous Functions VCP_SPEC_AUDIO = 0x04 , // Section 8.6 Audio Functions VCP_SPEC_DPVL = 0x02 , // Section 8.7 DPVL Functions VCP_SPEC_MFG = 0x01 , // Section 8.8 Manufacturer Specific VCP_SPEC_WINDOW = 0x8000 , // Table 5 in MCCS 2.0 spec } Vcp_Spec_Ids; // Set these bits in a flag byte to indicate the MCCS versions for which a feature is valid // #define MCCS_V10 0x01 // #define MCCS_V20 0x02 // #define MCCS_V21 0x04 // #define MCCS_V30 0x08 // #define MCCS_V22 0x10 char * vcp_interpret_global_feature_flags( DDCA_Global_Feature_Flags flags, char * buf, int bufsz); #ifdef MOVED_TO_FEATURE_METADATA typedef bool (*Format_Normal_Feature_Detail_Function) ( Nontable_Vcp_Value* code_info, DDCA_MCCS_Version_Spec vcp_version, char * buffer, int bufsz); typedef bool (*Format_Normal_Feature_Detail_Function2) ( Nontable_Vcp_Value* code_info, // Display_Ref * dref, // DDCA_MCCS_Version_Spec vcp_version, DDCA_Feature_Value_Entry * sl_values, char * buffer, int bufsz); typedef bool (*Format_Table_Feature_Detail_Function) ( Buffer * data_bytes, DDCA_MCCS_Version_Spec vcp_version, char ** p_result_buffer); #endif extern DDCA_Feature_Value_Entry * pxc8_display_controller_type_values; // To consider: // In retrospect this is probably better, but not worth redoing // typedef struct { // char * name; // VCP_Feature_Subset subsets; // Version_Feature_Flags flags; // Feature_Value_Entry * sl_values; // } Version_Specific_Info; #define VCP_FEATURE_TABLE_ENTRY_MARKER "VFTE" typedef struct { char marker[4]; Byte code; char * desc; Format_Normal_Feature_Detail_Function nontable_formatter; Format_Table_Feature_Detail_Function table_formatter; // Format_Normal_Feature_Detail_Function2 dynamic_nc_formatter; // only set for synthetic, udf features DDCA_Global_Feature_Flags vcp_global_flags; gushort vcp_spec_groups; VCP_Feature_Subset vcp_subsets; char * v20_name; char * v21_name; char * v30_name; char * v22_name; DDCA_Version_Feature_Flags v20_flags; DDCA_Version_Feature_Flags v21_flags; DDCA_Version_Feature_Flags v30_flags; DDCA_Version_Feature_Flags v22_flags; DDCA_Feature_Value_Entry * default_sl_values; DDCA_Feature_Value_Entry * v21_sl_values; DDCA_Feature_Value_Entry * v30_sl_values; DDCA_Feature_Value_Entry * v22_sl_values; } VCP_Feature_Table_Entry; void dbgrpt_vcp_entry(VCP_Feature_Table_Entry * pfte, int depth); char * spec_group_names_r( VCP_Feature_Table_Entry * pentry, char * buf, int bufsz); // // Functions that return or destroy a VCP_Feature_Table_Entry // void free_synthetic_vcp_entry( VCP_Feature_Table_Entry * vfte); #ifdef UNUSED VCP_Feature_Table_Entry * vcp_create_dynamic_feature( DDCA_Vcp_Feature_Code id, DDCA_Feature_Metadata * dynamic_metadata); #endif VCP_Feature_Table_Entry * vcp_create_dummy_feature_for_hexid( DDCA_Vcp_Feature_Code id); VCP_Feature_Table_Entry * vcp_create_table_dummy_feature_for_hexid( DDCA_Vcp_Feature_Code id); VCP_Feature_Table_Entry * vcp_find_feature_by_hexid( DDCA_Vcp_Feature_Code id); VCP_Feature_Table_Entry * vcp_find_feature_by_hexid_w_default( DDCA_Vcp_Feature_Code id); // // Functions to extract information from a VCP_Feature_Table_Entry // bool has_version_specific_features( VCP_Feature_Table_Entry * vfte); DDCA_MCCS_Version_Spec get_highest_non_deprecated_version( VCP_Feature_Table_Entry * vfte); bool is_version_conditional_vcp_type( VCP_Feature_Table_Entry * vfte); bool is_feature_supported_in_version( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); bool is_feature_readable_by_vcp_version( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); bool is_feature_writable_by_vcp_version( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); bool is_table_feature_by_vcp_version( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); DDCA_Version_Feature_Flags get_version_specific_feature_flags( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); DDCA_Version_Feature_Flags get_version_sensitive_feature_flags( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); DDCA_Feature_Value_Entry * get_version_specific_sl_values( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); DDCA_Feature_Value_Entry * get_version_sensitive_sl_values( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); DDCA_Feature_Value_Entry * get_highest_version_sl_values( VCP_Feature_Table_Entry* vfte); char * get_version_sensitive_feature_name( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); char * get_version_specific_feature_name( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vcp_version); char * get_non_version_specific_feature_name( VCP_Feature_Table_Entry * pvft_entry); Display_Feature_Metadata * extract_version_feature_info_from_feature_table_entry( VCP_Feature_Table_Entry * vfte, DDCA_MCCS_Version_Spec vspec, bool version_sensitive); // // Functions that query the feature table by VCP feature code // char* get_feature_name_by_id_only( DDCA_Vcp_Feature_Code feature_code); char* get_feature_name_by_id_and_vcp_version( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec); #ifdef MCCS_VERSION_ID Display_Feature_Metadata * get_version_feature_info_by_version_id_dfm( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Id mccs_version_id, bool with_default, bool version_sensitive); #endif Display_Feature_Metadata * get_version_feature_info_by_vspec_dfm( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vspec, bool with_default, bool version_sensitive); // not used externally // DDCA_Feature_Value_Entry * // find_feature_value_table( // DDCA_Vcp_Feature_Code feature_code, // DDCA_MCCS_Version_Spec vcp_version); DDCA_Feature_Value_Entry * find_feature_values_for_capabilities( DDCA_Vcp_Feature_Code feature_code, DDCA_MCCS_Version_Spec vcp_version); // // Report Functions // // // Miscellaneous Functions // bool vcp_format_feature_detail( VCP_Feature_Table_Entry * vcp_entry, DDCA_MCCS_Version_Spec vcp_version, DDCA_Any_Vcp_Value * valrec, char * * aformatted_data ); int vcp_get_feature_code_count(); VCP_Feature_Table_Entry * vcp_get_feature_table_entry(int ndx); void init_vcp_feature_codes(); #endif /* VCP_FEATURE_CODES_H_ */ ddcutil-2.2.0/src/adl/0000755000175000001440000000000014754576332010247 5ddcutil-2.2.0/src/adl/adl_impl/0000755000175000001440000000000014754576332012030 5ddcutil-2.2.0/src/adl/adl_mock_impl/0000755000175000001440000000000014754576332013041 5ddcutil-2.2.0/src/cython/0000755000175000001440000000000014754576332011013 5ddcutil-2.2.0/src/cython/Makefile.in0000644000175000001440000010304514754576332013003 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/cython ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_path_python3.m4 \ $(top_srcdir)/m4/ax_pkg_swig.m4 \ $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/ax_python_env.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/introspection.m4 $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(py3execdir)" "$(DESTDIR)$(pyexecdir)" LTLIBRARIES = $(py3exec_LTLIBRARIES) $(pyexec_LTLIBRARIES) @ENABLE_CYTHON_TRUE@cyddc2_la_DEPENDENCIES = ../libcommon.la \ @ENABLE_CYTHON_TRUE@ ../libddcutil.la @ENABLE_CYTHON_TRUE@nodist_cyddc2_la_OBJECTS = cyddc2_la-cyddc2.lo cyddc2_la_OBJECTS = $(nodist_cyddc2_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = cyddc2_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(cyddc2_la_CFLAGS) \ $(CFLAGS) $(cyddc2_la_LDFLAGS) $(LDFLAGS) -o $@ @ENABLE_CYTHON_TRUE@am_cyddc2_la_rpath = -rpath $(pyexecdir) @ENABLE_CYTHON_TRUE@cyddc3_la_DEPENDENCIES = ../libcommon.la \ @ENABLE_CYTHON_TRUE@ ../libddcutil.la @ENABLE_CYTHON_TRUE@nodist_cyddc3_la_OBJECTS = cyddc3_la-cyddc3.lo cyddc3_la_OBJECTS = $(nodist_cyddc3_la_OBJECTS) cyddc3_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(cyddc3_la_CFLAGS) \ $(CFLAGS) $(cyddc3_la_LDFLAGS) $(LDFLAGS) -o $@ @ENABLE_CYTHON_TRUE@am_cyddc3_la_rpath = -rpath $(py3execdir) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/cyddc2_la-cyddc2.Plo \ ./$(DEPDIR)/cyddc3_la-cyddc3.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(nodist_cyddc2_la_SOURCES) $(nodist_cyddc3_la_SOURCES) DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GOBJECT_CFLAGS = @GOBJECT_CFLAGS@ GOBJECT_LIBS = @GOBJECT_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTROSPECTION_CFLAGS = @INTROSPECTION_CFLAGS@ INTROSPECTION_COMPILER = @INTROSPECTION_COMPILER@ INTROSPECTION_GENERATE = @INTROSPECTION_GENERATE@ INTROSPECTION_GIRDIR = @INTROSPECTION_GIRDIR@ INTROSPECTION_LIBS = @INTROSPECTION_LIBS@ INTROSPECTION_MAKEFILE = @INTROSPECTION_MAKEFILE@ INTROSPECTION_SCANNER = @INTROSPECTION_SCANNER@ INTROSPECTION_TYPELIBDIR = @INTROSPECTION_TYPELIBDIR@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VMAJOR = @PACKAGE_VMAJOR@ PACKAGE_VMICRO = @PACKAGE_VMICRO@ PACKAGE_VMINOR = @PACKAGE_VMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PY2_CFLAGS = @PY2_CFLAGS@ PY2_EXECDIR = @PY2_EXECDIR@ PY2_EXTRA_LDFLAGS = @PY2_EXTRA_LDFLAGS@ PY2_EXTRA_LIBS = @PY2_EXTRA_LIBS@ PY2_LIBS = @PY2_LIBS@ PY3_CFLAGS = @PY3_CFLAGS@ PY3_EXECDIR = @PY3_EXECDIR@ PY3_EXTRA_LDFLAGS = @PY3_EXTRA_LDFLAGS@ PY3_EXTRA_LIBS = @PY3_EXTRA_LIBS@ PY3_LIBS = @PY3_LIBS@ PYEXECDIR = @PYEXECDIR@ PYTHON = @PYTHON@ PYTHON3 = @PYTHON3@ PYTHON3_EXEC_PREFIX = @PYTHON3_EXEC_PREFIX@ PYTHON3_PLATFORM = @PYTHON3_PLATFORM@ PYTHON3_PREFIX = @PYTHON3_PREFIX@ PYTHON3_VERSION = @PYTHON3_VERSION@ PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ PYTHON_PLATFORM = @PYTHON_PLATFORM@ PYTHON_PREFIX = @PYTHON_PREFIX@ PYTHON_VERSION = @PYTHON_VERSION@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ SWIG = @SWIG@ SWIG_LIB = @SWIG_LIB@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ pkgpy3execdir = @pkgpy3execdir@ pkgpyexecdir = @pkgpyexecdir@ pkgpython3dir = @pkgpython3dir@ pkgpythondir = @pkgpythondir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ py2execdir = @py2execdir@ py3execdir = @py3execdir@ pyexecdir = @pyexecdir@ python3dir = @python3dir@ pythondir = @pythondir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ generated_source_files = \ cyddc2.c \ cyddc3.c CLEANFILES = ${generated_source_files} *.so cyddc2.html cyddc3.html # Python extension modules, installed in $(py2execdir) or $(py3execdir) @ENABLE_CYTHON_TRUE@pyexec_LTLIBRARIES = cyddc2.la @ENABLE_CYTHON_TRUE@py3exec_LTLIBRARIES = cyddc3.la # nodist_py3exec_PYTHON = # # Python 2 version # # Module source code, nodist because cyddc2.c is generated @ENABLE_CYTHON_TRUE@nodist_cyddc2_la_SOURCES = cyddc2.c # Flags when compiling files in cyddc2_SOURCES @ENABLE_CYTHON_TRUE@cyddc2_la_CPPFLAGS = -I${top_srcdir}/src -I${top_srcdir}/src/public ${PY2_CFLAGS} @ENABLE_CYTHON_TRUE@cyddc2_la_CFLAGS = $(PYTHON_CFLAGS) # Global and order-independent shared library and program linker config flags and options @ENABLE_CYTHON_TRUE@cyddc2_la_LDFLAGS = -module -shared \ @ENABLE_CYTHON_TRUE@ -export_dynamic -static version_info \ @ENABLE_CYTHON_TRUE@ '@LT_CURRENT@:@LT_REVISION@:@LT_AGE@' # Link in the core library @ENABLE_CYTHON_TRUE@cyddc2_la_LIBADD = \ @ENABLE_CYTHON_TRUE@ ../libcommon.la \ @ENABLE_CYTHON_TRUE@ ../libddcutil.la # # Python 3 version # # nodist because cyddc3.c is generated @ENABLE_CYTHON_TRUE@nodist_cyddc3_la_SOURCES = cyddc3.c # Flags when compiling files in cyddc3_SOURCES @ENABLE_CYTHON_TRUE@cyddc3_la_CPPFLAGS = -I${top_srcdir}/src -I${top_srcdir}/src/public ${PY3_CFLAGS} @ENABLE_CYTHON_TRUE@cyddc3_la_CFLAGS = $(PYTHON3_CFLAGS) # Global and order-independent shared library and program linker config flags and options # -module forces libtool to generate a dynamically loadable module # -static do not link against shared libraries, all external references must be resolved from static libraries # -shared create a shared library # -export-dynamic add all symbols to dynamic symbol table, needed for dlopen # -avoid-version avoid versioning if possible (any effect on Linux?) # -version-info @ENABLE_CYTHON_TRUE@cyddc3_la_LDFLAGS = -module -shared \ @ENABLE_CYTHON_TRUE@ -export_dynamic -static version_info \ @ENABLE_CYTHON_TRUE@ '@LT_CURRENT@:@LT_REVISION@:@LT_AGE@' # Link in the core library @ENABLE_CYTHON_TRUE@cyddc3_la_LIBADD = \ @ENABLE_CYTHON_TRUE@ ../libcommon.la \ @ENABLE_CYTHON_TRUE@ ../libddcutil.la all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/cython/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/cython/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-py3execLTLIBRARIES: $(py3exec_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(py3exec_LTLIBRARIES)'; test -n "$(py3execdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(py3execdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(py3execdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(py3execdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(py3execdir)"; \ } uninstall-py3execLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(py3exec_LTLIBRARIES)'; test -n "$(py3execdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(py3execdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(py3execdir)/$$f"; \ done clean-py3execLTLIBRARIES: -test -z "$(py3exec_LTLIBRARIES)" || rm -f $(py3exec_LTLIBRARIES) @list='$(py3exec_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } install-pyexecLTLIBRARIES: $(pyexec_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(pyexec_LTLIBRARIES)'; test -n "$(pyexecdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(pyexecdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pyexecdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(pyexecdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(pyexecdir)"; \ } uninstall-pyexecLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(pyexec_LTLIBRARIES)'; test -n "$(pyexecdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(pyexecdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(pyexecdir)/$$f"; \ done clean-pyexecLTLIBRARIES: -test -z "$(pyexec_LTLIBRARIES)" || rm -f $(pyexec_LTLIBRARIES) @list='$(pyexec_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } cyddc2.la: $(cyddc2_la_OBJECTS) $(cyddc2_la_DEPENDENCIES) $(EXTRA_cyddc2_la_DEPENDENCIES) $(AM_V_CCLD)$(cyddc2_la_LINK) $(am_cyddc2_la_rpath) $(cyddc2_la_OBJECTS) $(cyddc2_la_LIBADD) $(LIBS) cyddc3.la: $(cyddc3_la_OBJECTS) $(cyddc3_la_DEPENDENCIES) $(EXTRA_cyddc3_la_DEPENDENCIES) $(AM_V_CCLD)$(cyddc3_la_LINK) $(am_cyddc3_la_rpath) $(cyddc3_la_OBJECTS) $(cyddc3_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cyddc2_la-cyddc2.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cyddc3_la-cyddc3.Plo@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< cyddc2_la-cyddc2.lo: cyddc2.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc2_la_CPPFLAGS) $(CPPFLAGS) $(cyddc2_la_CFLAGS) $(CFLAGS) -MT cyddc2_la-cyddc2.lo -MD -MP -MF $(DEPDIR)/cyddc2_la-cyddc2.Tpo -c -o cyddc2_la-cyddc2.lo `test -f 'cyddc2.c' || echo '$(srcdir)/'`cyddc2.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/cyddc2_la-cyddc2.Tpo $(DEPDIR)/cyddc2_la-cyddc2.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cyddc2.c' object='cyddc2_la-cyddc2.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc2_la_CPPFLAGS) $(CPPFLAGS) $(cyddc2_la_CFLAGS) $(CFLAGS) -c -o cyddc2_la-cyddc2.lo `test -f 'cyddc2.c' || echo '$(srcdir)/'`cyddc2.c cyddc3_la-cyddc3.lo: cyddc3.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc3_la_CPPFLAGS) $(CPPFLAGS) $(cyddc3_la_CFLAGS) $(CFLAGS) -MT cyddc3_la-cyddc3.lo -MD -MP -MF $(DEPDIR)/cyddc3_la-cyddc3.Tpo -c -o cyddc3_la-cyddc3.lo `test -f 'cyddc3.c' || echo '$(srcdir)/'`cyddc3.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/cyddc3_la-cyddc3.Tpo $(DEPDIR)/cyddc3_la-cyddc3.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='cyddc3.c' object='cyddc3_la-cyddc3.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc3_la_CPPFLAGS) $(CPPFLAGS) $(cyddc3_la_CFLAGS) $(CFLAGS) -c -o cyddc3_la-cyddc3.lo `test -f 'cyddc3.c' || echo '$(srcdir)/'`cyddc3.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: for dir in "$(DESTDIR)$(py3execdir)" "$(DESTDIR)$(pyexecdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-py3execLTLIBRARIES \ clean-pyexecLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/cyddc2_la-cyddc2.Plo -rm -f ./$(DEPDIR)/cyddc3_la-cyddc3.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-py3execLTLIBRARIES install-pyexecLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/cyddc2_la-cyddc2.Plo -rm -f ./$(DEPDIR)/cyddc3_la-cyddc3.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-py3execLTLIBRARIES uninstall-pyexecLTLIBRARIES .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-py3execLTLIBRARIES \ clean-pyexecLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-py3execLTLIBRARIES install-pyexecLTLIBRARIES \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-py3execLTLIBRARIES uninstall-pyexecLTLIBRARIES .PRECIOUS: Makefile @ENABLE_CYTHON_TRUE@cyddc2.c: cyddc.pyx show_vars @ENABLE_CYTHON_TRUE@ @echo "=====> (src/cython/Makefile) Executing target cyddc2.c" @ENABLE_CYTHON_TRUE@ cython -I${top_srcdir}/src -I{top_srcdir}/src/public -I . -2 -o cyddc2.c -a cyddc.pyx @ENABLE_CYTHON_TRUE@cyddc3.c: cyddc.pyx show_vars @ENABLE_CYTHON_TRUE@ @echo "=====> (src/cython/Makefile) Executing target cyddc.c" @ENABLE_CYTHON_TRUE@ cython -I${top_srcdir}/src -I{top_srcdir}/src/public -I . -3 -o cyddc3.c -a cyddc.pyx # Add show_vars to dependencies for debugging show_vars: @echo " AM_CFLAGS = $(AM_CFLAGS)" @echo " AM_CPPFLAGS = $(AM_CPPFLAGS)" @echo " AX_SWIG_PYTHON_CPPFLAGS = $(AX_SWIG_PYTHON_CPPFLAGS)" @echo " AX_SWIG_PYTHON_LIBS = $(AX_SWIG_PYTHON_LIBS)" @echo " AX_SWIG_PYTHON_OPT = $(AX_SWIG_PYTHON_OPT)" @echo " PYTHON_CFLAGS = $(PYTHON_CFLAGS)" @echo " PYTHON_CPPFLAGS = $(PYTHON_CPPFLAGS)" @echo " PYTHON_EXEC_PREFIX = $(PYTHON_EXEC_PREFIX)" @echo " PYTHON_EXTRA_LDFLAGS = $(PYTHON_EXTRA_LDFLAGS)" @echo " PYTHON_EXTRA_LIBS = $(PYTHON_EXTRA_LIBS)" @echo " PY2_CFLAGS = $(PY2_CFLAGS)" @echo " PY2_LIBS = $(PY2_LIBS)" @echo " PY2_EXTRA_LDFLAGS = $(PY2_EXTRA_LDFLAGS)" @echo " PY2_EXTRA_LIBS = $(PY2_EXTRA_LIBS)" @echo " PY3_CFLAGS = $(PY3_CFLAGS)" @echo " PY3_LIBS = $(PY3_LIBS)" @echo " PY3_EXTRA_LDFLAGS = $(PY3_EXTRA_LDFLAGS)" @echo " PY3_EXTRA_LIBS = $(PY3_EXTRA_LIBS)" @echo " PYTHON_LDFLAGS = $(PYTHON_LDFLAGS)" @echo " PYTHON_LIBS = $(PYTHON_LIBS)" @echo " PYTHON_SITE_PKG = $(PYTHON_SITE_PKG)" @echo " PYTHON_SITE_PKG_EXEC = $(PYTHON_SITE_PKG_EXEC)" @echo " SWIG = $(SWIG) " @echo " SWIG_LIB = $(SWIG_LIB)" @echo " includedir = $(includedir)" @echo " prefix = $(prefix)" @echo " pyexecdir = $(pyexecdir)" @echo " pythondir = $(pythondir)" @echo " py2execdir = $(py2execdir)" @echo " py3execdir = $(py3execdir)" @echo " python3dir = $(python3dir)" @echo " srcdir = $(srcdir)" @echo " top_srcdir = $(top_srcdir)" @echo " LIBS = $(LIBS)" @echo " cyddc2_la_OBJECTS = $(cyddc2_la_OBJECTS)" @echo " cyddc2_la_DEPENDENCIES = $(cyddc2_la_DEPENDENCIES)" @echo " EXTRA_cyddc2_la_DEPENDENCIES = $(EXTRA_cyddc2_la_DEPENDENCIES)" @echo " cyddc2_la_LINK = $(cyddc2_la_LINK)" @echo " am_cyddc2_la_rpath = $(am_cyddc2_la_rpath)" @echo " cyddc2_la_OBJECTS = $(cyddc2_la_OBJECTS)" @echo " cyddc2_la_LIBADD = $(cyddc2_la_LIBADD)" @echo " cyddc3_la_OBJECTS = $(cyddc3_la_OBJECTS)" @echo " cyddc3_la_DEPENDENCIES = $(cyddc3_la_DEPENDENCIES)" @echo " EXTRA_cyddc3_la_DEPENDENCIES = $(EXTRA_cyddc3_la_DEPENDENCIES)" @echo " cyddc3_la_LINK = $(cyddc3_la_LINK)" @echo " am_cyddc3_la_rpath = $(am_cyddc3_la_rpath)" @echo " cyddc3_la_OBJECTS = $(cyddc3_la_OBJECTS)" @echo " cyddc3_la_LIBADD = $(cyddc3_la_LIBADD)" # ld vars: #@echo " PY2_EXECDIR = $(PY2_EXECDIR)" # @echo " PY3_EXECDIR = $(PY3_EXECDIR)" .PHONY: show_vars # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/cython/Makefile0000644000175000001440000007637614754576332012416 # Makefile.in generated by automake 1.16.5 from Makefile.am. # src/cython/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/ddcutil pkgincludedir = $(includedir)/ddcutil pkglibdir = $(libdir)/ddcutil pkglibexecdir = $(libexecdir)/ddcutil am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-pc-linux-gnu host_triplet = x86_64-pc-linux-gnu subdir = src/cython ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_path_python3.m4 \ $(top_srcdir)/m4/ax_pkg_swig.m4 \ $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/ax_python_env.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/introspection.m4 $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(py3execdir)" "$(DESTDIR)$(pyexecdir)" LTLIBRARIES = $(py3exec_LTLIBRARIES) $(pyexec_LTLIBRARIES) #cyddc2_la_DEPENDENCIES = ../libcommon.la \ # ../libddcutil.la #nodist_cyddc2_la_OBJECTS = cyddc2_la-cyddc2.lo cyddc2_la_OBJECTS = $(nodist_cyddc2_la_OBJECTS) AM_V_lt = $(am__v_lt_$(V)) am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) am__v_lt_0 = --silent am__v_lt_1 = cyddc2_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(cyddc2_la_CFLAGS) \ $(CFLAGS) $(cyddc2_la_LDFLAGS) $(LDFLAGS) -o $@ #am_cyddc2_la_rpath = -rpath $(pyexecdir) #cyddc3_la_DEPENDENCIES = ../libcommon.la \ # ../libddcutil.la #nodist_cyddc3_la_OBJECTS = cyddc3_la-cyddc3.lo cyddc3_la_OBJECTS = $(nodist_cyddc3_la_OBJECTS) cyddc3_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(cyddc3_la_CFLAGS) \ $(CFLAGS) $(cyddc3_la_LDFLAGS) $(LDFLAGS) -o $@ #am_cyddc3_la_rpath = -rpath $(py3execdir) AM_V_P = $(am__v_P_$(V)) am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY)) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I. -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/cyddc2_la-cyddc2.Plo \ ./$(DEPDIR)/cyddc3_la-cyddc3.Plo am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(nodist_cyddc2_la_SOURCES) $(nodist_cyddc3_la_SOURCES) DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} '/shared/playproj/i2c/config/missing' aclocal-1.16 AMTAR = $${TAR-tar} AM_DEFAULT_VERBOSITY = 0 AR = ar AUTOCONF = ${SHELL} '/shared/playproj/i2c/config/missing' autoconf AUTOHEADER = ${SHELL} '/shared/playproj/i2c/config/missing' autoheader AUTOMAKE = ${SHELL} '/shared/playproj/i2c/config/missing' automake-1.16 AWK = gawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 CPPFLAGS = CSCOPE = cscope CTAGS = ctags CYGPATH_W = echo DBG = DEFS = -DHAVE_CONFIG_H DEPDIR = .deps DLLTOOL = false DOCBASE_INSTALL_DOCS = install-docs DOXYGEN = DOXYGEN_PAPER_SIZE = DSYMUTIL = DUMPBIN = DX_CONFIG = DX_DOCDIR = DX_DOT = DX_DOXYGEN = DX_DVIPS = DX_EGREP = DX_ENV = DX_FLAG_chi = DX_FLAG_chm = DX_FLAG_doc = DX_FLAG_dot = DX_FLAG_html = DX_FLAG_man = DX_FLAG_pdf = DX_FLAG_ps = DX_FLAG_rtf = DX_FLAG_xml = DX_HHC = DX_LATEX = DX_MAKEINDEX = DX_PDFLATEX = DX_PERL = DX_PROJECT = ECHO_C = ECHO_N = -n ECHO_T = EGREP = /usr/bin/grep -E ENABLE_ENVCMDS_FLAG = 1 ENABLE_SHARED_LIB_FLAG = 1 ENABLE_TARGETBSD_FLAG = 0 ENABLE_UDEV_FLAG = 1 ENABLE_USB_FLAG = 1 ETAGS = etags EXEEXT = FGREP = /usr/bin/grep -F FILECMD = file GLIB_CFLAGS = -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include GLIB_LIBS = -lglib-2.0 GOBJECT_CFLAGS = GOBJECT_LIBS = GREP = /usr/bin/grep INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s INTROSPECTION_CFLAGS = -I/usr/include/gobject-introspection-1.0 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include INTROSPECTION_COMPILER = /usr/bin/g-ir-compiler INTROSPECTION_GENERATE = /usr/bin/g-ir-generate INTROSPECTION_GIRDIR = /usr/share/gir-1.0 INTROSPECTION_LIBS = -lgirepository-1.0 -lgobject-2.0 -lglib-2.0 INTROSPECTION_MAKEFILE = /usr/share/gobject-introspection-1.0/Makefile.introspection INTROSPECTION_SCANNER = /usr/bin/g-ir-scanner INTROSPECTION_TYPELIBDIR = /usr/lib/x86_64-linux-gnu/girepository-1.0 LD = /usr/bin/ld -m elf_x86_64 LDFLAGS = LIBDRM_CFLAGS = -I/usr/include/libdrm LIBDRM_LIBS = -ldrm LIBOBJS = LIBS = LIBTOOL = $(SHELL) $(top_builddir)/libtool LIBTOOL_DEPS = ./config//ltmain.sh LIBUSB_CFLAGS = -I/usr/include/libusb-1.0 LIBUSB_LIBS = -lusb-1.0 LIBX11_CFLAGS = LIBX11_LIBS = -lX11 LIPO = LN_S = ln -s LTLIBOBJS = LT_AGE = 0 LT_CURRENT = 4 LT_REVISION = 0 LT_SYS_LIBRARY_PATH = MAKEINFO = ${SHELL} '/shared/playproj/i2c/config/missing' makeinfo MANIFEST_TOOL = : MKDIR_P = /usr/bin/mkdir -p NM = /usr/bin/nm -B NMEDIT = OBJDUMP = objdump OBJEXT = o OTOOL = OTOOL64 = PACKAGE = ddcutil PACKAGE_BUGREPORT = rockowitz@minsoft.com PACKAGE_NAME = ddcutil PACKAGE_STRING = ddcutil 1.0.0 PACKAGE_TARNAME = ddcutil PACKAGE_URL = PACKAGE_VERSION = 1.0.0 PACKAGE_VMAJOR = 1 PACKAGE_VMICRO = 0 PACKAGE_VMINOR = 0 PATH_SEPARATOR = : PKG_CONFIG = /usr/bin/pkg-config PKG_CONFIG_LIBDIR = PKG_CONFIG_PATH = PY2_CFLAGS = PY2_EXECDIR = PY2_EXTRA_LDFLAGS = PY2_EXTRA_LIBS = PY2_LIBS = PY3_CFLAGS = PY3_EXECDIR = PY3_EXTRA_LDFLAGS = PY3_EXTRA_LIBS = PY3_LIBS = PYEXECDIR = PYTHON = PYTHON3 = PYTHON3_EXEC_PREFIX = PYTHON3_PLATFORM = PYTHON3_PREFIX = PYTHON3_VERSION = PYTHON_EXEC_PREFIX = PYTHON_PLATFORM = PYTHON_PREFIX = PYTHON_VERSION = RANLIB = ranlib REQUIRED_PACKAGES = glib-2.0 >= 2.32 xrandr x11 SED = /usr/bin/sed SET_MAKE = SHELL = /bin/bash STRIP = strip SWIG = SWIG_LIB = UDEV_CFLAGS = UDEV_LIBS = -ludev VERSION = 1.0.0 XRANDR_CFLAGS = XRANDR_LIBS = -lXrandr ZLIB_CFLAGS = ZLIB_LIBS = -lz abs_builddir = /shared/playproj/i2c/src/cython abs_srcdir = /shared/playproj/i2c/src/cython abs_top_builddir = /shared/playproj/i2c abs_top_srcdir = /shared/playproj/i2c ac_ct_AR = ar ac_ct_CC = gcc ac_ct_DUMPBIN = am__include = include am__leading_dot = . am__quote = am__tar = $${TAR-tar} chof - "$$tardir" am__untar = $${TAR-tar} xf - bindir = ${exec_prefix}/bin build = x86_64-pc-linux-gnu build_alias = build_cpu = x86_64 build_os = linux-gnu build_vendor = pc builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = x86_64-pc-linux-gnu host_alias = host_cpu = x86_64 host_os = linux-gnu host_vendor = pc htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /shared/playproj/i2c/config/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = $(MKDIR_P) oldincludedir = /usr/include pdfdir = ${docdir} pkgpy3execdir = pkgpyexecdir = pkgpython3dir = pkgpythondir = prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} py2execdir = py3execdir = pyexecdir = python3dir = pythondir = runstatedir = ${localstatedir}/run sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = top_build_prefix = ../../ top_builddir = ../.. top_srcdir = ../.. generated_source_files = \ cyddc2.c \ cyddc3.c CLEANFILES = ${generated_source_files} *.so cyddc2.html cyddc3.html # Python extension modules, installed in $(py2execdir) or $(py3execdir) #pyexec_LTLIBRARIES = cyddc2.la #py3exec_LTLIBRARIES = cyddc3.la # nodist_py3exec_PYTHON = # # Python 2 version # # Module source code, nodist because cyddc2.c is generated #nodist_cyddc2_la_SOURCES = cyddc2.c # Flags when compiling files in cyddc2_SOURCES #cyddc2_la_CPPFLAGS = -I${top_srcdir}/src -I${top_srcdir}/src/public ${PY2_CFLAGS} #cyddc2_la_CFLAGS = $(PYTHON_CFLAGS) # Global and order-independent shared library and program linker config flags and options #cyddc2_la_LDFLAGS = -module -shared \ # -export_dynamic -static version_info \ # '4:0:0' # Link in the core library #cyddc2_la_LIBADD = \ # ../libcommon.la \ # ../libddcutil.la # # Python 3 version # # nodist because cyddc3.c is generated #nodist_cyddc3_la_SOURCES = cyddc3.c # Flags when compiling files in cyddc3_SOURCES #cyddc3_la_CPPFLAGS = -I${top_srcdir}/src -I${top_srcdir}/src/public ${PY3_CFLAGS} #cyddc3_la_CFLAGS = $(PYTHON3_CFLAGS) # Global and order-independent shared library and program linker config flags and options # -module forces libtool to generate a dynamically loadable module # -static do not link against shared libraries, all external references must be resolved from static libraries # -shared create a shared library # -export-dynamic add all symbols to dynamic symbol table, needed for dlopen # -avoid-version avoid versioning if possible (any effect on Linux?) # -version-info #cyddc3_la_LDFLAGS = -module -shared \ # -export_dynamic -static version_info \ # '4:0:0' # Link in the core library #cyddc3_la_LIBADD = \ # ../libcommon.la \ # ../libddcutil.la all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/cython/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/cython/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-py3execLTLIBRARIES: $(py3exec_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(py3exec_LTLIBRARIES)'; test -n "$(py3execdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(py3execdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(py3execdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(py3execdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(py3execdir)"; \ } uninstall-py3execLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(py3exec_LTLIBRARIES)'; test -n "$(py3execdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(py3execdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(py3execdir)/$$f"; \ done clean-py3execLTLIBRARIES: -test -z "$(py3exec_LTLIBRARIES)" || rm -f $(py3exec_LTLIBRARIES) @list='$(py3exec_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } install-pyexecLTLIBRARIES: $(pyexec_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(pyexec_LTLIBRARIES)'; test -n "$(pyexecdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(pyexecdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pyexecdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(pyexecdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(pyexecdir)"; \ } uninstall-pyexecLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(pyexec_LTLIBRARIES)'; test -n "$(pyexecdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(pyexecdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(pyexecdir)/$$f"; \ done clean-pyexecLTLIBRARIES: -test -z "$(pyexec_LTLIBRARIES)" || rm -f $(pyexec_LTLIBRARIES) @list='$(pyexec_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } cyddc2.la: $(cyddc2_la_OBJECTS) $(cyddc2_la_DEPENDENCIES) $(EXTRA_cyddc2_la_DEPENDENCIES) $(AM_V_CCLD)$(cyddc2_la_LINK) $(am_cyddc2_la_rpath) $(cyddc2_la_OBJECTS) $(cyddc2_la_LIBADD) $(LIBS) cyddc3.la: $(cyddc3_la_OBJECTS) $(cyddc3_la_DEPENDENCIES) $(EXTRA_cyddc3_la_DEPENDENCIES) $(AM_V_CCLD)$(cyddc3_la_LINK) $(am_cyddc3_la_rpath) $(cyddc3_la_OBJECTS) $(cyddc3_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c include ./$(DEPDIR)/cyddc2_la-cyddc2.Plo # am--include-marker include ./$(DEPDIR)/cyddc3_la-cyddc3.Plo # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @echo '# dummy' >$@-t && $(am__mv) $@-t $@ am--depfiles: $(am__depfiles_remade) .c.o: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ $(am__mv) $$depbase.Tpo $$depbase.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c -o $@ $< .c.obj: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ $(am__mv) $$depbase.Tpo $$depbase.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ $(am__mv) $$depbase.Tpo $$depbase.Plo # $(AM_V_CC)source='$<' object='$@' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LTCOMPILE) -c -o $@ $< cyddc2_la-cyddc2.lo: cyddc2.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc2_la_CPPFLAGS) $(CPPFLAGS) $(cyddc2_la_CFLAGS) $(CFLAGS) -MT cyddc2_la-cyddc2.lo -MD -MP -MF $(DEPDIR)/cyddc2_la-cyddc2.Tpo -c -o cyddc2_la-cyddc2.lo `test -f 'cyddc2.c' || echo '$(srcdir)/'`cyddc2.c $(AM_V_at)$(am__mv) $(DEPDIR)/cyddc2_la-cyddc2.Tpo $(DEPDIR)/cyddc2_la-cyddc2.Plo # $(AM_V_CC)source='cyddc2.c' object='cyddc2_la-cyddc2.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc2_la_CPPFLAGS) $(CPPFLAGS) $(cyddc2_la_CFLAGS) $(CFLAGS) -c -o cyddc2_la-cyddc2.lo `test -f 'cyddc2.c' || echo '$(srcdir)/'`cyddc2.c cyddc3_la-cyddc3.lo: cyddc3.c $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc3_la_CPPFLAGS) $(CPPFLAGS) $(cyddc3_la_CFLAGS) $(CFLAGS) -MT cyddc3_la-cyddc3.lo -MD -MP -MF $(DEPDIR)/cyddc3_la-cyddc3.Tpo -c -o cyddc3_la-cyddc3.lo `test -f 'cyddc3.c' || echo '$(srcdir)/'`cyddc3.c $(AM_V_at)$(am__mv) $(DEPDIR)/cyddc3_la-cyddc3.Tpo $(DEPDIR)/cyddc3_la-cyddc3.Plo # $(AM_V_CC)source='cyddc3.c' object='cyddc3_la-cyddc3.lo' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(cyddc3_la_CPPFLAGS) $(CPPFLAGS) $(cyddc3_la_CFLAGS) $(CFLAGS) -c -o cyddc3_la-cyddc3.lo `test -f 'cyddc3.c' || echo '$(srcdir)/'`cyddc3.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: for dir in "$(DESTDIR)$(py3execdir)" "$(DESTDIR)$(pyexecdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-py3execLTLIBRARIES \ clean-pyexecLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/cyddc2_la-cyddc2.Plo -rm -f ./$(DEPDIR)/cyddc3_la-cyddc3.Plo -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-py3execLTLIBRARIES install-pyexecLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/cyddc2_la-cyddc2.Plo -rm -f ./$(DEPDIR)/cyddc3_la-cyddc3.Plo -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-py3execLTLIBRARIES uninstall-pyexecLTLIBRARIES .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \ clean-generic clean-libtool clean-py3execLTLIBRARIES \ clean-pyexecLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-py3execLTLIBRARIES install-pyexecLTLIBRARIES \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-py3execLTLIBRARIES uninstall-pyexecLTLIBRARIES .PRECIOUS: Makefile #cyddc2.c: cyddc.pyx show_vars # @echo "=====> (src/cython/Makefile) Executing target cyddc2.c" # cython -I${top_srcdir}/src -I{top_srcdir}/src/public -I . -2 -o cyddc2.c -a cyddc.pyx #cyddc3.c: cyddc.pyx show_vars # @echo "=====> (src/cython/Makefile) Executing target cyddc.c" # cython -I${top_srcdir}/src -I{top_srcdir}/src/public -I . -3 -o cyddc3.c -a cyddc.pyx # Add show_vars to dependencies for debugging show_vars: @echo " AM_CFLAGS = $(AM_CFLAGS)" @echo " AM_CPPFLAGS = $(AM_CPPFLAGS)" @echo " AX_SWIG_PYTHON_CPPFLAGS = $(AX_SWIG_PYTHON_CPPFLAGS)" @echo " AX_SWIG_PYTHON_LIBS = $(AX_SWIG_PYTHON_LIBS)" @echo " AX_SWIG_PYTHON_OPT = $(AX_SWIG_PYTHON_OPT)" @echo " PYTHON_CFLAGS = $(PYTHON_CFLAGS)" @echo " PYTHON_CPPFLAGS = $(PYTHON_CPPFLAGS)" @echo " PYTHON_EXEC_PREFIX = $(PYTHON_EXEC_PREFIX)" @echo " PYTHON_EXTRA_LDFLAGS = $(PYTHON_EXTRA_LDFLAGS)" @echo " PYTHON_EXTRA_LIBS = $(PYTHON_EXTRA_LIBS)" @echo " PY2_CFLAGS = $(PY2_CFLAGS)" @echo " PY2_LIBS = $(PY2_LIBS)" @echo " PY2_EXTRA_LDFLAGS = $(PY2_EXTRA_LDFLAGS)" @echo " PY2_EXTRA_LIBS = $(PY2_EXTRA_LIBS)" @echo " PY3_CFLAGS = $(PY3_CFLAGS)" @echo " PY3_LIBS = $(PY3_LIBS)" @echo " PY3_EXTRA_LDFLAGS = $(PY3_EXTRA_LDFLAGS)" @echo " PY3_EXTRA_LIBS = $(PY3_EXTRA_LIBS)" @echo " PYTHON_LDFLAGS = $(PYTHON_LDFLAGS)" @echo " PYTHON_LIBS = $(PYTHON_LIBS)" @echo " PYTHON_SITE_PKG = $(PYTHON_SITE_PKG)" @echo " PYTHON_SITE_PKG_EXEC = $(PYTHON_SITE_PKG_EXEC)" @echo " SWIG = $(SWIG) " @echo " SWIG_LIB = $(SWIG_LIB)" @echo " includedir = $(includedir)" @echo " prefix = $(prefix)" @echo " pyexecdir = $(pyexecdir)" @echo " pythondir = $(pythondir)" @echo " py2execdir = $(py2execdir)" @echo " py3execdir = $(py3execdir)" @echo " python3dir = $(python3dir)" @echo " srcdir = $(srcdir)" @echo " top_srcdir = $(top_srcdir)" @echo " LIBS = $(LIBS)" @echo " cyddc2_la_OBJECTS = $(cyddc2_la_OBJECTS)" @echo " cyddc2_la_DEPENDENCIES = $(cyddc2_la_DEPENDENCIES)" @echo " EXTRA_cyddc2_la_DEPENDENCIES = $(EXTRA_cyddc2_la_DEPENDENCIES)" @echo " cyddc2_la_LINK = $(cyddc2_la_LINK)" @echo " am_cyddc2_la_rpath = $(am_cyddc2_la_rpath)" @echo " cyddc2_la_OBJECTS = $(cyddc2_la_OBJECTS)" @echo " cyddc2_la_LIBADD = $(cyddc2_la_LIBADD)" @echo " cyddc3_la_OBJECTS = $(cyddc3_la_OBJECTS)" @echo " cyddc3_la_DEPENDENCIES = $(cyddc3_la_DEPENDENCIES)" @echo " EXTRA_cyddc3_la_DEPENDENCIES = $(EXTRA_cyddc3_la_DEPENDENCIES)" @echo " cyddc3_la_LINK = $(cyddc3_la_LINK)" @echo " am_cyddc3_la_rpath = $(am_cyddc3_la_rpath)" @echo " cyddc3_la_OBJECTS = $(cyddc3_la_OBJECTS)" @echo " cyddc3_la_LIBADD = $(cyddc3_la_LIBADD)" # ld vars: #@echo " PY2_EXECDIR = $(PY2_EXECDIR)" # @echo " PY3_EXECDIR = $(PY3_EXECDIR)" .PHONY: show_vars # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/src/gobject_api/0000755000175000001440000000000014754576332011755 5ddcutil-2.2.0/Makefile.am0000644000175000001440000001132414754153540010665 # Top level Makefile.am # Copyright (C) 2014-2023 Sanford Rockowitz # SPDX-License-Identifier: GPL-2.0-or-later # To automatically update libtool script if it becomes out of date LIBTOOL_DEPS = @LIBTOOL_DEPS@ # From autoconf manual: # ... if you use aclocal from Automake to generate aclocal.m4, you must also # set ACLOCAL_AMFLAGS = -I dir in your top-level Makefile.am. # Due to a limitation in the Autoconf implementation of autoreconf, these # include directives currently must be set on a single line in Makefile.am, # without any backslash-newlines # Introspection does this. ACLOCAL_AMFLAGS = -I m4 ${ACLOCAL_FLAGS} DIST_SUBDIRS = src man data docs EXTRA_DIST = README.md NEWS.md CHANGELOG.md EXTRA_DIST += m4/ax_prog_doxygen.m4 if USE_DOXYGEN DOXYDIR = docs endif SUBDIRS = src man data $(DOXYDIR) # if ENABLE_GOBJECT_COND DISTCHECK_CONFIGURE_FLAGS = --enable-introspection # endif EXTRA_DIST += m4/introspection.m4 # install-data-local: # @echo "(Makefile) install-data-local):" # @echo " docdir = $(docdir)" if ENABLE_SHARED_LIB_COND libddcdocdir = $(datarootdir)/doc/libddcutil # libddcdoc_DATA = AUTHORS endif dist-hook: echo "(Makefile) Executing dist-hook..." chmod a-x ${distdir}/AUTHORS ${distdir}/COPYING ${distdir}/README.md find ${distdir} -name "*~" -exec rm -v {} \; find ${distdir} -name "*.ctl" -exec rm -v {} \; find ${distdir} -name "*.lst" -exec rm -v {} \; find ${distdir} -name "*.la" -exec rm -v {} \; find ${distdir} -name "*.old" -exec rm -v {} \; find ${distdir} -name "*.new" -exec rm -v {} \; find ${distdir} -name "*.tmp" -exec rm -v {} \; find ${distdir} -name "*old" -type d -prune -exec rm -fv {} \; find ${distdir} -name "*new" -type d -prune -exec rm -fv {} \; find ${distdir} -name ".gitignore" -exec rm -v {} \; rm -rfv ${distdir}/.github # Too many false positives: # alpha.clone.CloneChecker # alpha.deadcode.UnreachableCode # alpha.core.CastToStruct # Copied and adapted from colord # is calling autogen.sh within this file dangerous? clang: $(MAKE) clean; \ rm -rf clang; \ scan-build --use-analyzer=/usr/bin/clang \ -o clang-report \ ./autogen.sh \ --disable_gobject_api \ --enable-cffi \ --enable-cython \ ; \ scan-build --use-analyzer=/usr/bin/clang \ -o clang-report \ -enable-checker alpha.core.CastSize \ -enable-checker alpha.core.BoolAssignment \ -enable-checker alpha.core.Conversion \ -enable-checker alpha.core.SizeofPtr \ make # $(foreach v, $(.VARIABLES), @echo "$v = $$v") show: @echo "---> Show variables" @echo "" @echo "Set by PKG_CHECK_MODULES:" @echo " GLIB_CFLAGS = $(GLIB_CFLAGS) " @echo " GLIB_LIBS = $(GLIB_LIBS)" @echo " JANSSON_LIBS = $(JANSSON_LIBS)" @echo " JANSSON_CFLAGS = $(JANSSON_CFLAGS)" @echo " UDEV_CFLAGS = $(UDEV_CFLAGS)" @echo " UDEV_LIBS = $(UDEV_LIBS)" @echo " SYSTEMD_CFLAGS = $(SYSTEMD_CFLAGS)" @echo " SYSTEMD_LIBS = $(SYSTEMD_LIBS)" @echo " LIBUSB_CFLAGS = $(LIBUSB_CFLAGS)" @echo " LIBUSB_LIBS = $(LIBUSB_LIBS)" @echo "" @echo "Addtional:" @echo " prefix = $(prefix)" @echo " exec_prefix = $(exec_prefix)" @echo " libdir = $(libdir)" @echo " libexecdir = $(libexecdir)" @echo " top_srcdir = $(top_srcdir)" @echo " srcdir = $(srcdir)" @echo " pkgconfigdir: = ${pkgconfigdir}" @echo "" @echo " CFLAGS = $(CFLAGS)" @echo " CPPFLAGS = $(CPPFLAGS)" @echo " LDFLAGS = $(LDFLAGS)" .PHONY: clang show # ldconfig fails when executed in pbuilder due to permissions # just have to tell users to run it manually # install-exec-local: # @echo "(install-exec-local):" # ldconfig # uninstall-local: # @echo "(uninstall-local):=" # ldconfig # Rename to "all-local" for development all-local-disabled: @echo "" @echo "(Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" ddcutil-2.2.0/configure0000775000175000001440000234010114754576150010550 #! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.72 for ddcutil 2.2.0. # # Report bugs to . # # # Copyright (C) 1992-1996, 1998-2017, 2020-2023 Free Software Foundation, # Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case e in #( e) case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac ;; esac fi # Reset variables that may have inherited troublesome values from # the environment. # IFS needs to be set, to space, tab, and newline, in precisely that order. # (If _AS_PATH_WALK were called with IFS unset, it would have the # side effect of setting IFS to empty, thus disabling word splitting.) # Quoting is to prevent editors from complaining about space-tab. as_nl=' ' export as_nl IFS=" "" $as_nl" PS1='$ ' PS2='> ' PS4='+ ' # Ensure predictable behavior from utilities with locale-dependent output. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # We cannot yet rely on "unset" to work, but we need these variables # to be unset--not just set to an empty or harmless value--now, to # avoid bugs in old shells (e.g. pre-3.0 UWIN ksh). This construct # also avoids known problems related to "unset" and subshell syntax # in other old shells (e.g. bash 2.01 and pdksh 5.2.14). for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH do eval test \${$as_var+y} \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done # Ensure that fds 0, 1, and 2 are open. if (exec 3>&0) 2>/dev/null; then :; else exec 0&1) 2>/dev/null; then :; else exec 1>/dev/null; fi if (exec 3>&2) ; then :; else exec 2>/dev/null; fi # The user is always right. if ${PATH_SEPARATOR+false} :; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac test -r "$as_dir$0" && as_myself=$as_dir$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as 'sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed 'exec'. printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test \${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case e in #( e) case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ) then : else case e in #( e) exitcode=1; echo positional parameters were not saved. ;; esac fi test x\$exitcode = x0 || exit 1 blah=\$(echo \$(echo blah)) test x\"\$blah\" = xblah || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null then : as_have_required=yes else case e in #( e) as_have_required=no ;; esac fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null then : else case e in #( e) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && as_run=a "$as_shell" -c "$as_bourne_compatible""$as_required" 2>/dev/null then : CONFIG_SHELL=$as_shell as_have_required=yes if as_run=a "$as_shell" -c "$as_bourne_compatible""$as_suggested" 2>/dev/null then : break 2 fi fi done;; esac as_found=false done IFS=$as_save_IFS if $as_found then : else case e in #( e) if { test -f "$SHELL" || test -f "$SHELL.exe"; } && as_run=a "$SHELL" -c "$as_bourne_compatible""$as_required" 2>/dev/null then : CONFIG_SHELL=$SHELL as_have_required=yes fi ;; esac fi if test "x$CONFIG_SHELL" != x then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed 'exec'. printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno then : printf "%s\n" "$0: This script requires a shell more modern than all" printf "%s\n" "$0: the shells that I found on your system." if test ${ZSH_VERSION+y} ; then printf "%s\n" "$0: In particular, zsh $ZSH_VERSION has bugs and should" printf "%s\n" "$0: be upgraded to zsh 4.3.4 or later." else printf "%s\n" "$0: Please tell bug-autoconf@gnu.org and $0: rockowitz@minsoft.com about your system, including any $0: error possibly output before this message. Then install $0: a modern shell, or manually run the script under such a $0: shell if you do have one." fi exit 1 fi ;; esac fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null then : eval 'as_fn_append () { eval $1+=\$2 }' else case e in #( e) as_fn_append () { eval $1=\$$1\$2 } ;; esac fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null then : eval 'as_fn_arith () { as_val=$(( $* )) }' else case e in #( e) as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } ;; esac fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi printf "%s\n" "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' t clear :clear s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { printf "%s\n" "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } # Determine whether it's possible to make 'echo' print without a newline. # These variables are no longer used directly by Autoconf, but are AC_SUBSTed # for compatibility with existing Makefiles. ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac # For backward compatibility with old third-party macros, we provide # the shell variables $as_echo and $as_echo_n. New code should use # AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively. as_echo='printf %s\n' as_echo_n='printf %s' rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both 'ln -s file dir' and 'ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; 'ln -s' creates a wrapper executable. # In both cases, we have to default to 'cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_sed_cpp="y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g" as_tr_cpp="eval sed '$as_sed_cpp'" # deprecated # Sed expression to map a string onto a valid variable name. as_sed_sh="y%*+%pp%;s%[^_$as_cr_alnum]%_%g" as_tr_sh="eval sed '$as_sed_sh'" # deprecated SHELL=${CONFIG_SHELL-/bin/sh} test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='ddcutil' PACKAGE_TARNAME='ddcutil' PACKAGE_VERSION='2.2.0' PACKAGE_STRING='ddcutil 2.2.0' PACKAGE_BUGREPORT='rockowitz@minsoft.com' PACKAGE_URL='' ac_unique_file="src/util/coredefs.h" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_STDIO_H # include #endif #ifdef HAVE_STDLIB_H # include #endif #ifdef HAVE_STRING_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_header_c_list= ac_subst_vars='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS REQUIRED_PACKAGES ZLIB_LIBS ZLIB_CFLAGS HAVE_DOCBASE_FALSE HAVE_DOCBASE_TRUE DOCBASE_INSTALL_DOCS USE_DOXYGEN_FALSE USE_DOXYGEN_TRUE DX_RULES PAPER_SIZE DOXYGEN_PAPER_SIZE GENERATE_LATEX DX_PDFLATEX DX_FLAG_pdf DX_EGREP DX_DVIPS DX_MAKEINDEX DX_LATEX DX_FLAG_ps DX_FLAG_html GENERATE_CHI DX_FLAG_chi GENERATE_HTMLHELP GENERATE_HTML HHC_PATH DX_HHC DX_FLAG_chm GENERATE_XML DX_FLAG_xml GENERATE_RTF DX_FLAG_rtf GENERATE_MAN DX_FLAG_man DOT_PATH HAVE_DOT DX_DOT DX_FLAG_dot PERL_PATH DX_PERL DX_DOXYGEN DX_FLAG_doc PROJECT SRCDIR DX_ENV DX_DOCDIR DX_CONFIG DX_PROJECT DOXYGEN USE_X11_COND_FALSE USE_X11_COND_TRUE XEXT_LIBS XEXT_CFLAGS XRANDR_LIBS XRANDR_CFLAGS LIBX11_LIBS LIBX11_CFLAGS USE_LIBDRM_COND_FALSE USE_LIBDRM_COND_TRUE LIBDRM_LIBS LIBDRM_CFLAGS LIBUSB_LIBS LIBUSB_CFLAGS UDEV_LIBS UDEV_CFLAGS JANSSON_LIBS JANSSON_CFLAGS GLIB_LIBS GLIB_CFLAGS LIBOBJS ENABLE_FORCE_SUSE_COND_FALSE ENABLE_FORCE_SUSE_COND_TRUE ENABLE_FAILSIM_COND_FALSE ENABLE_FAILSIM_COND_TRUE ENABLE_CALLGRAPH_COND_FALSE ENABLE_CALLGRAPH_COND_TRUE INCLUDE_TESTCASES_COND_FALSE INCLUDE_TESTCASES_COND_TRUE ENABLE_USB_FLAG ENABLE_USB_COND_FALSE ENABLE_USB_COND_TRUE ENABLE_UDEV_FLAG ENABLE_UDEV_COND_FALSE ENABLE_UDEV_COND_TRUE ENABLE_ENVCMDS_FLAG ENABLE_ENVCMDS_COND_FALSE ENABLE_ENVCMDS_COND_TRUE ENABLE_TARGETBSD_FLAG ENABLE_TARGETBSD_COND_FALSE ENABLE_TARGETBSD_COND_TRUE ENABLE_DOXYGEN_COND_FALSE ENABLE_DOXYGEN_COND_TRUE ASAN_COND_FALSE ASAN_COND_TRUE STATIC_FUNCTIONS_VISIBLE_COND_FALSE STATIC_FUNCTIONS_VISIBLE_COND_TRUE ENABLE_BUILD_TIMESTAMP_FLAG ENABLE_BUILD_TIMESTAMP_COND_FALSE ENABLE_BUILD_TIMESTAMP_COND_TRUE INSTALL_LIB_ONLY_COND_FALSE INSTALL_LIB_ONLY_COND_TRUE ENABLE_SHARED_LIB_FLAG ENABLE_SHARED_LIB_COND_FALSE ENABLE_SHARED_LIB_COND_TRUE HAVE_ADL_COND_FALSE HAVE_ADL_COND_TRUE LT_AGE LT_REVISION LT_CURRENT LIBTOOL_DEPS LT_SYS_LIBRARY_PATH OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB DLLTOOL OBJDUMP FILECMD LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP EGREP GREP SED host_os host_vendor host_cpu host build_os build_vendor build_cpu build LIBTOOL PKG_CONFIG_LIBDIR PKG_CONFIG_PATH PKG_CONFIG am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE am__nodep AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__include DEPDIR OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC ac_ct_AR AR AM_BACKSLASH AM_DEFAULT_VERBOSITY AM_DEFAULT_V AM_V CSCOPE ETAGS CTAGS am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM WARNINGS_ARE_ERRORS_COND_FALSE WARNINGS_ARE_ERRORS_COND_TRUE DBG VERSION_VSUFFIX VERSION_VMICRO VERSION_VMINOR VERSION_VMAJOR target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir runstatedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL am__quote' ac_subst_files='' ac_user_opts=' enable_option_checking enable_silent_rules enable_dependency_tracking enable_static enable_shared with_pic enable_fast_install with_aix_soname with_gnu_ld with_sysroot enable_libtool_lock enable_lib enable_install_lib_only enable_build_timestamp enable_envcmds enable_udev enable_usb enable_drm enable_x11 enable_static_functions_visible enable_asan enable_targetbsd enable_doxygen enable_testcases enable_callgraph enable_failsim enable_force_suse enable_doxygen_doc enable_doxygen_dot enable_doxygen_man enable_doxygen_rtf enable_doxygen_xml enable_doxygen_chm enable_doxygen_chi enable_doxygen_html enable_doxygen_ps enable_doxygen_pdf ' ac_precious_vars='build_alias host_alias target_alias DBG CC CFLAGS LDFLAGS LIBS CPPFLAGS PKG_CONFIG PKG_CONFIG_PATH PKG_CONFIG_LIBDIR LT_SYS_LIBRARY_PATH GLIB_CFLAGS GLIB_LIBS JANSSON_CFLAGS JANSSON_LIBS UDEV_CFLAGS UDEV_LIBS LIBUSB_CFLAGS LIBUSB_LIBS LIBDRM_CFLAGS LIBDRM_LIBS LIBX11_CFLAGS LIBX11_LIBS XRANDR_CFLAGS XRANDR_LIBS XEXT_CFLAGS XEXT_LIBS DOXYGEN DOXYGEN_PAPER_SIZE ZLIB_CFLAGS ZLIB_LIBS' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' runstatedir='${localstatedir}/run' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -runstatedir | --runstatedir | --runstatedi | --runstated \ | --runstate | --runstat | --runsta | --runst | --runs \ | --run | --ru | --r) ac_prev=runstatedir ;; -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ | --run=* | --ru=* | --r=*) runstatedir=$ac_optarg ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: '$ac_option' Try '$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: '$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. printf "%s\n" "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && printf "%s\n" "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir runstatedir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: '$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but 'cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF 'configure' configures ddcutil 2.2.0 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print 'checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for '--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or '..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, 'make install' will install all the files in '$ac_default_prefix/bin', '$ac_default_prefix/lib' etc. You can specify an installation prefix other than '$ac_default_prefix' using '--prefix', for instance '--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/ddcutil] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of ddcutil 2.2.0:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-silent-rules less verbose build output (undo: "make V=1") --disable-silent-rules verbose build output (undo: "make V=0") --enable-dependency-tracking do not reject slow dependency extractors --disable-dependency-tracking speeds up one-time build --enable-static[=PKGS] build static libraries [default=no] --enable-shared[=PKGS] build shared libraries [default=yes] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) --enable-lib=[yes/no] Build shared library and clients[default=yes] --enable-install-lib-only=[yes/no] Install only shared shared librarys[default=no] --enable-build-timestamp=[yes/no] Insert build date/time in executables[default=yes] --enable-envcmds=[yes/no] Include environment and usbenvironment[default=yes] --enable-udev=[yes/no] Use UDEV[default=yes] --enable-usb=[yes/no] Support USB connected displays[default=yes] --enable-drm=[yes/no] Use DRM[default=yes] --enable-x11=[yes/no] Use X11[default=yes] --enable-static-functions-visible=[no/yes] Remove static qualifier from functions[default=no] --enable-asan=[no/yes] Build for asan (address sanitizer)[default=no] --enable-targetbsd=[no/yes] Build for BSD[default=no] (Developer-only) --enable-doxygen=[no/yes] Build API documentation using Doxygen (if it is installed)[default=no] (Developer-only) --enable-testcases=[no/yes] Include test cases [default=no] (Developer-only) --enable-callgraph=[no/yes] Create .expand files for static call graph[default=no] (Developer-only) --enable-failsim=[no/yes] Build with failure simulation[default=no] (Developer-only) --enable-force-suse=[no/yes] Force SUSE target directories[default=no] (Developer-only) --disable-doxygen-doc don't generate any doxygen documentation --enable-doxygen-dot generate graphics for doxygen documentation --enable-doxygen-man generate doxygen manual pages --enable-doxygen-rtf generate doxygen RTF documentation --enable-doxygen-xml generate doxygen XML documentation --enable-doxygen-chm generate doxygen compressed HTML help documentation --enable-doxygen-chi generate doxygen seperate compressed HTML help index file --disable-doxygen-html don't generate doxygen plain HTML documentation --disable-doxygen-ps don't generate doxygen PostScript documentation --disable-doxygen-pdf don't generate doxygen PDF documentation Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use both] --with-aix-soname=aix|svr4|both shared library versioning (aka "SONAME") variant to provide on AIX, [default=aix]. --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot[=DIR] Search for dependent libraries within DIR (or the compiler's sysroot if not specified). Some influential environment variables: DBG Turn on script debugging messages(0/1) CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory PKG_CONFIG path to pkg-config utility PKG_CONFIG_PATH directories to add to pkg-config's search path PKG_CONFIG_LIBDIR path overriding pkg-config's built-in search path LT_SYS_LIBRARY_PATH User-defined run-time library search path. GLIB_CFLAGS C compiler flags for GLIB, overriding pkg-config GLIB_LIBS linker flags for GLIB, overriding pkg-config JANSSON_CFLAGS C compiler flags for JANSSON, overriding pkg-config JANSSON_LIBS linker flags for JANSSON, overriding pkg-config UDEV_CFLAGS C compiler flags for UDEV, overriding pkg-config UDEV_LIBS linker flags for UDEV, overriding pkg-config LIBUSB_CFLAGS C compiler flags for LIBUSB, overriding pkg-config LIBUSB_LIBS linker flags for LIBUSB, overriding pkg-config LIBDRM_CFLAGS C compiler flags for LIBDRM, overriding pkg-config LIBDRM_LIBS linker flags for LIBDRM, overriding pkg-config LIBX11_CFLAGS C compiler flags for LIBX11, overriding pkg-config LIBX11_LIBS linker flags for LIBX11, overriding pkg-config XRANDR_CFLAGS C compiler flags for XRANDR, overriding pkg-config XRANDR_LIBS linker flags for XRANDR, overriding pkg-config XEXT_CFLAGS C compiler flags for XEXT, overriding pkg-config XEXT_LIBS linker flags for XEXT, overriding pkg-config DOXYGEN Doxygen source doc generation program DOXYGEN_PAPER_SIZE a4wide (default), a4, letter, legal or executive ZLIB_CFLAGS C compiler flags for ZLIB, overriding pkg-config ZLIB_LIBS linker flags for ZLIB, overriding pkg-config Use these variables to override the choices made by 'configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for configure.gnu first; this name is used for a wrapper for # Metaconfig's "Configure" on case-insensitive file systems. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else printf "%s\n" "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF ddcutil configure 2.2.0 generated by GNU Autoconf 2.72 Copyright (C) 2023 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest.beam if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext then : ac_retval=0 else case e in #( e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 ;; esac fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest.beam conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext } then : ac_retval=0 else case e in #( e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 ;; esac fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 printf %s "checking for $2... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO" then : eval "$3=yes" else case e in #( e) eval "$3=no" ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 printf "%s\n" "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 printf %s "checking for $2... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (void); below. */ #include #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (void); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main (void) { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : eval "$3=yes" else case e in #( e) eval "$3=no" ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext ;; esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 printf "%s\n" "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_c_check_type LINENO TYPE VAR INCLUDES # ------------------------------------------- # Tests whether TYPE exists after having included INCLUDES, setting cache # variable VAR accordingly. ac_fn_c_check_type () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 printf %s "checking for $2... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 else case e in #( e) eval "$3=no" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main (void) { if (sizeof ($2)) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main (void) { if (sizeof (($2))) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : else case e in #( e) eval "$3=yes" ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 printf "%s\n" "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_type # ac_fn_c_try_run LINENO # ---------------------- # Try to run conftest.$ac_ext, and return whether this succeeded. Assumes that # executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; } then : ac_retval=0 else case e in #( e) printf "%s\n" "$as_me: program exited with status $ac_status" >&5 printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status ;; esac fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_find_uintX_t LINENO BITS VAR # ------------------------------------ # Finds an unsigned integer type with width BITS, setting cache variable VAR # accordingly. ac_fn_c_find_uintX_t () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for uint$2_t" >&5 printf %s "checking for uint$2_t... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 else case e in #( e) eval "$3=no" # Order is important - never check a type that is potentially smaller # than half of the expected target width. for ac_type in uint$2_t 'unsigned int' 'unsigned long int' \ 'unsigned long long int' 'unsigned short int' 'unsigned char'; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main (void) { static int test_array [1 - 2 * !((($ac_type) -1 >> ($2 / 2 - 1)) >> ($2 / 2 - 1) == 3)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : case $ac_type in #( uint$2_t) : eval "$3=yes" ;; #( *) : eval "$3=\$ac_type" ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext if eval test \"x\$"$3"\" = x"no" then : else case e in #( e) break ;; esac fi done ;; esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 printf "%s\n" "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_find_uintX_t # ac_fn_check_decl LINENO SYMBOL VAR INCLUDES EXTRA-OPTIONS FLAG-VAR # ------------------------------------------------------------------ # Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR # accordingly. Pass EXTRA-OPTIONS to the compiler, using FLAG-VAR. ac_fn_check_decl () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack as_decl_name=`echo $2|sed 's/ *(.*//'` { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5 printf %s "checking whether $as_decl_name is declared... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 else case e in #( e) as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'` eval ac_save_FLAGS=\$$6 as_fn_append $6 " $5" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main (void) { #ifndef $as_decl_name #ifdef __cplusplus (void) $as_decl_use; #else (void) $as_decl_name; #endif #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : eval "$3=yes" else case e in #( e) eval "$3=no" ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext eval $6=\$ac_save_FLAGS ;; esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 printf "%s\n" "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_check_decl ac_configure_args_raw= for ac_arg do case $ac_arg in *\'*) ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append ac_configure_args_raw " '$ac_arg'" done case $ac_configure_args_raw in *$as_nl*) ac_safe_unquote= ;; *) ac_unsafe_z='|&;<>()$`\\"*?[ '' ' # This string ends in space, tab. ac_unsafe_a="$ac_unsafe_z#~" ac_safe_unquote="s/ '\\([^$ac_unsafe_a][^$ac_unsafe_z]*\\)'/ \\1/g" ac_configure_args_raw=` printf "%s\n" "$ac_configure_args_raw" | sed "$ac_safe_unquote"`;; esac cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by ddcutil $as_me 2.2.0, which was generated by GNU Autoconf 2.72. Invocation command line was $ $0$ac_configure_args_raw _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac printf "%s\n" "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Sanitize IFS. IFS=" "" $as_nl" # Save into config.log some information that might help in debugging. { echo printf "%s\n" "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo printf "%s\n" "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac printf "%s\n" "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then printf "%s\n" "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac printf "%s\n" "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then printf "%s\n" "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && printf "%s\n" "$as_me: caught signal $ac_signal" printf "%s\n" "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h printf "%s\n" "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. printf "%s\n" "#define PACKAGE_NAME \"$PACKAGE_NAME\"" >>confdefs.h printf "%s\n" "#define PACKAGE_TARNAME \"$PACKAGE_TARNAME\"" >>confdefs.h printf "%s\n" "#define PACKAGE_VERSION \"$PACKAGE_VERSION\"" >>confdefs.h printf "%s\n" "#define PACKAGE_STRING \"$PACKAGE_STRING\"" >>confdefs.h printf "%s\n" "#define PACKAGE_BUGREPORT \"$PACKAGE_BUGREPORT\"" >>confdefs.h printf "%s\n" "#define PACKAGE_URL \"$PACKAGE_URL\"" >>confdefs.h # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. if test -n "$CONFIG_SITE"; then ac_site_files="$CONFIG_SITE" elif test "x$prefix" != xNONE; then ac_site_files="$prefix/share/config.site $prefix/etc/config.site" else ac_site_files="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site" fi for ac_site_file in $ac_site_files do case $ac_site_file in #( */*) : ;; #( *) : ac_site_file=./$ac_site_file ;; esac if test -f "$ac_site_file" && test -r "$ac_site_file"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 printf "%s\n" "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See 'config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 printf "%s\n" "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 printf "%s\n" "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Test code for whether the C compiler supports C89 (global declarations) ac_c_conftest_c89_globals=' /* Does the compiler advertise C89 conformance? Do not test the value of __STDC__, because some compilers set it to 0 while being otherwise adequately conformant. */ #if !defined __STDC__ # error "Compiler does not advertise C89 conformance" #endif #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7 src/conf.sh. */ struct buf { int x; }; struct buf * (*rcsopen) (struct buf *, struct stat *, int); static char *e (char **p, int i) { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* C89 style stringification. */ #define noexpand_stringify(a) #a const char *stringified = noexpand_stringify(arbitrary+token=sequence); /* C89 style token pasting. Exercises some of the corner cases that e.g. old MSVC gets wrong, but not very hard. */ #define noexpand_concat(a,b) a##b #define expand_concat(a,b) noexpand_concat(a,b) extern int vA; extern int vbee; #define aye A #define bee B int *pvA = &expand_concat(v,aye); int *pvbee = &noexpand_concat(v,bee); /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not \xHH hex character constants. These do not provoke an error unfortunately, instead are silently treated as an "x". The following induces an error, until -std is added to get proper ANSI mode. Curiously \x00 != x always comes out true, for an array size at least. It is necessary to write \x00 == 0 to get something that is true only with -std. */ int osf4_cc_array ['\''\x00'\'' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) '\''x'\'' int xlc6_cc_array[FOO(a) == '\''x'\'' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, int *(*)(struct buf *, struct stat *, int), int, int);' # Test code for whether the C compiler supports C89 (body of main). ac_c_conftest_c89_main=' ok |= (argc == 0 || f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]); ' # Test code for whether the C compiler supports C99 (global declarations) ac_c_conftest_c99_globals=' /* Does the compiler advertise C99 conformance? */ #if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L # error "Compiler does not advertise C99 conformance" #endif // See if C++-style comments work. #include extern int puts (const char *); extern int printf (const char *, ...); extern int dprintf (int, const char *, ...); extern void *malloc (size_t); extern void free (void *); // Check varargs macros. These examples are taken from C99 6.10.3.5. // dprintf is used instead of fprintf to avoid needing to declare // FILE and stderr. #define debug(...) dprintf (2, __VA_ARGS__) #define showlist(...) puts (#__VA_ARGS__) #define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__)) static void test_varargs_macros (void) { int x = 1234; int y = 5678; debug ("Flag"); debug ("X = %d\n", x); showlist (The first, second, and third items.); report (x>y, "x is %d but y is %d", x, y); } // Check long long types. #define BIG64 18446744073709551615ull #define BIG32 4294967295ul #define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0) #if !BIG_OK #error "your preprocessor is broken" #endif #if BIG_OK #else #error "your preprocessor is broken" #endif static long long int bignum = -9223372036854775807LL; static unsigned long long int ubignum = BIG64; struct incomplete_array { int datasize; double data[]; }; struct named_init { int number; const wchar_t *name; double average; }; typedef const char *ccp; static inline int test_restrict (ccp restrict text) { // Iterate through items via the restricted pointer. // Also check for declarations in for loops. for (unsigned int i = 0; *(text+i) != '\''\0'\''; ++i) continue; return 0; } // Check varargs and va_copy. static bool test_varargs (const char *format, ...) { va_list args; va_start (args, format); va_list args_copy; va_copy (args_copy, args); const char *str = ""; int number = 0; float fnumber = 0; while (*format) { switch (*format++) { case '\''s'\'': // string str = va_arg (args_copy, const char *); break; case '\''d'\'': // int number = va_arg (args_copy, int); break; case '\''f'\'': // float fnumber = va_arg (args_copy, double); break; default: break; } } va_end (args_copy); va_end (args); return *str && number && fnumber; } ' # Test code for whether the C compiler supports C99 (body of main). ac_c_conftest_c99_main=' // Check bool. _Bool success = false; success |= (argc != 0); // Check restrict. if (test_restrict ("String literal") == 0) success = true; char *restrict newvar = "Another string"; // Check varargs. success &= test_varargs ("s, d'\'' f .", "string", 65, 34.234); test_varargs_macros (); // Check flexible array members. struct incomplete_array *ia = malloc (sizeof (struct incomplete_array) + (sizeof (double) * 10)); ia->datasize = 10; for (int i = 0; i < ia->datasize; ++i) ia->data[i] = i * 1.234; // Work around memory leak warnings. free (ia); // Check named initializers. struct named_init ni = { .number = 34, .name = L"Test wide string", .average = 543.34343, }; ni.number = 58; int dynamic_array[ni.number]; dynamic_array[0] = argv[0][0]; dynamic_array[ni.number - 1] = 543; // work around unused variable warnings ok |= (!success || bignum == 0LL || ubignum == 0uLL || newvar[0] == '\''x'\'' || dynamic_array[ni.number - 1] != 543); ' # Test code for whether the C compiler supports C11 (global declarations) ac_c_conftest_c11_globals=' /* Does the compiler advertise C11 conformance? */ #if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112L # error "Compiler does not advertise C11 conformance" #endif // Check _Alignas. char _Alignas (double) aligned_as_double; char _Alignas (0) no_special_alignment; extern char aligned_as_int; char _Alignas (0) _Alignas (int) aligned_as_int; // Check _Alignof. enum { int_alignment = _Alignof (int), int_array_alignment = _Alignof (int[100]), char_alignment = _Alignof (char) }; _Static_assert (0 < -_Alignof (int), "_Alignof is signed"); // Check _Noreturn. int _Noreturn does_not_return (void) { for (;;) continue; } // Check _Static_assert. struct test_static_assert { int x; _Static_assert (sizeof (int) <= sizeof (long int), "_Static_assert does not work in struct"); long int y; }; // Check UTF-8 literals. #define u8 syntax error! char const utf8_literal[] = u8"happens to be ASCII" "another string"; // Check duplicate typedefs. typedef long *long_ptr; typedef long int *long_ptr; typedef long_ptr long_ptr; // Anonymous structures and unions -- taken from C11 6.7.2.1 Example 1. struct anonymous { union { struct { int i; int j; }; struct { int k; long int l; } w; }; int m; } v1; ' # Test code for whether the C compiler supports C11 (body of main). ac_c_conftest_c11_main=' _Static_assert ((offsetof (struct anonymous, i) == offsetof (struct anonymous, w.k)), "Anonymous union alignment botch"); v1.i = 2; v1.w.k = 5; ok |= v1.i != 5; ' # Test code for whether the C compiler supports C11 (complete). ac_c_conftest_c11_program="${ac_c_conftest_c89_globals} ${ac_c_conftest_c99_globals} ${ac_c_conftest_c11_globals} int main (int argc, char **argv) { int ok = 0; ${ac_c_conftest_c89_main} ${ac_c_conftest_c99_main} ${ac_c_conftest_c11_main} return ok; } " # Test code for whether the C compiler supports C99 (complete). ac_c_conftest_c99_program="${ac_c_conftest_c89_globals} ${ac_c_conftest_c99_globals} int main (int argc, char **argv) { int ok = 0; ${ac_c_conftest_c89_main} ${ac_c_conftest_c99_main} return ok; } " # Test code for whether the C compiler supports C89 (complete). ac_c_conftest_c89_program="${ac_c_conftest_c89_globals} int main (int argc, char **argv) { int ok = 0; ${ac_c_conftest_c89_main} return ok; } " as_fn_append ac_header_c_list " stdio.h stdio_h HAVE_STDIO_H" as_fn_append ac_header_c_list " stdlib.h stdlib_h HAVE_STDLIB_H" as_fn_append ac_header_c_list " string.h string_h HAVE_STRING_H" as_fn_append ac_header_c_list " inttypes.h inttypes_h HAVE_INTTYPES_H" as_fn_append ac_header_c_list " stdint.h stdint_h HAVE_STDINT_H" as_fn_append ac_header_c_list " strings.h strings_h HAVE_STRINGS_H" as_fn_append ac_header_c_list " sys/stat.h sys_stat_h HAVE_SYS_STAT_H" as_fn_append ac_header_c_list " sys/types.h sys_types_h HAVE_SYS_TYPES_H" as_fn_append ac_header_c_list " unistd.h unistd_h HAVE_UNISTD_H" # Auxiliary files required by this configure script. ac_aux_files="config.guess config.sub ltmain.sh compile ar-lib missing install-sh" # Locations in which to look for auxiliary files. ac_aux_dir_candidates="${srcdir}/config" # Search for a directory containing all of the required auxiliary files, # $ac_aux_files, from the $PATH-style list $ac_aux_dir_candidates. # If we don't find one directory that contains all the files we need, # we report the set of missing files from the *first* directory in # $ac_aux_dir_candidates and give up. ac_missing_aux_files="" ac_first_candidate=: printf "%s\n" "$as_me:${as_lineno-$LINENO}: looking for aux files: $ac_aux_files" >&5 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in $ac_aux_dir_candidates do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac as_found=: printf "%s\n" "$as_me:${as_lineno-$LINENO}: trying $as_dir" >&5 ac_aux_dir_found=yes ac_install_sh= for ac_aux in $ac_aux_files do # As a special case, if "install-sh" is required, that requirement # can be satisfied by any of "install-sh", "install.sh", or "shtool", # and $ac_install_sh is set appropriately for whichever one is found. if test x"$ac_aux" = x"install-sh" then if test -f "${as_dir}install-sh"; then printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}install-sh found" >&5 ac_install_sh="${as_dir}install-sh -c" elif test -f "${as_dir}install.sh"; then printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}install.sh found" >&5 ac_install_sh="${as_dir}install.sh -c" elif test -f "${as_dir}shtool"; then printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}shtool found" >&5 ac_install_sh="${as_dir}shtool install -c" else ac_aux_dir_found=no if $ac_first_candidate; then ac_missing_aux_files="${ac_missing_aux_files} install-sh" else break fi fi else if test -f "${as_dir}${ac_aux}"; then printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}${ac_aux} found" >&5 else ac_aux_dir_found=no if $ac_first_candidate; then ac_missing_aux_files="${ac_missing_aux_files} ${ac_aux}" else break fi fi fi done if test "$ac_aux_dir_found" = yes; then ac_aux_dir="$as_dir" break fi ac_first_candidate=false as_found=false done IFS=$as_save_IFS if $as_found then : else case e in #( e) as_fn_error $? "cannot find required auxiliary files:$ac_missing_aux_files" "$LINENO" 5 ;; esac fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. if test -f "${ac_aux_dir}config.guess"; then ac_config_guess="$SHELL ${ac_aux_dir}config.guess" fi if test -f "${ac_aux_dir}config.sub"; then ac_config_sub="$SHELL ${ac_aux_dir}config.sub" fi if test -f "$ac_aux_dir/configure"; then ac_configure="$SHELL ${ac_aux_dir}configure" fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: '$ac_var' was set to '$ac_old_val' in the previous run" >&5 printf "%s\n" "$as_me: error: '$ac_var' was set to '$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: '$ac_var' was not set in the previous run" >&5 printf "%s\n" "$as_me: error: '$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: '$ac_var' has changed since the previous run:" >&5 printf "%s\n" "$as_me: error: '$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in '$ac_var' since the previous run:" >&5 printf "%s\n" "$as_me: warning: ignoring whitespace changes in '$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: former value: '$ac_old_val'" >&5 printf "%s\n" "$as_me: former value: '$ac_old_val'" >&2;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: current value: '$ac_new_val'" >&5 printf "%s\n" "$as_me: current value: '$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`printf "%s\n" "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 printf "%s\n" "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run '${MAKE-make} distclean' and/or 'rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu printf "%s\n" "#define VERSION_VMAJOR 2 " >>confdefs.h printf "%s\n" "#define VERSION_VMINOR 2 " >>confdefs.h printf "%s\n" "#define VERSION_VMICRO 0 " >>confdefs.h printf "%s\n" "#define VERSION_VSUFFIX \"dev\" " >>confdefs.h VERSION_VMAJOR=2 VERSION_VMINOR=2 VERSION_VMICRO=0 VERSION_VSUFFIX="dev" if test "x$"dev"" != "x" ; then WARNINGS_ARE_ERRORS_COND_TRUE= WARNINGS_ARE_ERRORS_COND_FALSE='#' else WARNINGS_ARE_ERRORS_COND_TRUE='#' WARNINGS_ARE_ERRORS_COND_FALSE= fi if test 0$DBG -ne 0 then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: debug messages enabled" >&5 printf "%s\n" "$as_me: debug messages enabled" >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: debug messages disabled" >&5 printf "%s\n" "$as_me: debug messages disabled" >&6;} ;; esac fi ac_config_headers="$ac_config_headers config.h" ac_config_files="$ac_config_files Makefile src/Makefile src/util/Makefile src/usb_util/Makefile src/base/Makefile src/vcp/Makefile src/dynvcp/Makefile src/sysfs/Makefile src/i2c/Makefile src/usb/Makefile src/ddc/Makefile src/dw/Makefile src/test/Makefile src/cmdline/Makefile src/app_sysenv/Makefile src/app_ddcutil/Makefile src/libmain/Makefile src/sample_clients/Makefile man/Makefile data/Makefile docs/Makefile docs/doxygen/Makefile src/public/ddcutil_macros.h data/ddcutil.pc" # AC_DEFINE_UNQUOTED([DDCUTIL_MAJOR_VERSION], [$ddcutil_major_version], [ddcutil major version]) am__api_version='1.16' # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 printf %s "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if test ${ac_cv_path_install+y} then : printf %s "(cached) " >&6 else case e in #( e) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac # Account for fact that we put trailing slashes in our PATH walk. case $as_dir in #(( ./ | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir/" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir ;; esac fi if test ${ac_cv_path_install+y}; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 printf "%s\n" "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 printf %s "checking whether build environment is sane... " >&6; } # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". as_fn_error $? "ls -t appears to fail. Make sure there is not a broken alias in your environment" "$LINENO" 5 fi if test "$2" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$2" = conftest.file ) then # Ok. : else as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi rm -f conftest.file test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was 's,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`printf "%s\n" "$program_transform_name" | sed "$ac_script"` # Expand $ac_aux_dir to an absolute path. am_aux_dir=`cd "$ac_aux_dir" && pwd` if test x"${MISSING+set}" != xset; then MISSING="\${SHELL} '$am_aux_dir/missing'" fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 'missing' script is too old or missing" >&5 printf "%s\n" "$as_me: WARNING: 'missing' script is too old or missing" >&2;} fi if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_STRIP+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 printf "%s\n" "$STRIP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_STRIP+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 printf "%s\n" "$ac_ct_STRIP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a race-free mkdir -p" >&5 printf %s "checking for a race-free mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if test ${ac_cv_path_mkdir+y} then : printf %s "(cached) " >&6 else case e in #( e) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do as_fn_executable_p "$as_dir$ac_prog$ac_exec_ext" || continue case `"$as_dir$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir ('*'coreutils) '* | \ *'BusyBox '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS ;; esac fi test -d ./--version && rmdir ./--version if test ${ac_cv_path_mkdir+y}; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use plain mkdir -p, # in the hope it doesn't have the bugs of ancient mkdir. MKDIR_P='mkdir -p' fi fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 printf "%s\n" "$MKDIR_P" >&6; } for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_AWK+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 printf "%s\n" "$AWK" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$AWK" && break done { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 printf %s "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`printf "%s\n" "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval test \${ac_cv_prog_make_${ac_make}_set+y} then : printf %s "(cached) " >&6 else case e in #( e) cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make ;; esac fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } SET_MAKE= else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null # Check whether --enable-silent-rules was given. if test ${enable_silent_rules+y} then : enableval=$enable_silent_rules; fi case $enable_silent_rules in # ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=1;; esac am_make=${MAKE-make} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 printf %s "checking whether $am_make supports nested variables... " >&6; } if test ${am_cv_make_support_nested_variables+y} then : printf %s "(cached) " >&6 else case e in #( e) if printf "%s\n" 'TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 printf "%s\n" "$am_cv_make_support_nested_variables" >&6; } if test $am_cv_make_support_nested_variables = yes; then AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AM_BACKSLASH='\' if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='ddcutil' VERSION='2.2.0' printf "%s\n" "#define PACKAGE \"$PACKAGE\"" >>confdefs.h printf "%s\n" "#define VERSION \"$VERSION\"" >>confdefs.h # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # mkdir_p='$(MKDIR_P)' # We need awk for the "check" target (and possibly the TAP driver). The # system "awk" is bad on some platforms. # Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AMTAR='$${TAR-tar}' # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar pax cpio none' am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' # Variables for tags utilities; see am/tags.am if test -z "$CTAGS"; then CTAGS=ctags fi if test -z "$ETAGS"; then ETAGS=etags fi if test -z "$CSCOPE"; then CSCOPE=cscope fi # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5 fi fi # Check whether --enable-silent-rules was given. if test ${enable_silent_rules+y} then : enableval=$enable_silent_rules; fi case $enable_silent_rules in # ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=0;; esac am_make=${MAKE-make} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 printf %s "checking whether $am_make supports nested variables... " >&6; } if test ${am_cv_make_support_nested_variables+y} then : printf %s "(cached) " >&6 else case e in #( e) if printf "%s\n" 'TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 printf "%s\n" "$am_cv_make_support_nested_variables" >&6; } if test $am_cv_make_support_nested_variables = yes; then AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AM_BACKSLASH='\' DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} supports the include directive" >&5 printf %s "checking whether ${MAKE-make} supports the include directive... " >&6; } cat > confinc.mk << 'END' am__doit: @echo this is the am__doit target >confinc.out .PHONY: am__doit END am__include="#" am__quote= # BSD make does it like this. echo '.include "confinc.mk" # ignored' > confmf.BSD # Other make implementations (GNU, Solaris 10, AIX) do it like this. echo 'include confinc.mk # ignored' > confmf.GNU _am_result=no for s in GNU BSD; do { echo "$as_me:$LINENO: ${MAKE-make} -f confmf.$s && cat confinc.out" >&5 (${MAKE-make} -f confmf.$s && cat confinc.out) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } case $?:`cat confinc.out 2>/dev/null` in #( '0:this is the am__doit target') : case $s in #( BSD) : am__include='.include' am__quote='"' ;; #( *) : am__include='include' am__quote='' ;; esac ;; #( *) : ;; esac if test "$am__include" != "#"; then _am_result="yes ($s style)" break fi done rm -f confinc.* confmf.* { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${_am_result}" >&5 printf "%s\n" "${_am_result}" >&6; } # Check whether --enable-dependency-tracking was given. if test ${enable_dependency_tracking+y} then : enableval=$enable_dependency_tracking; fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else AMDEP_TRUE='#' AMDEP_FALSE= fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 printf "%s\n" "$ac_ct_CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then if test "$as_dir$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir$ac_word${1+' '}$@" fi fi fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 printf "%s\n" "$ac_ct_CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}clang", so it can be a program name with args. set dummy ${ac_tool_prefix}clang; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}clang" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "clang", so it can be a program name with args. set dummy clang; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="clang" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 printf "%s\n" "$ac_ct_CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi fi test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See 'config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion -version; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 printf %s "checking whether the C compiler works... " >&6; } ac_link_default=`printf "%s\n" "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then : # Autoconf-2.13 could set the ac_cv_exeext variable to 'no'. # So ignore a value of 'no', otherwise this would lead to 'EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test ${ac_cv_exeext+y} && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an '-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else case e in #( e) ac_file='' ;; esac fi if test -z "$ac_file" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See 'config.log' for more details" "$LINENO" 5; } else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 printf %s "checking for C compiler default output file name... " >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 printf "%s\n" "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 printf %s "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then : # If both 'conftest.exe' and 'conftest' are 'present' (well, observable) # catch 'conftest.exe'. For instance with Cygwin, 'ls conftest' will # work properly (i.e., refer to 'conftest.exe'), while it won't with # 'rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else case e in #( e) { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See 'config.log' for more details" "$LINENO" 5; } ;; esac fi rm -f conftest conftest$ac_cv_exeext { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 printf "%s\n" "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main (void) { FILE *f = fopen ("conftest.out", "w"); if (!f) return 1; return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 printf %s "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error 77 "cannot run C compiled programs. If you meant to cross compile, use '--host'. See 'config.log' for more details" "$LINENO" 5; } fi fi fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 printf "%s\n" "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext \ conftest.o conftest.obj conftest.out ac_clean_files=$ac_clean_files_save { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 printf %s "checking for suffix of object files... " >&6; } if test ${ac_cv_objext+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else case e in #( e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See 'config.log' for more details" "$LINENO" 5; } ;; esac fi rm -f conftest.$ac_cv_objext conftest.$ac_ext ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 printf "%s\n" "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the compiler supports GNU C" >&5 printf %s "checking whether the compiler supports GNU C... " >&6; } if test ${ac_cv_c_compiler_gnu+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_compiler_gnu=yes else case e in #( e) ac_compiler_gnu=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 printf "%s\n" "$ac_cv_c_compiler_gnu" >&6; } ac_compiler_gnu=$ac_cv_c_compiler_gnu if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+y} ac_save_CFLAGS=$CFLAGS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 printf %s "checking whether $CC accepts -g... " >&6; } if test ${ac_cv_prog_cc_g+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_g=yes else case e in #( e) CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : else case e in #( e) ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 printf "%s\n" "$ac_cv_prog_cc_g" >&6; } if test $ac_test_CFLAGS; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi ac_prog_cc_stdc=no if test x$ac_prog_cc_stdc = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C11 features" >&5 printf %s "checking for $CC option to enable C11 features... " >&6; } if test ${ac_cv_prog_cc_c11+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_prog_cc_c11=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_c_conftest_c11_program _ACEOF for ac_arg in '' -std=gnu11 do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_c11=$ac_arg fi rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c11" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC ;; esac fi if test "x$ac_cv_prog_cc_c11" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } else case e in #( e) if test "x$ac_cv_prog_cc_c11" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5 printf "%s\n" "$ac_cv_prog_cc_c11" >&6; } CC="$CC $ac_cv_prog_cc_c11" ;; esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c11 ac_prog_cc_stdc=c11 ;; esac fi fi if test x$ac_prog_cc_stdc = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C99 features" >&5 printf %s "checking for $CC option to enable C99 features... " >&6; } if test ${ac_cv_prog_cc_c99+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_prog_cc_c99=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_c_conftest_c99_program _ACEOF for ac_arg in '' -std=gnu99 -std=c99 -c99 -qlanglvl=extc1x -qlanglvl=extc99 -AC99 -D_STDC_C99= do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_c99=$ac_arg fi rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c99" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC ;; esac fi if test "x$ac_cv_prog_cc_c99" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } else case e in #( e) if test "x$ac_cv_prog_cc_c99" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 printf "%s\n" "$ac_cv_prog_cc_c99" >&6; } CC="$CC $ac_cv_prog_cc_c99" ;; esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c99 ac_prog_cc_stdc=c99 ;; esac fi fi if test x$ac_prog_cc_stdc = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C89 features" >&5 printf %s "checking for $CC option to enable C89 features... " >&6; } if test ${ac_cv_prog_cc_c89+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_c_conftest_c89_program _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC ;; esac fi if test "x$ac_cv_prog_cc_c89" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } else case e in #( e) if test "x$ac_cv_prog_cc_c89" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 printf "%s\n" "$ac_cv_prog_cc_c89" >&6; } CC="$CC $ac_cv_prog_cc_c89" ;; esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c89 ac_prog_cc_stdc=c89 ;; esac fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5 printf %s "checking whether $CC understands -c and -o together... " >&6; } if test ${am_cv_prog_cc_c_o+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5 ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 printf "%s\n" "$am_cv_prog_cc_c_o" >&6; } if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CC" am_compiler_list= { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 printf %s "checking dependency style of $depcc... " >&6; } if test ${am_cv_CC_dependencies_compiler_type+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 printf "%s\n" "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi if test -n "$ac_tool_prefix"; then for ac_prog in ar lib "link -lib" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_AR+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi AR=$ac_cv_prog_AR if test -n "$AR"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 printf "%s\n" "$AR" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar lib "link -lib" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_AR+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 printf "%s\n" "$ac_ct_AR" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking the archiver ($AR) interface" >&5 printf %s "checking the archiver ($AR) interface... " >&6; } if test ${am_cv_ar_interface+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu am_cv_ar_interface=ar cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int some_variable = 0; _ACEOF if ac_fn_c_try_compile "$LINENO" then : am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$am_ar_try\""; } >&5 (eval $am_ar_try) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then am_cv_ar_interface=ar else am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$am_ar_try\""; } >&5 (eval $am_ar_try) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then am_cv_ar_interface=lib else am_cv_ar_interface=unknown fi fi rm -f conftest.lib libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_ar_interface" >&5 printf "%s\n" "$am_cv_ar_interface" >&6; } case $am_cv_ar_interface in ar) ;; lib) # Microsoft lib, so override with the ar-lib wrapper script. # FIXME: It is wrong to rewrite AR. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__AR in this case, # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something # similar. AR="$am_aux_dir/ar-lib $AR" ;; unknown) as_fn_error $? "could not determine $AR interface" "$LINENO" 5 ;; esac if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_PKG_CONFIG+y} then : printf %s "(cached) " >&6 else case e in #( e) case $PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_PKG_CONFIG="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi PKG_CONFIG=$ac_cv_path_PKG_CONFIG if test -n "$PKG_CONFIG"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5 printf "%s\n" "$PKG_CONFIG" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_PKG_CONFIG"; then ac_pt_PKG_CONFIG=$PKG_CONFIG # Extract the first word of "pkg-config", so it can be a program name with args. set dummy pkg-config; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_PKG_CONFIG+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_PKG_CONFIG="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG if test -n "$ac_pt_PKG_CONFIG"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5 printf "%s\n" "$ac_pt_PKG_CONFIG" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_PKG_CONFIG" = x; then PKG_CONFIG="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac PKG_CONFIG=$ac_pt_PKG_CONFIG fi else PKG_CONFIG="$ac_cv_path_PKG_CONFIG" fi fi if test -n "$PKG_CONFIG"; then _pkg_min_version=0.9.0 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5 printf %s "checking pkg-config is at least version $_pkg_min_version... " >&6; } if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } PKG_CONFIG="" fi fi if test -z "$PKG_CONFIG"; then as_fn_error $? "pkg-config not found" "$LINENO" 5 fi required_packages= # AC_PROG_C99 for CENTOS 7 in OBS, EOL 6/30/2024 ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 printf "%s\n" "$ac_ct_CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then if test "$as_dir$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir$ac_word${1+' '}$@" fi fi fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 printf "%s\n" "$ac_ct_CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}clang", so it can be a program name with args. set dummy ${ac_tool_prefix}clang; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}clang" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 printf "%s\n" "$CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "clang", so it can be a program name with args. set dummy clang; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="clang" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 printf "%s\n" "$ac_ct_CC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi fi test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See 'config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion -version; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" printf "%s\n" "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the compiler supports GNU C" >&5 printf %s "checking whether the compiler supports GNU C... " >&6; } if test ${ac_cv_c_compiler_gnu+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_compiler_gnu=yes else case e in #( e) ac_compiler_gnu=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 printf "%s\n" "$ac_cv_c_compiler_gnu" >&6; } ac_compiler_gnu=$ac_cv_c_compiler_gnu if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+y} ac_save_CFLAGS=$CFLAGS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 printf %s "checking whether $CC accepts -g... " >&6; } if test ${ac_cv_prog_cc_g+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_g=yes else case e in #( e) CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : else case e in #( e) ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 printf "%s\n" "$ac_cv_prog_cc_g" >&6; } if test $ac_test_CFLAGS; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi ac_prog_cc_stdc=no if test x$ac_prog_cc_stdc = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C11 features" >&5 printf %s "checking for $CC option to enable C11 features... " >&6; } if test ${ac_cv_prog_cc_c11+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_prog_cc_c11=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_c_conftest_c11_program _ACEOF for ac_arg in '' -std=gnu11 do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_c11=$ac_arg fi rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c11" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC ;; esac fi if test "x$ac_cv_prog_cc_c11" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } else case e in #( e) if test "x$ac_cv_prog_cc_c11" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5 printf "%s\n" "$ac_cv_prog_cc_c11" >&6; } CC="$CC $ac_cv_prog_cc_c11" ;; esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c11 ac_prog_cc_stdc=c11 ;; esac fi fi if test x$ac_prog_cc_stdc = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C99 features" >&5 printf %s "checking for $CC option to enable C99 features... " >&6; } if test ${ac_cv_prog_cc_c99+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_prog_cc_c99=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_c_conftest_c99_program _ACEOF for ac_arg in '' -std=gnu99 -std=c99 -c99 -qlanglvl=extc1x -qlanglvl=extc99 -AC99 -D_STDC_C99= do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_c99=$ac_arg fi rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c99" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC ;; esac fi if test "x$ac_cv_prog_cc_c99" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } else case e in #( e) if test "x$ac_cv_prog_cc_c99" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 printf "%s\n" "$ac_cv_prog_cc_c99" >&6; } CC="$CC $ac_cv_prog_cc_c99" ;; esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c99 ac_prog_cc_stdc=c99 ;; esac fi fi if test x$ac_prog_cc_stdc = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C89 features" >&5 printf %s "checking for $CC option to enable C89 features... " >&6; } if test ${ac_cv_prog_cc_c89+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_c_conftest_c89_program _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC ;; esac fi if test "x$ac_cv_prog_cc_c89" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } else case e in #( e) if test "x$ac_cv_prog_cc_c89" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 printf "%s\n" "$ac_cv_prog_cc_c89" >&6; } CC="$CC $ac_cv_prog_cc_c89" ;; esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c89 ac_prog_cc_stdc=c89 ;; esac fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5 printf %s "checking whether $CC understands -c and -o together... " >&6; } if test ${am_cv_prog_cc_c_o+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5 ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 printf "%s\n" "$am_cv_prog_cc_c_o" >&6; } if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CC" am_compiler_list= { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 printf %s "checking dependency style of $depcc... " >&6; } if test ${am_cv_CC_dependencies_compiler_type+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 printf "%s\n" "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi case `pwd` in *\ * | *\ *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 printf "%s\n" "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; esac macro_version='2.4.7' macro_revision='2.4.7' ltmain=$ac_aux_dir/ltmain.sh # Make sure we can run config.sub. $SHELL "${ac_aux_dir}config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL ${ac_aux_dir}config.sub" "$LINENO" 5 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 printf %s "checking build system type... " >&6; } if test ${ac_cv_build+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "${ac_aux_dir}config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "${ac_aux_dir}config.sub" $ac_build_alias` || as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $ac_build_alias failed" "$LINENO" 5 ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 printf "%s\n" "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 printf %s "checking host system type... " >&6; } if test ${ac_cv_host+y} then : printf %s "(cached) " >&6 else case e in #( e) if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "${ac_aux_dir}config.sub" $host_alias` || as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $host_alias failed" "$LINENO" 5 fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 printf "%s\n" "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac # Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\(["`$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 printf %s "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "" } case $ECHO in printf*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: printf" >&5 printf "%s\n" "printf" >&6; } ;; print*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 printf "%s\n" "print -r" >&6; } ;; *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: cat" >&5 printf "%s\n" "cat" >&6; } ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 printf %s "checking for a sed that does not truncate output... " >&6; } if test ${ac_cv_path_SED+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_prog in sed gsed do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in #( *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; #( *) ac_count=0 printf %s 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" printf "%s\n" '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 printf "%s\n" "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 printf %s "checking for grep that handles long lines and -e... " >&6; } if test ${ac_cv_path_GREP+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_prog in grep ggrep do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in #( *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; #( *) ac_count=0 printf %s 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" printf "%s\n" 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 printf "%s\n" "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 printf %s "checking for egrep... " >&6; } if test ${ac_cv_path_EGREP+y} then : printf %s "(cached) " >&6 else case e in #( e) if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_prog in egrep do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in #( *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; #( *) ac_count=0 printf %s 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" printf "%s\n" 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 printf "%s\n" "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" EGREP_TRADITIONAL=$EGREP ac_cv_path_EGREP_TRADITIONAL=$EGREP { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 printf %s "checking for fgrep... " >&6; } if test ${ac_cv_path_FGREP+y} then : printf %s "(cached) " >&6 else case e in #( e) if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then ac_path_FGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_prog in fgrep do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_FGREP="$as_dir$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP case `"$ac_path_FGREP" --version 2>&1` in #( *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; #( *) ac_count=0 printf %s 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" printf "%s\n" 'FGREP' >> "conftest.nl" "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_FGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_FGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_FGREP"; then as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_FGREP=$FGREP fi fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 printf "%s\n" "$ac_cv_path_FGREP" >&6; } FGREP="$ac_cv_path_FGREP" test -z "$GREP" && GREP=grep # Check whether --with-gnu-ld was given. if test ${with_gnu_ld+y} then : withval=$with_gnu_ld; test no = "$withval" || with_gnu_ld=yes else case e in #( e) with_gnu_ld=no ;; esac fi ac_prog=ld if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 printf %s "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD=$ac_prog ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test yes = "$with_gnu_ld"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 printf %s "checking for GNU ld... " >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 printf %s "checking for non-GNU ld... " >&6; } fi if test ${lt_cv_path_LD+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD=$ac_dir/$ac_prog # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 printf "%s\n" "$LD" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 printf %s "checking if the linker ($LD) is GNU ld... " >&6; } if test ${lt_cv_prog_gnu_ld+y} then : printf %s "(cached) " >&6 else case e in #( e) # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 printf "%s\n" "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 printf %s "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if test ${lt_cv_path_NM+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM=$NM else lt_nm_to_check=${ac_tool_prefix}nm if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. tmp_nm=$ac_dir/$lt_tmp_nm if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then # Check to see if the nm accepts a BSD-compat flag. # Adding the 'sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty case $build_os in mingw*) lt_bad_file=conftest.nm/nofile ;; *) lt_bad_file=/dev/null ;; esac case `"$tmp_nm" -B $lt_bad_file 2>&1 | $SED '1q'` in *$lt_bad_file* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break 2 ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | $SED '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break 2 ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS=$lt_save_ifs done : ${lt_cv_path_NM=no} fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 printf "%s\n" "$lt_cv_path_NM" >&6; } if test no != "$lt_cv_path_NM"; then NM=$lt_cv_path_NM else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else if test -n "$ac_tool_prefix"; then for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DUMPBIN+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 printf "%s\n" "$DUMPBIN" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$DUMPBIN" && break done fi if test -z "$DUMPBIN"; then ac_ct_DUMPBIN=$DUMPBIN for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_DUMPBIN+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 printf "%s\n" "$ac_ct_DUMPBIN" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$ac_ct_DUMPBIN" && break done if test "x$ac_ct_DUMPBIN" = x; then DUMPBIN=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DUMPBIN=$ac_ct_DUMPBIN fi fi case `$DUMPBIN -symbols -headers /dev/null 2>&1 | $SED '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols -headers" ;; *) DUMPBIN=: ;; esac fi if test : != "$DUMPBIN"; then NM=$DUMPBIN fi fi test -z "$NM" && NM=nm { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 printf %s "checking the name lister ($NM) interface... " >&6; } if test ${lt_cv_nm_interface+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: output\"" >&5) cat conftest.out >&5 if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 printf "%s\n" "$lt_cv_nm_interface" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 printf %s "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 printf "%s\n" "no, using $LN_S" >&6; } fi # find the maximum length of command line arguments { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 printf %s "checking the maximum length of command line arguments... " >&6; } if test ${lt_cv_sys_max_cmd_len+y} then : printf %s "(cached) " >&6 else case e in #( e) i=0 teststring=ABCD case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; bitrig* | darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | $SED 's/.*[ ]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len" && \ test undefined != "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test X`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test 17 != "$i" # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ;; esac fi if test -n "$lt_cv_sys_max_cmd_len"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 printf "%s\n" "$lt_cv_sys_max_cmd_len" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none" >&5 printf "%s\n" "none" >&6; } fi max_cmd_len=$lt_cv_sys_max_cmd_len : ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 printf %s "checking how to convert $build file names to $host format... " >&6; } if test ${lt_cv_to_host_file_cmd+y} then : printf %s "(cached) " >&6 else case e in #( e) case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac ;; esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 printf "%s\n" "$lt_cv_to_host_file_cmd" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 printf %s "checking how to convert $build file names to toolchain format... " >&6; } if test ${lt_cv_to_tool_file_cmd+y} then : printf %s "(cached) " >&6 else case e in #( e) #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac ;; esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 printf "%s\n" "$lt_cv_to_tool_file_cmd" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 printf %s "checking for $LD option to reload object files... " >&6; } if test ${lt_cv_ld_reload_flag+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_ld_reload_flag='-r' ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 printf "%s\n" "$lt_cv_ld_reload_flag" >&6; } reload_flag=$lt_cv_ld_reload_flag case $reload_flag in "" | " "*) ;; *) reload_flag=" $reload_flag" ;; esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in cygwin* | mingw* | pw32* | cegcc*) if test yes != "$GCC"; then reload_cmds=false fi ;; darwin*) if test yes = "$GCC"; then reload_cmds='$LTCC $LTCFLAGS -nostdlib $wl-r -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi ;; esac if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}file", so it can be a program name with args. set dummy ${ac_tool_prefix}file; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_FILECMD+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$FILECMD"; then ac_cv_prog_FILECMD="$FILECMD" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_FILECMD="${ac_tool_prefix}file" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi FILECMD=$ac_cv_prog_FILECMD if test -n "$FILECMD"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $FILECMD" >&5 printf "%s\n" "$FILECMD" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_FILECMD"; then ac_ct_FILECMD=$FILECMD # Extract the first word of "file", so it can be a program name with args. set dummy file; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_FILECMD+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_FILECMD"; then ac_cv_prog_ac_ct_FILECMD="$ac_ct_FILECMD" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_FILECMD="file" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_FILECMD=$ac_cv_prog_ac_ct_FILECMD if test -n "$ac_ct_FILECMD"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_FILECMD" >&5 printf "%s\n" "$ac_ct_FILECMD" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_FILECMD" = x; then FILECMD=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac FILECMD=$ac_ct_FILECMD fi else FILECMD="$ac_cv_prog_FILECMD" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_OBJDUMP+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 printf "%s\n" "$OBJDUMP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_OBJDUMP+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 printf "%s\n" "$ac_ct_OBJDUMP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi test -z "$OBJDUMP" && OBJDUMP=objdump { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 printf %s "checking how to recognize dependent libraries... " >&6; } if test ${lt_cv_deplibs_check_method+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # 'unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # that responds to the $file_magic_cmd with a given extended regex. # If you have 'file' or equivalent on your system and you're not sure # whether 'pass_all' will *always* work, you probably want this one. case $host_os in aix[4-9]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[45]*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='$FILECMD -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. if ( file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly* | midnightbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=$FILECMD lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=$FILECMD case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[3-9]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=$FILECMD lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd* | bitrig*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; os2*) lt_cv_deplibs_check_method=pass_all ;; esac ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 printf "%s\n" "$lt_cv_deplibs_check_method" >&6; } file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DLLTOOL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 printf "%s\n" "$DLLTOOL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_DLLTOOL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 printf "%s\n" "$ac_ct_DLLTOOL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi test -z "$DLLTOOL" && DLLTOOL=dlltool { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 printf %s "checking how to associate runtime and link libraries... " >&6; } if test ${lt_cv_sharedlib_from_linklib_cmd+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh; # decide which one to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd=$ECHO ;; esac ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 printf "%s\n" "$lt_cv_sharedlib_from_linklib_cmd" >&6; } sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO if test -n "$ac_tool_prefix"; then for ac_prog in ar do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_AR+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi AR=$ac_cv_prog_AR if test -n "$AR"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 printf "%s\n" "$AR" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_AR+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 printf "%s\n" "$ac_ct_AR" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} # Use ARFLAGS variable as AR's operation code to sync the variable naming with # Automake. If both AR_FLAGS and ARFLAGS are specified, AR_FLAGS should have # higher priority because thats what people were doing historically (setting # ARFLAGS for automake and AR_FLAGS for libtool). FIXME: Make the AR_FLAGS # variable obsoleted/removed. test ${AR_FLAGS+y} || AR_FLAGS=${ARFLAGS-cr} lt_ar_flags=$AR_FLAGS # Make AR_FLAGS overridable by 'make ARFLAGS='. Don't try to run-time override # by AR_FLAGS because that was never working and AR_FLAGS is about to die. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 printf %s "checking for archiver @FILE support... " >&6; } if test ${lt_cv_ar_at_file+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test 0 -eq "$ac_status"; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test 0 -ne "$ac_status"; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 printf "%s\n" "$lt_cv_ar_at_file" >&6; } if test no = "$lt_cv_ar_at_file"; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_STRIP+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 printf "%s\n" "$STRIP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_STRIP+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 printf "%s\n" "$ac_ct_STRIP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi test -z "$STRIP" && STRIP=: if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_RANLIB+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 printf "%s\n" "$RANLIB" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_RANLIB+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 printf "%s\n" "$ac_ct_RANLIB" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi test -z "$RANLIB" && RANLIB=: # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in bitrig* | openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Check for command to grab the raw symbol name followed by C symbol from nm. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 printf %s "checking command to parse $NM output from $compiler object... " >&6; } if test ${lt_cv_sys_global_symbol_pipe+y} then : printf %s "(cached) " >&6 else case e in #( e) # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[BCDEGRST]' # Regexp to match symbols that can be accessed directly from C. sympat='\([_A-Za-z][_A-Za-z0-9]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[BCDT]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) if test ia64 = "$host_cpu"; then symcode='[ABCDEGRST]' fi ;; irix* | nonstopux*) symcode='[BCDEGRST]' ;; osf*) symcode='[BCDEGQRST]' ;; solaris*) symcode='[BDRT]' ;; sco3.2v5*) symcode='[DT]' ;; sysv4.2uw2*) symcode='[DT]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[ABDT]' ;; sysv4) symcode='[DFNSTU]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[ABCDGIRSTW]' ;; esac if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Gets list of data symbols to import. lt_cv_sys_global_symbol_to_import="$SED -n -e 's/^I .* \(.*\)$/\1/p'" # Adjust the below global symbol transforms to fixup imported variables. lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'" lt_c_name_hook=" -e 's/^I .* \(.*\)$/ {\"\1\", (void *) 0},/p'" lt_c_name_lib_hook="\ -e 's/^I .* \(lib.*\)$/ {\"\1\", (void *) 0},/p'\ -e 's/^I .* \(.*\)$/ {\"lib\1\", (void *) 0},/p'" else # Disable hooks by default. lt_cv_sys_global_symbol_to_import= lt_cdecl_hook= lt_c_name_hook= lt_c_name_lib_hook= fi # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="$SED -n"\ $lt_cdecl_hook\ " -e 's/^T .* \(.*\)$/extern int \1();/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="$SED -n"\ $lt_c_name_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/p'" # Transform an extracted symbol line into symbol name with lib prefix and # symbol address. lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="$SED -n"\ $lt_c_name_lib_hook\ " -e 's/^: \(.*\) .*$/ {\"\1\", (void *) 0},/p'"\ " -e 's/^$symcode$symcode* .* \(lib.*\)$/ {\"\1\", (void *) \&\1},/p'"\ " -e 's/^$symcode$symcode* .* \(.*\)$/ {\"lib\1\", (void *) \&\1},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function, # D for any global variable and I for any imported variable. # Also find C++ and __fastcall symbols from MSVC++ or ICC, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK '"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\ " /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\ " /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\ " {split(\$ 0,a,/\||\r/); split(a[2],s)};"\ " s[1]~/^[@?]/{print f,s[1],s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx" else lt_cv_sys_global_symbol_pipe="$SED -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | $SED '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Now try to grab the symbols. nlist=conftest.nm if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* .* \(.*\)$/ {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS=conftstm.$ac_objext CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest$ac_exeext; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&5 fi else echo "cannot find nm_test_var in $nlist" >&5 fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 fi else echo "$progname: failed program was:" >&5 cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test yes = "$pipe_works"; then break else lt_cv_sys_global_symbol_pipe= fi done ;; esac fi if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: failed" >&5 printf "%s\n" "failed" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ok" >&5 printf "%s\n" "ok" >&6; } fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then nm_file_list_spec='@' fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 printf %s "checking for sysroot... " >&6; } # Check whether --with-sysroot was given. if test ${with_sysroot+y} then : withval=$with_sysroot; else case e in #( e) with_sysroot=no ;; esac fi lt_sysroot= case $with_sysroot in #( yes) if test yes = "$GCC"; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | $SED -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_sysroot" >&5 printf "%s\n" "$with_sysroot" >&6; } as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 printf "%s\n" "${lt_sysroot:-no}" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a working dd" >&5 printf %s "checking for a working dd... " >&6; } if test ${ac_cv_path_lt_DD+y} then : printf %s "(cached) " >&6 else case e in #( e) printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i : ${lt_DD:=$DD} if test -z "$lt_DD"; then ac_path_lt_DD_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_prog in dd do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_lt_DD="$as_dir$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_lt_DD" || continue if "$ac_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=: fi $ac_path_lt_DD_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_lt_DD"; then : fi else ac_cv_path_lt_DD=$lt_DD fi rm -f conftest.i conftest2.i conftest.out ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_lt_DD" >&5 printf "%s\n" "$ac_cv_path_lt_DD" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to truncate binary pipes" >&5 printf %s "checking how to truncate binary pipes... " >&6; } if test ${lt_cv_truncate_bin+y} then : printf %s "(cached) " >&6 else case e in #( e) printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i lt_cv_truncate_bin= if "$ac_cv_path_lt_DD" bs=32 count=1 conftest.out 2>/dev/null; then cmp -s conftest.i conftest.out \ && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1" fi rm -f conftest.i conftest2.i conftest.out test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q" ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_truncate_bin" >&5 printf "%s\n" "$lt_cv_truncate_bin" >&6; } # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. func_cc_basename () { for cc_temp in $*""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` } # Check whether --enable-libtool-lock was given. if test ${enable_libtool_lock+y} then : enableval=$enable_libtool_lock; fi test no = "$enable_libtool_lock" || enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out what ABI is being produced by ac_compile, and set mode # options accordingly. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `$FILECMD conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE=32 ;; *ELF-64*) HPUX_IA64_MODE=64 ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then if test yes = "$lt_cv_prog_gnu_ld"; then case `$FILECMD conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `$FILECMD conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; mips64*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then emul=elf case `$FILECMD conftest.$ac_objext` in *32-bit*) emul="${emul}32" ;; *64-bit*) emul="${emul}64" ;; esac case `$FILECMD conftest.$ac_objext` in *MSB*) emul="${emul}btsmip" ;; *LSB*) emul="${emul}ltsmip" ;; esac case `$FILECMD conftest.$ac_objext` in *N32*) emul="${emul}n32" ;; esac LD="${LD-ld} -m $emul" fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. Note that the listed cases only cover the # situations where additional linker options are needed (such as when # doing 32-bit compilation for a host where ld defaults to 64-bit, or # vice versa); the common cases where no linker options are needed do # not appear in the list. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `$FILECMD conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) case `$FILECMD conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" ;; *) LD="${LD-ld} -m elf_i386" ;; esac ;; powerpc64le-*linux*) LD="${LD-ld} -m elf32lppclinux" ;; powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*linux*) LD="${LD-ld} -m elf64lppc" ;; powerpc-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -belf" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 printf %s "checking whether the C compiler needs -belf... " >&6; } if test ${lt_cv_cc_needs_belf+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_cv_cc_needs_belf=yes else case e in #( e) lt_cv_cc_needs_belf=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 printf "%s\n" "$lt_cv_cc_needs_belf" >&6; } if test yes != "$lt_cv_cc_needs_belf"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS=$SAVE_CFLAGS fi ;; *-*solaris*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `$FILECMD conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*|x86_64-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD=${LD-ld}_sol2 fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks=$enable_libtool_lock if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. set dummy ${ac_tool_prefix}mt; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_MANIFEST_TOOL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 printf "%s\n" "$MANIFEST_TOOL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_MANIFEST_TOOL"; then ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL # Extract the first word of "mt", so it can be a program name with args. set dummy mt; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_MANIFEST_TOOL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 printf "%s\n" "$ac_ct_MANIFEST_TOOL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_MANIFEST_TOOL" = x; then MANIFEST_TOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL fi else MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 printf %s "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } if test ${lt_cv_path_mainfest_tool+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 printf "%s\n" "$lt_cv_path_mainfest_tool" >&6; } if test yes != "$lt_cv_path_mainfest_tool"; then MANIFEST_TOOL=: fi case $host_os in rhapsody* | darwin*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DSYMUTIL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 printf "%s\n" "$DSYMUTIL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_DSYMUTIL"; then ac_ct_DSYMUTIL=$DSYMUTIL # Extract the first word of "dsymutil", so it can be a program name with args. set dummy dsymutil; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_DSYMUTIL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 printf "%s\n" "$ac_ct_DSYMUTIL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_DSYMUTIL" = x; then DSYMUTIL=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DSYMUTIL=$ac_ct_DSYMUTIL fi else DSYMUTIL="$ac_cv_prog_DSYMUTIL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. set dummy ${ac_tool_prefix}nmedit; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_NMEDIT+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 printf "%s\n" "$NMEDIT" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_NMEDIT"; then ac_ct_NMEDIT=$NMEDIT # Extract the first word of "nmedit", so it can be a program name with args. set dummy nmedit; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_NMEDIT+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_NMEDIT="nmedit" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 printf "%s\n" "$ac_ct_NMEDIT" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_NMEDIT" = x; then NMEDIT=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac NMEDIT=$ac_ct_NMEDIT fi else NMEDIT="$ac_cv_prog_NMEDIT" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. set dummy ${ac_tool_prefix}lipo; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_LIPO+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_LIPO="${ac_tool_prefix}lipo" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 printf "%s\n" "$LIPO" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_LIPO"; then ac_ct_LIPO=$LIPO # Extract the first word of "lipo", so it can be a program name with args. set dummy lipo; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_LIPO+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_LIPO="lipo" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 printf "%s\n" "$ac_ct_LIPO" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_LIPO" = x; then LIPO=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac LIPO=$ac_ct_LIPO fi else LIPO="$ac_cv_prog_LIPO" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. set dummy ${ac_tool_prefix}otool; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_OTOOL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL="${ac_tool_prefix}otool" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 printf "%s\n" "$OTOOL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL"; then ac_ct_OTOOL=$OTOOL # Extract the first word of "otool", so it can be a program name with args. set dummy otool; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_OTOOL+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL="otool" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 printf "%s\n" "$ac_ct_OTOOL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_OTOOL" = x; then OTOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL=$ac_ct_OTOOL fi else OTOOL="$ac_cv_prog_OTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. set dummy ${ac_tool_prefix}otool64; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_OTOOL64+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 printf "%s\n" "$OTOOL64" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL64"; then ac_ct_OTOOL64=$OTOOL64 # Extract the first word of "otool64", so it can be a program name with args. set dummy otool64; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_OTOOL64+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL64="otool64" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 printf "%s\n" "$ac_ct_OTOOL64" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_ct_OTOOL64" = x; then OTOOL64=":" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL64=$ac_ct_OTOOL64 fi else OTOOL64="$ac_cv_prog_OTOOL64" fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 printf %s "checking for -single_module linker flag... " >&6; } if test ${lt_cv_apple_cc_single_mod+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_apple_cc_single_mod=no if test -z "$LT_MULTI_MODULE"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&5 $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&5 # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test 0 = "$_lt_result"; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&5 fi rm -rf libconftest.dylib* rm -f conftest.* fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 printf "%s\n" "$lt_cv_apple_cc_single_mod" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 printf %s "checking for -exported_symbols_list linker flag... " >&6; } if test ${lt_cv_ld_exported_symbols_list+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_cv_ld_exported_symbols_list=yes else case e in #( e) lt_cv_ld_exported_symbols_list=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 printf "%s\n" "$lt_cv_ld_exported_symbols_list" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 printf %s "checking for -force_load linker flag... " >&6; } if test ${lt_cv_ld_force_load+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 echo "$AR $AR_FLAGS libconftest.a conftest.o" >&5 $AR $AR_FLAGS libconftest.a conftest.o 2>&5 echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&5 elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then lt_cv_ld_force_load=yes else cat conftest.err >&5 fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 printf "%s\n" "$lt_cv_ld_force_load" >&6; } case $host_os in rhapsody* | darwin1.[012]) _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; darwin*) case $MACOSX_DEPLOYMENT_TARGET,$host in 10.[012],*|,*powerpc*-darwin[5-8]*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; *) _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test yes = "$lt_cv_apple_cc_single_mod"; then _lt_dar_single_mod='$single_module' fi if test yes = "$lt_cv_ld_exported_symbols_list"; then _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib' fi if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac # func_munge_path_list VARIABLE PATH # ----------------------------------- # VARIABLE is name of variable containing _space_ separated list of # directories to be munged by the contents of PATH, which is string # having a format: # "DIR[:DIR]:" # string "DIR[ DIR]" will be prepended to VARIABLE # ":DIR[:DIR]" # string "DIR[ DIR]" will be appended to VARIABLE # "DIRP[:DIRP]::[DIRA:]DIRA" # string "DIRP[ DIRP]" will be prepended to VARIABLE and string # "DIRA[ DIRA]" will be appended to VARIABLE # "DIR[:DIR]" # VARIABLE will be replaced by "DIR[ DIR]" func_munge_path_list () { case x$2 in x) ;; *:) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\" ;; x:*) eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\" ;; *::*) eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\" ;; *) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\" ;; esac } ac_header= ac_cache= for ac_item in $ac_header_c_list do if test $ac_cache; then ac_fn_c_check_header_compile "$LINENO" $ac_header ac_cv_header_$ac_cache "$ac_includes_default" if eval test \"x\$ac_cv_header_$ac_cache\" = xyes; then printf "%s\n" "#define $ac_item 1" >> confdefs.h fi ac_header= ac_cache= elif test $ac_header; then ac_cache=$ac_item else ac_header=$ac_item fi done if test $ac_cv_header_stdlib_h = yes && test $ac_cv_header_string_h = yes then : printf "%s\n" "#define STDC_HEADERS 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default " if test "x$ac_cv_header_dlfcn_h" = xyes then : printf "%s\n" "#define HAVE_DLFCN_H 1" >>confdefs.h fi # Set options # Check whether --enable-static was given. if test ${enable_static+y} then : enableval=$enable_static; p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS=$lt_save_ifs ;; esac else case e in #( e) enable_static=no ;; esac fi enable_dlopen=no enable_win32_dll=no # Check whether --enable-shared was given. if test ${enable_shared+y} then : enableval=$enable_shared; p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS=$lt_save_ifs ;; esac else case e in #( e) enable_shared=yes ;; esac fi # Check whether --with-pic was given. if test ${with_pic+y} then : withval=$with_pic; lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for lt_pkg in $withval; do IFS=$lt_save_ifs if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS=$lt_save_ifs ;; esac else case e in #( e) pic_mode=default ;; esac fi # Check whether --enable-fast-install was given. if test ${enable_fast_install+y} then : enableval=$enable_fast_install; p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, for pkg in $enableval; do IFS=$lt_save_ifs if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS=$lt_save_ifs ;; esac else case e in #( e) enable_fast_install=yes ;; esac fi shared_archive_member_spec= case $host,$enable_shared in power*-*-aix[5-9]*,yes) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking which variant of shared library versioning to provide" >&5 printf %s "checking which variant of shared library versioning to provide... " >&6; } # Check whether --with-aix-soname was given. if test ${with_aix_soname+y} then : withval=$with_aix_soname; case $withval in aix|svr4|both) ;; *) as_fn_error $? "Unknown argument to --with-aix-soname" "$LINENO" 5 ;; esac lt_cv_with_aix_soname=$with_aix_soname else case e in #( e) if test ${lt_cv_with_aix_soname+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_with_aix_soname=aix ;; esac fi with_aix_soname=$lt_cv_with_aix_soname ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_aix_soname" >&5 printf "%s\n" "$with_aix_soname" >&6; } if test aix != "$with_aix_soname"; then # For the AIX way of multilib, we name the shared archive member # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o', # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File. # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag, # the AIX toolchain works better with OBJECT_MODE set (default 32). if test 64 = "${OBJECT_MODE-32}"; then shared_archive_member_spec=shr_64 else shared_archive_member_spec=shr fi fi ;; *) with_aix_soname=aix ;; esac # This can be used to rebuild libtool when needed LIBTOOL_DEPS=$ltmain # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' test -z "$LN_S" && LN_S="ln -s" if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 printf %s "checking for objdir... " >&6; } if test ${lt_cv_objdir+y} then : printf %s "(cached) " >&6 else case e in #( e) rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 printf "%s\n" "$lt_cv_objdir" >&6; } objdir=$lt_cv_objdir printf "%s\n" "#define LT_OBJDIR \"$lt_cv_objdir/\"" >>confdefs.h case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a '.a' archive for static linking (except MSVC and # ICC, which need '.lib'). libext=a with_gnu_ld=$lt_cv_prog_gnu_ld old_CC=$CC old_CFLAGS=$CFLAGS # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o func_cc_basename $compiler cc_basename=$func_cc_basename_result # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 printf %s "checking for ${ac_tool_prefix}file... " >&6; } if test ${lt_cv_path_MAGIC_CMD+y} then : printf %s "(cached) " >&6 else case e in #( e) case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD=$MAGIC_CMD lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/${ac_tool_prefix}file"; then lt_cv_path_MAGIC_CMD=$ac_dir/"${ac_tool_prefix}file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD=$lt_cv_path_MAGIC_CMD if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; esac ;; esac fi MAGIC_CMD=$lt_cv_path_MAGIC_CMD if test -n "$MAGIC_CMD"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 printf "%s\n" "$MAGIC_CMD" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for file" >&5 printf %s "checking for file... " >&6; } if test ${lt_cv_path_MAGIC_CMD+y} then : printf %s "(cached) " >&6 else case e in #( e) case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD=$MAGIC_CMD lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS=$lt_save_ifs test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/file"; then lt_cv_path_MAGIC_CMD=$ac_dir/"file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD=$lt_cv_path_MAGIC_CMD if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; esac ;; esac fi MAGIC_CMD=$lt_cv_path_MAGIC_CMD if test -n "$MAGIC_CMD"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 printf "%s\n" "$MAGIC_CMD" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi else MAGIC_CMD=: fi fi fi ;; esac # Use C for the default configuration in the libtool script lt_save_CC=$CC ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o objext=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then lt_prog_compiler_no_builtin_flag= if test yes = "$GCC"; then case $cc_basename in nvcc*) lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; *) lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 printf %s "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if test ${lt_cv_prog_compiler_rtti_exceptions+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" ## exclude from sc_useless_quotes_in_assignment # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_rtti_exceptions=yes fi fi $RM conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 printf "%s\n" "$lt_cv_prog_compiler_rtti_exceptions" >&6; } if test yes = "$lt_cv_prog_compiler_rtti_exceptions"; then lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" else : fi fi lt_prog_compiler_wl= lt_prog_compiler_pic= lt_prog_compiler_static= if test yes = "$GCC"; then lt_prog_compiler_wl='-Wl,' lt_prog_compiler_static='-static' case $host_os in aix*) # All AIX code is PIC. if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' fi lt_prog_compiler_pic='-fPIC' ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the '-m68020' flag to GCC prevents building anything better, # like '-m68040'. lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic='-DDLL_EXPORT' case $host_os in os2*) lt_prog_compiler_static='$wl-static' ;; esac ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) lt_prog_compiler_pic='-fPIC' ;; esac ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. lt_prog_compiler_can_build_shared=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic=-Kconform_pic fi ;; *) lt_prog_compiler_pic='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 lt_prog_compiler_wl='-Xlinker ' if test -n "$lt_prog_compiler_pic"; then lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) lt_prog_compiler_wl='-Wl,' if test ia64 = "$host_cpu"; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' else lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' fi ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' case $cc_basename in nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; esac ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' case $host_os in os2*) lt_prog_compiler_static='$wl-static' ;; esac ;; hpux9* | hpux10* | hpux11*) lt_prog_compiler_wl='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? lt_prog_compiler_static='$wl-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) lt_prog_compiler_wl='-Wl,' # PIC (with -KPIC) is the default. lt_prog_compiler_static='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64, which still supported -KPIC. ecc*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; # Lahey Fortran 8.1. lf95*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='--shared' lt_prog_compiler_static='--static' ;; nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; tcc*) # Fabrice Bellard et al's Tiny C Compiler lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; ccc*) lt_prog_compiler_wl='-Wl,' # All Alpha code is PIC. lt_prog_compiler_static='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-qpic' lt_prog_compiler_static='-qstaticlink' ;; *) case `$CC -V 2>&1 | $SED 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='' ;; *Sun\ F* | *Sun*Fortran*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Wl,' ;; *Intel*\ [CF]*Compiler*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; *Portland\ Group*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; esac ;; esac ;; newsos6) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; osf3* | osf4* | osf5*) lt_prog_compiler_wl='-Wl,' # All OSF/1 code is PIC. lt_prog_compiler_static='-non_shared' ;; rdos*) lt_prog_compiler_static='-non_shared' ;; solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) lt_prog_compiler_wl='-Qoption ld ';; *) lt_prog_compiler_wl='-Wl,';; esac ;; sunos4*) lt_prog_compiler_wl='-Qoption ld ' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic='-Kconform_pic' lt_prog_compiler_static='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; unicos*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_can_build_shared=no ;; uts4*) lt_prog_compiler_pic='-pic' lt_prog_compiler_static='-Bstatic' ;; *) lt_prog_compiler_can_build_shared=no ;; esac fi case $host_os in # For platforms that do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic= ;; *) lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 printf %s "checking for $compiler option to produce PIC... " >&6; } if test ${lt_cv_prog_compiler_pic+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_prog_compiler_pic=$lt_prog_compiler_pic ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 printf "%s\n" "$lt_cv_prog_compiler_pic" >&6; } lt_prog_compiler_pic=$lt_cv_prog_compiler_pic # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 printf %s "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } if test ${lt_cv_prog_compiler_pic_works+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" ## exclude from sc_useless_quotes_in_assignment # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works=yes fi fi $RM conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 printf "%s\n" "$lt_cv_prog_compiler_pic_works" >&6; } if test yes = "$lt_cv_prog_compiler_pic_works"; then case $lt_prog_compiler_pic in "" | " "*) ;; *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; esac else lt_prog_compiler_pic= lt_prog_compiler_can_build_shared=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 printf %s "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if test ${lt_cv_prog_compiler_static_works+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_prog_compiler_static_works=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works=yes fi else lt_cv_prog_compiler_static_works=yes fi fi $RM -r conftest* LDFLAGS=$save_LDFLAGS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 printf "%s\n" "$lt_cv_prog_compiler_static_works" >&6; } if test yes = "$lt_cv_prog_compiler_static_works"; then : else lt_prog_compiler_static= fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if test ${lt_cv_prog_compiler_c_o+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 printf "%s\n" "$lt_cv_prog_compiler_c_o" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if test ${lt_cv_prog_compiler_c_o+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 printf "%s\n" "$lt_cv_prog_compiler_c_o" >&6; } hard_links=nottested if test no = "$lt_cv_prog_compiler_c_o" && test no != "$need_locks"; then # do not overwrite the value of need_locks provided by the user { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 printf %s "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 printf "%s\n" "$hard_links" >&6; } if test no = "$hard_links"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&5 printf "%s\n" "$as_me: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 printf %s "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } runpath_var= allow_undefined_flag= always_export_symbols=no archive_cmds= archive_expsym_cmds= compiler_needs_object=no enable_shared_with_static_runtimes=no export_dynamic_flag_spec= export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' hardcode_automatic=no hardcode_direct=no hardcode_direct_absolute=no hardcode_libdir_flag_spec= hardcode_libdir_separator= hardcode_minus_L=no hardcode_shlibpath_var=unsupported inherit_rpath=no link_all_deplibs=unknown module_cmds= module_expsym_cmds= old_archive_from_new_cmds= old_archive_from_expsyms_cmds= thread_safe_flag_spec= whole_archive_flag_spec= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list include_expsyms= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ' (' and ')$', so one must not match beginning or # end of line. Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc', # as well as any symbol that contains 'd'. exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. if test yes != "$GCC"; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++ or ICC) with_gnu_ld=yes ;; openbsd* | bitrig*) with_gnu_ld=no ;; esac ld_shlibs=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test yes = "$with_gnu_ld"; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; *\ \(GNU\ Binutils\)\ [3-9]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test yes = "$lt_use_gnu_ld_interface"; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='$wl' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' export_dynamic_flag_spec='$wl--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else whole_archive_flag_spec= fi supports_anon_versioning=no case `$LD -v | $SED -e 's/([^)]\+)\s\+//' 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[3-9]*) # On AIX/PPC, the GNU linker is very broken if test ia64 != "$host_cpu"; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' else ld_shlibs=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' export_dynamic_flag_spec='$wl--export-all-symbols' allow_undefined_flag=unsupported always_export_symbols=no enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file, use it as # is; otherwise, prepend EXPORTS... archive_expsym_cmds='if test DEF = "`$SED -n -e '\''s/^[ ]*//'\'' -e '\''/^\(;.*\)*$/d'\'' -e '\''s/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p'\'' -e q $export_symbols`" ; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs=no fi ;; haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' link_all_deplibs=yes ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported shrext_cmds=.dll archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' enable_shared_with_static_runtimes=yes file_list_spec='@' ;; interix[3-9]*) hardcode_direct=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='$wl-rpath,$libdir' export_dynamic_flag_spec='$wl-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test linux-dietlibc = "$host_os"; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test no = "$tmp_diet" then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 whole_archive_flag_spec= tmp_sharedflag='--shared' ;; nagfor*) # NAGFOR 5.3 tmp_sharedflag='-Wl,-shared' ;; xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' compiler_needs_object=yes ;; esac case `$CC -V 2>&1 | $SED 5q` in *Sun\ C*) # Sun C 5.9 whole_archive_flag_spec='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive' compiler_needs_object=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' if test yes = "$supports_anon_versioning"; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib' fi case $cc_basename in tcc*) export_dynamic_flag_spec='-rdynamic' ;; xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test yes = "$supports_anon_versioning"; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else ld_shlibs=no fi ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac ;; sunos4*) archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= hardcode_direct=yes hardcode_shlibpath_var=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac if test no = "$ld_shlibs"; then runpath_var= hardcode_libdir_flag_spec= export_dynamic_flag_spec= whole_archive_flag_spec= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) allow_undefined_flag=unsupported always_export_symbols=yes archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. hardcode_minus_L=yes if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. hardcode_direct=unsupported fi ;; aix[4-9]*) if test ia64 = "$host_cpu"; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag= else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to GNU nm, but means don't demangle to AIX nm. # Without the "-l" option, or with the "-B" option, AIX nm treats # weak defined symbols like other global defined symbols, whereas # GNU nm marks them as "W". # While the 'weak' keyword is ignored in the Export File, we need # it in the Import File for the 'aix-soname' feature, so we have # to replace the "-B" option with "-P" for AIX nm. if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols' else export_symbols_cmds='`func_echo_all $NM | $SED -e '\''s/B\([^B]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "L") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && (substr(\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # have runtime linking enabled, and use it for executables. # For shared libraries, we enable/disable runtime linking # depending on the kind of the shared library created - # when "with_aix_soname,aix_use_runtimelinking" is: # "aix,no" lib.a(lib.so.V) shared, rtl:no, for executables # "aix,yes" lib.so shared, rtl:yes, for executables # lib.a static archive # "both,no" lib.so.V(shr.o) shared, rtl:yes # lib.a(lib.so.V) shared, rtl:no, for executables # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a(lib.so.V) shared, rtl:no # "svr4,*" lib.so.V(shr.o) shared, rtl:yes, for executables # lib.a static archive case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then aix_use_runtimelinking=yes break fi done if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then # With aix-soname=svr4, we create the lib.so.V shared archives only, # so we don't have lib.a shared libs to link our executables. # We have to force runtime linking in this case. aix_use_runtimelinking=yes LDFLAGS="$LDFLAGS -Wl,-brtl" fi ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds='' hardcode_direct=yes hardcode_direct_absolute=yes hardcode_libdir_separator=':' link_all_deplibs=yes file_list_spec='$wl-f,' case $with_aix_soname,$aix_use_runtimelinking in aix,*) ;; # traditional, no import file svr4,* | *,yes) # use import file # The Import File defines what to hardcode. hardcode_direct=no hardcode_direct_absolute=no ;; esac if test yes = "$GCC"; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`$CC -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L=yes hardcode_libdir_flag_spec='-L$libdir' hardcode_libdir_separator= fi ;; esac shared_flag='-shared' if test yes = "$aix_use_runtimelinking"; then shared_flag="$shared_flag "'$wl-G' fi # Need to ensure runtime linking is disabled for the traditional # shared library, or the linker may eventually find shared libraries # /with/ Import File - we do not want to mix them. shared_flag_aix='-shared' shared_flag_svr4='-shared $wl-G' else # not using gcc if test ia64 = "$host_cpu"; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test yes = "$aix_use_runtimelinking"; then shared_flag='$wl-G' else shared_flag='$wl-bM:SRE' fi shared_flag_aix='$wl-bM:SRE' shared_flag_svr4='$wl-G' fi fi export_dynamic_flag_spec='$wl-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. always_export_symbols=yes if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag='-berok' # Determine the default libpath from the value encoded in an # empty executable. if test set = "${lt_cv_aix_libpath+set}"; then aix_libpath=$lt_cv_aix_libpath else if test ${lt_cv_aix_libpath_+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=/usr/lib:/lib fi ;; esac fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag else if test ia64 = "$host_cpu"; then hardcode_libdir_flag_spec='$wl-R $libdir:/usr/lib:/lib' allow_undefined_flag="-z nodefs" archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test set = "${lt_cv_aix_libpath+set}"; then aix_libpath=$lt_cv_aix_libpath else if test ${lt_cv_aix_libpath_+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=/usr/lib:/lib fi ;; esac fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag=' $wl-bernotok' allow_undefined_flag=' $wl-berok' if test yes = "$with_gnu_ld"; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec='$wl--whole-archive$convenience $wl--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec='$convenience' fi archive_cmds_need_lc=yes archive_expsym_cmds='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d' # -brtl affects multiple linker settings, -berok does not and is overridden later compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([, ]\\)%-berok\\1%g"`' if test svr4 != "$with_aix_soname"; then # This is similar to how AIX traditionally builds its shared libraries. archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname' fi if test aix != "$with_aix_soname"; then archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) > $output_objdir/$realname.d/$shared_archive_member_spec.imp~$AR $AR_FLAGS $output_objdir/$soname $output_objdir/$realname.d/$shared_archive_member_spec.o $output_objdir/$realname.d/$shared_archive_member_spec.imp' else # used by -dlpreopen to get the symbols archive_expsym_cmds="$archive_expsym_cmds"'~$MV $output_objdir/$realname.d/$soname $output_objdir' fi archive_expsym_cmds="$archive_expsym_cmds"'~$RM -r $output_objdir/$realname.d' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; bsdi[45]*) export_dynamic_flag_spec=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl* | icl*) # Native MSVC or ICC hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported always_export_symbols=yes file_list_spec='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' archive_expsym_cmds='if test DEF = "`$SED -n -e '\''s/^[ ]*//'\'' -e '\''/^\(;.*\)*$/d'\'' -e '\''s/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p'\'' -e q $export_symbols`" ; then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' enable_shared_with_static_runtimes=yes exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib old_postinstall_cmds='chmod 644 $oldlib' postlink_cmds='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile=$lt_outputfile.exe lt_tool_outputfile=$lt_tool_outputfile.exe ;; esac~ if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC and ICC wrapper hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. old_archive_from_new_cmds='true' # FIXME: Should let the user specify the lib program. old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' enable_shared_with_static_runtimes=yes ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc=no hardcode_direct=no hardcode_automatic=yes hardcode_shlibpath_var=unsupported if test yes = "$lt_cv_ld_force_load"; then whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec='' fi link_all_deplibs=yes allow_undefined_flag=$_lt_dar_allow_undefined case $cc_basename in ifort*|nagfor*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test yes = "$_lt_dar_can_shared"; then output_verbose_link_cmd=func_echo_all archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil" module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil" archive_expsym_cmds="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" module_expsym_cmds="$SED -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" else ld_shlibs=no fi ;; dgux*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly* | midnightbsd*) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; hpux9*) if test yes = "$GCC"; then archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' else archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib' fi hardcode_libdir_flag_spec='$wl+b $wl$libdir' hardcode_libdir_separator=: hardcode_direct=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes export_dynamic_flag_spec='$wl-E' ;; hpux10*) if test yes,no = "$GCC,$with_gnu_ld"; then archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test no = "$with_gnu_ld"; then hardcode_libdir_flag_spec='$wl+b $wl$libdir' hardcode_libdir_separator=: hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes fi ;; hpux11*) if test yes,no = "$GCC,$with_gnu_ld"; then case $host_cpu in hppa*64*) archive_cmds='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) archive_cmds='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 printf %s "checking if $CC understands -b... " >&6; } if test ${lt_cv_prog_compiler__b+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_prog_compiler__b=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler__b=yes fi else lt_cv_prog_compiler__b=yes fi fi $RM -r conftest* LDFLAGS=$save_LDFLAGS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 printf "%s\n" "$lt_cv_prog_compiler__b" >&6; } if test yes = "$lt_cv_prog_compiler__b"; then archive_cmds='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi ;; esac fi if test no = "$with_gnu_ld"; then hardcode_libdir_flag_spec='$wl+b $wl$libdir' hardcode_libdir_separator=: case $host_cpu in hppa*64*|ia64*) hardcode_direct=no hardcode_shlibpath_var=no ;; *) hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='$wl-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test yes = "$GCC"; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 printf %s "checking whether the $host_os linker accepts -exported_symbol... " >&6; } if test ${lt_cv_irix_exported_symbol+y} then : printf %s "(cached) " >&6 else case e in #( e) save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int foo (void) { return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_cv_irix_exported_symbol=yes else case e in #( e) lt_cv_irix_exported_symbol=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 printf "%s\n" "$lt_cv_irix_exported_symbol" >&6; } if test yes = "$lt_cv_irix_exported_symbol"; then archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib' fi else archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' hardcode_libdir_separator=: inherit_rpath=yes link_all_deplibs=yes ;; linux*) case $cc_basename in tcc*) # Fabrice Bellard et al's Tiny C Compiler ld_shlibs=yes archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; newsos6) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' hardcode_libdir_separator=: hardcode_shlibpath_var=no ;; *nto* | *qnx*) ;; openbsd* | bitrig*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no hardcode_direct_absolute=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols' hardcode_libdir_flag_spec='$wl-rpath,$libdir' export_dynamic_flag_spec='$wl-E' else archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='$wl-rpath,$libdir' fi else ld_shlibs=no fi ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported shrext_cmds=.dll archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~ $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~ $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~ $ECHO EXPORTS >> $output_objdir/$libname.def~ prefix_cmds="$SED"~ if test EXPORTS = "`$SED 1q $export_symbols`"; then prefix_cmds="$prefix_cmds -e 1d"; fi~ prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~ cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' enable_shared_with_static_runtimes=yes file_list_spec='@' ;; osf3*) if test yes = "$GCC"; then allow_undefined_flag=' $wl-expect_unresolved $wl\*' archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' hardcode_libdir_separator=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test yes = "$GCC"; then allow_undefined_flag=' $wl-expect_unresolved $wl\*' archive_cmds='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib' hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib' archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly hardcode_libdir_flag_spec='-rpath $libdir' fi archive_cmds_need_lc='no' hardcode_libdir_separator=: ;; solaris*) no_undefined_flag=' -z defs' if test yes = "$GCC"; then wlarc='$wl' archive_cmds='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' archive_cmds='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='$wl' archive_cmds='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi hardcode_libdir_flag_spec='-R$libdir' hardcode_shlibpath_var=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands '-z linker_flag'. GCC discards it without '$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test yes = "$GCC"; then whole_archive_flag_spec='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract' else whole_archive_flag_spec='-z allextract$convenience -z defaultextract' fi ;; esac link_all_deplibs=yes ;; sunos4*) if test sequent = "$host_vendor"; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. archive_cmds='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi hardcode_libdir_flag_spec='-L$libdir' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; sysv4) case $host_vendor in sni) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' reload_cmds='$CC -r -o $output$reload_objs' hardcode_direct=no ;; motorola) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' hardcode_shlibpath_var=no ;; sysv4.3*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no export_dynamic_flag_spec='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes ld_shlibs=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag='$wl-z,text' archive_cmds_need_lc=no hardcode_shlibpath_var=no runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We CANNOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag='$wl-z,text' allow_undefined_flag='$wl-z,nodefs' archive_cmds_need_lc=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='$wl-R,$libdir' hardcode_libdir_separator=':' link_all_deplibs=yes export_dynamic_flag_spec='$wl-Bexport' runpath_var='LD_RUN_PATH' if test yes = "$GCC"; then archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; *) ld_shlibs=no ;; esac if test sni = "$host_vendor"; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) export_dynamic_flag_spec='$wl-Blargedynsym' ;; esac fi fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 printf "%s\n" "$ld_shlibs" >&6; } test no = "$ld_shlibs" && can_build_shared=no with_gnu_ld=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc" in x|xyes) # Assume -lc should be added archive_cmds_need_lc=yes if test yes,yes = "$GCC,$enable_shared"; then case $archive_cmds in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 printf %s "checking whether -lc should be explicitly linked in... " >&6; } if test ${lt_cv_archive_cmds_need_lc+y} then : printf %s "(cached) " >&6 else case e in #( e) $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl pic_flag=$lt_prog_compiler_pic compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag allow_undefined_flag= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc=no else lt_cv_archive_cmds_need_lc=yes fi allow_undefined_flag=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 printf "%s\n" "$lt_cv_archive_cmds_need_lc" >&6; } archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc ;; esac fi ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 printf %s "checking dynamic linker characteristics... " >&6; } if test yes = "$GCC"; then case $host_os in darwin*) lt_awk_arg='/^libraries:/,/LR/' ;; *) lt_awk_arg='/^libraries:/' ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq='s|=\([A-Za-z]:\)|\1|g' ;; *) lt_sed_strip_eq='s|=/|/|g' ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary... lt_tmp_lt_search_path_spec= lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` # ...but if some path component already ends with the multilib dir we assume # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer). case "$lt_multi_os_dir; $lt_search_path_spec " in "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*) lt_multi_os_dir= ;; esac for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir" elif test -n "$lt_multi_os_dir"; then test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS = " "; FS = "/|\n";} { lt_foo = ""; lt_count = 0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo = "/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[lt_foo]++; } if (lt_freq[lt_foo] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's|/\([A-Za-z]:\)|\1|g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=.so postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='$libname$release$shared_ext$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test ia64 = "$host_cpu"; then # AIX 5 supports IA64 library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line '#! .'. This would cause the generated library to # depend on '.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # Using Import Files as archive members, it is possible to support # filename-based versioning of shared library archives on AIX. While # this would work for both with and without runtime linking, it will # prevent static linking of such archives. So we do filename-based # shared library versioning with .so extension only, which is used # when both runtime linking and shared linking is enabled. # Unfortunately, runtime linking may impact performance, so we do # not want this to be the default eventually. Also, we use the # versioned .so libs for executables only if there is the -brtl # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. # To allow for filename-based versioning support, we need to create # libNAME.so.V as an archive file, containing: # *) an Import File, referring to the versioned filename of the # archive as well as the shared archive member, telling the # bitwidth (32 or 64) of that shared object, and providing the # list of exported symbols of that shared object, eventually # decorated with the 'weak' keyword # *) the shared object with the F_LOADONLY flag set, to really avoid # it being seen by the linker. # At run time we better use the real file rather than another symlink, # but for link time we create the symlink libNAME.so -> libNAME.so.V case $with_aix_soname,$aix_use_runtimelinking in # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. aix,yes) # traditional libtool dynamic_linker='AIX unversionable lib.so' # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; aix,no) # traditional AIX only dynamic_linker='AIX lib.a(lib.so.V)' # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' ;; svr4,*) # full svr4 only dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o)" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,yes) # both, prefer svr4 dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o), lib.a(lib.so.V)" library_names_spec='$libname$release$shared_ext$major $libname$shared_ext' # unpreferred sharedlib libNAME.a needs extra handling postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"' postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"' # We do not specify a path in Import Files, so LIBPATH fires. shlibpath_overrides_runpath=yes ;; *,no) # both, prefer aix dynamic_linker="AIX lib.a(lib.so.V), lib.so.V($shared_archive_member_spec.o)" library_names_spec='$libname$release.a $libname.a' soname_spec='$libname$release$shared_ext$major' # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)' postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"' ;; esac shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='$libname$shared_ext' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo $libname | $SED -e 's/^lib/pw/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl* | *,icl*) # Native MSVC or ICC libname_spec='$name' soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' library_names_spec='$libname.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec=$LIB if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC and ICC wrapper library_names_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='$libname$release$major$shared_ext $libname$shared_ext' soname_spec='$libname$release$major$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly* | midnightbsd*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=no sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' if test 32 = "$HPUX_IA64_MODE"; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" sys_lib_dlsearch_path_spec=/usr/lib/hpux32 else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" sys_lib_dlsearch_path_spec=/usr/lib/hpux64 fi ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test yes = "$lt_cv_prog_gnu_ld"; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff" sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; linux*android*) version_type=none # Android doesn't support versioned libraries. need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext' soname_spec='$libname$release$shared_ext' finish_cmds= shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes dynamic_linker='Android linker' # Don't embed -rpath directories since the linker doesn't support them. hardcode_libdir_flag_spec='-L$libdir' ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if test ${lt_cv_shlibpath_overrides_runpath+y} then : printf %s "(cached) " >&6 else case e in #( e) lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir ;; esac fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Add ABI-specific directories to the system library path. sys_lib_dlsearch_path_spec="/lib64 /usr/lib64 /lib /usr/lib" # Ideally, we could use ldconfig to report *all* directores which are # searched for libraries, however this is still not possible. Aside from not # being certain /sbin/ldconfig is available, command # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, # even though it is searched at run-time. Try to do the best guess by # appending ld.so.conf contents (and includes) to the search path. if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="$sys_lib_dlsearch_path_spec $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd* | bitrig*) version_type=sunos sys_lib_dlsearch_path_spec=/usr/lib need_lib_prefix=no if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then need_version=no else need_version=yes fi library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; os2*) libname_spec='$name' version_type=windows shrext_cmds=.dll need_version=no need_lib_prefix=no # OS/2 can only load a DLL with a base name of 8 characters or less. soname_spec='`test -n "$os2dllname" && libname="$os2dllname"; v=$($ECHO $release$versuffix | tr -d .-); n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _); $ECHO $n$v`$shared_ext' library_names_spec='${libname}_dll.$libext' dynamic_linker='OS/2 ld.exe' shlibpath_var=BEGINLIBPATH sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec postinstall_cmds='base_file=`basename \$file`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='$libname$release$shared_ext$major' library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test yes = "$with_gnu_ld"; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec; then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' soname_spec='$libname$shared_ext.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=sco need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test yes = "$with_gnu_ld"; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' soname_spec='$libname$release$shared_ext$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 printf "%s\n" "$dynamic_linker" >&6; } test no = "$dynamic_linker" && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test yes = "$GCC"; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec fi if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec fi # remember unaugmented sys_lib_dlsearch_path content for libtool script decls... configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec # ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" # to be used as default LT_SYS_LIBRARY_PATH value in generated libtool configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 printf %s "checking how to hardcode library paths into programs... " >&6; } hardcode_action= if test -n "$hardcode_libdir_flag_spec" || test -n "$runpath_var" || test yes = "$hardcode_automatic"; then # We can hardcode non-existent directories. if test no != "$hardcode_direct" && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, )" && test no != "$hardcode_minus_L"; then # Linking always hardcodes the temporary library directory. hardcode_action=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action=unsupported fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 printf "%s\n" "$hardcode_action" >&6; } if test relink = "$hardcode_action" || test yes = "$inherit_rpath"; then # Fast installation is not supported enable_fast_install=no elif test yes = "$shlibpath_overrides_runpath" || test no = "$enable_shared"; then # Fast installation is not necessary enable_fast_install=needless fi if test yes != "$enable_dlopen"; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen=load_add_on lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen=LoadLibrary lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen=dlopen lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 printf %s "checking for dlopen in -ldl... " >&6; } if test ${ac_cv_lib_dl_dlopen+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. The 'extern "C"' is for builds by C++ compilers; although this is not generally supported in C code supporting it here has little cost and some practical benefit (sr 110532). */ #ifdef __cplusplus extern "C" #endif char dlopen (void); int main (void) { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dl_dlopen=yes else case e in #( e) ac_cv_lib_dl_dlopen=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 printf "%s\n" "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl else case e in #( e) lt_cv_dlopen=dyld lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; esac fi ;; tpf*) # Don't try to run any link tests for TPF. We know it's impossible # because TPF is a cross-compiler, and we know how we open DSOs. lt_cv_dlopen=dlopen lt_cv_dlopen_libs= lt_cv_dlopen_self=no ;; *) ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" if test "x$ac_cv_func_shl_load" = xyes then : lt_cv_dlopen=shl_load else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 printf %s "checking for shl_load in -ldld... " >&6; } if test ${ac_cv_lib_dld_shl_load+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. The 'extern "C"' is for builds by C++ compilers; although this is not generally supported in C code supporting it here has little cost and some practical benefit (sr 110532). */ #ifdef __cplusplus extern "C" #endif char shl_load (void); int main (void) { return shl_load (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dld_shl_load=yes else case e in #( e) ac_cv_lib_dld_shl_load=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 printf "%s\n" "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes then : lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld else case e in #( e) ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes then : lt_cv_dlopen=dlopen else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 printf %s "checking for dlopen in -ldl... " >&6; } if test ${ac_cv_lib_dl_dlopen+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. The 'extern "C"' is for builds by C++ compilers; although this is not generally supported in C code supporting it here has little cost and some practical benefit (sr 110532). */ #ifdef __cplusplus extern "C" #endif char dlopen (void); int main (void) { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dl_dlopen=yes else case e in #( e) ac_cv_lib_dl_dlopen=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 printf "%s\n" "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 printf %s "checking for dlopen in -lsvld... " >&6; } if test ${ac_cv_lib_svld_dlopen+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. The 'extern "C"' is for builds by C++ compilers; although this is not generally supported in C code supporting it here has little cost and some practical benefit (sr 110532). */ #ifdef __cplusplus extern "C" #endif char dlopen (void); int main (void) { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_svld_dlopen=yes else case e in #( e) ac_cv_lib_svld_dlopen=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 printf "%s\n" "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 printf %s "checking for dld_link in -ldld... " >&6; } if test ${ac_cv_lib_dld_dld_link+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. The 'extern "C"' is for builds by C++ compilers; although this is not generally supported in C code supporting it here has little cost and some practical benefit (sr 110532). */ #ifdef __cplusplus extern "C" #endif char dld_link (void); int main (void) { return dld_link (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dld_dld_link=yes else case e in #( e) ac_cv_lib_dld_dld_link=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 printf "%s\n" "$ac_cv_lib_dld_dld_link" >&6; } if test "x$ac_cv_lib_dld_dld_link" = xyes then : lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld fi ;; esac fi ;; esac fi ;; esac fi ;; esac fi ;; esac fi ;; esac if test no = "$lt_cv_dlopen"; then enable_dlopen=no else enable_dlopen=yes fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS=$CPPFLAGS test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS=$LDFLAGS wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS=$LIBS LIBS="$lt_cv_dlopen_libs $LIBS" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 printf %s "checking whether a program can dlopen itself... " >&6; } if test ${lt_cv_dlopen_self+y} then : printf %s "(cached) " >&6 else case e in #( e) if test yes = "$cross_compiling"; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; esac else : # compilation failed lt_cv_dlopen_self=no fi fi rm -fr conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 printf "%s\n" "$lt_cv_dlopen_self" >&6; } if test yes = "$lt_cv_dlopen_self"; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 printf %s "checking whether a statically linked program can dlopen itself... " >&6; } if test ${lt_cv_dlopen_self_static+y} then : printf %s "(cached) " >&6 else case e in #( e) if test yes = "$cross_compiling"; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; esac else : # compilation failed lt_cv_dlopen_self_static=no fi fi rm -fr conftest* ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 printf "%s\n" "$lt_cv_dlopen_self_static" >&6; } fi CPPFLAGS=$save_CPPFLAGS LDFLAGS=$save_LDFLAGS LIBS=$save_LIBS ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi striplib= old_striplib= { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 printf %s "checking whether stripping libraries is possible... " >&6; } if test -z "$STRIP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } else if $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then old_striplib="$STRIP --strip-debug" striplib="$STRIP --strip-unneeded" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } else case $host_os in darwin*) # FIXME - insert some real tests, host_os isn't really good enough striplib="$STRIP -x" old_striplib="$STRIP -S" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } ;; freebsd*) if $STRIP -V 2>&1 | $GREP "elftoolchain" >/dev/null; then old_striplib="$STRIP --strip-debug" striplib="$STRIP --strip-unneeded" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi ;; *) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } ;; esac fi fi # Report what library types will actually be built { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 printf %s "checking if libtool supports shared libraries... " >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 printf "%s\n" "$can_build_shared" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 printf %s "checking whether to build shared libraries... " >&6; } test no = "$can_build_shared" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test yes = "$enable_shared" && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[4-9]*) if test ia64 != "$host_cpu"; then case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in yes,aix,yes) ;; # shared object as lib.so file only yes,svr4,*) ;; # shared object as lib.so archive member only yes,*) enable_static=no ;; # shared object in lib.a archive as well esac fi ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 printf "%s\n" "$enable_shared" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 printf %s "checking whether to build static libraries... " >&6; } # Make sure either enable_shared or enable_static is yes. test yes = "$enable_shared" || enable_static=yes { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 printf "%s\n" "$enable_static" >&6; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CC=$lt_save_CC ac_config_commands="$ac_config_commands libtool" # Only expand once: ### ### Version specification ### # libtool versioning - applies to libddcutil # # See http://sources.redhat.com/autobook/autobook/autobook_91.html#SEC91 for details # # increment; # CURRENT If the API or ABI interface has changed (reset REVISION to 0) # REVISION If the API and ABI remains the same, but bugs are fixed. # AGE backward compatibility (i.e. number of releases prior to current # for which this release is backward compatible) # # Alternative comments: # # Here are a set of rules to help you update your library version # information: # # 1. Start with version information of `0:0:0' for each libtool library. # 2. Update the version information only immediately before a public # release of your software. More frequent updates are unnecessary, and # only guarantee that the current interface number gets larger faster. # 3. If the library source code has changed at all since the last update, # then increment revision (`c:r:a' becomes `c:r+1:a'). # 4. If any interfaces have been added, removed, or changed since the last # update, increment current, and set revision to 0. # 5. If any interfaces have been added since the last public release, then # increment age. # 6. If any interfaces have been removed since the last public release, # then set age to 0. # # The LT_... values are used to create the argument for the --version-info parm. # Note that this parm is processed differently depending on operating system. # For Linux, the second and third fields in the shared object name's suffix are # taken directly from the command line, while the first is calculated as current-age. # For example, if LT_CURRENT=13, LT_REVISION=4, LT_AGE=4, the geneated parm # is --version-info "13:1:4", and the generated SO name looks like xxx.so.9.4.1 LT_CURRENT=7 LT_REVISION=0 LT_AGE=2 ### ### Recognize command options for configure script ### ### ### Documented options ### { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Checking configure command options... " >&5 printf "%s\n" "$as_me: Checking configure command options... " >&6;} adl_header_dir="" if test -n "$adl_header_dir" ; then HAVE_ADL_COND_TRUE= HAVE_ADL_COND_FALSE='#' else HAVE_ADL_COND_TRUE='#' HAVE_ADL_COND_FALSE= fi # Check whether --enable-lib was given. if test ${enable_lib+y} then : enableval=$enable_lib; enable_lib=${enableval} else case e in #( e) enable_lib=yes ;; esac fi if test "x$enable_lib" = "xyes" ; then ENABLE_SHARED_LIB_COND_TRUE= ENABLE_SHARED_LIB_COND_FALSE='#' else ENABLE_SHARED_LIB_COND_TRUE='#' ENABLE_SHARED_LIB_COND_FALSE= fi if test "x$enable_lib" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: lib... enabled " >&5 printf "%s\n" "$as_me: lib... enabled " >&6;} ENABLE_SHARED_LIB_FLAG=1 printf "%s\n" "#define BUILD_SHARED_LIB 1" >>confdefs.h else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: lib... disabled " >&5 printf "%s\n" "$as_me: lib... disabled " >&6;} ENABLE_SHARED_LIB_FLAG=0 ;; esac fi # Check whether --enable-install-lib-only was given. if test ${enable_install_lib_only+y} then : enableval=$enable_install_lib_only; enable_install_lib_only=${enableval} else case e in #( e) enable_install_lib_only=no ;; esac fi if test "x$enable_install_lib_only" = "xyes" ; then INSTALL_LIB_ONLY_COND_TRUE= INSTALL_LIB_ONLY_COND_FALSE='#' else INSTALL_LIB_ONLY_COND_TRUE='#' INSTALL_LIB_ONLY_COND_FALSE= fi if test "x$enable_install_lib_only" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: install_lib_only... enabled " >&5 printf "%s\n" "$as_me: install_lib_only... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: install_lib_only... disabled " >&5 printf "%s\n" "$as_me: install_lib_only... disabled " >&6;} ;; esac fi if test "x$enable_lib" = "xno" -a "x$enable_install_lib_only" = "xyes" then : as_fn_error $? "--disable-lib contradicts --enable-install-lib-only " "$LINENO" 5 fi # Check whether --enable-build-timestamp was given. if test ${enable_build_timestamp+y} then : enableval=$enable_build_timestamp; enable_build_timestamp=${enableval} else case e in #( e) enable_build_timestamp=yes ;; esac fi if test "x$enable_build_timestamp" = "xyes" ; then ENABLE_BUILD_TIMESTAMP_COND_TRUE= ENABLE_BUILD_TIMESTAMP_COND_FALSE='#' else ENABLE_BUILD_TIMESTAMP_COND_TRUE='#' ENABLE_BUILD_TIMESTAMP_COND_FALSE= fi if test "x$enable_build_timestamp" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: build-timestamp... enabled " >&5 printf "%s\n" "$as_me: build-timestamp... enabled " >&6;} ENABLE_BUILD_TIMESTAMP_FLAG=1 printf "%s\n" "#define BUILD_TIMESTAMP 1" >>confdefs.h else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: build-timestamp... disabled " >&5 printf "%s\n" "$as_me: build-timestamp... disabled " >&6;} ENABLE_BUILD_TIMESTAMP_FLAG=0 ;; esac fi # Check whether --enable-envcmds was given. if test ${enable_envcmds+y} then : enableval=$enable_envcmds; enable_envcmds=${enableval} else case e in #( e) enable_envcmds=yes ;; esac fi if test "x$enable_envcmds" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: envcmds... enabled (provisional) " >&5 printf "%s\n" "$as_me: envcmds... enabled (provisional) " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: envcmds... disabled " >&5 printf "%s\n" "$as_me: envcmds... disabled " >&6;} ;; esac fi # Check whether --enable-udev was given. if test ${enable_udev+y} then : enableval=$enable_udev; enable_udev=${enableval} else case e in #( e) enable_udev=yes ;; esac fi # Check whether --enable-usb was given. if test ${enable_usb+y} then : enableval=$enable_usb; enable_usb=${enableval} else case e in #( e) enable_usb=yes ;; esac fi if test "x$enable_usb" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: usb... enabled (provisional) " >&5 printf "%s\n" "$as_me: usb... enabled (provisional) " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: usb... disabled " >&5 printf "%s\n" "$as_me: usb... disabled " >&6;} ;; esac fi # Check whether --enable-drm was given. if test ${enable_drm+y} then : enableval=$enable_drm; enable_drm=${enableval} else case e in #( e) enable_drm=yes ;; esac fi if test "x$enable_drm" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: drm... enabled (provisional) " >&5 printf "%s\n" "$as_me: drm... enabled (provisional) " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: drm... disabled " >&5 printf "%s\n" "$as_me: drm... disabled " >&6;} ;; esac fi # Check whether --enable-x11 was given. if test ${enable_x11+y} then : enableval=$enable_x11; enable_x11=${enableval} else case e in #( e) enable_x11=yes ;; esac fi # enable_x11=no # AS_IF([test "x$enable_x11" = "xyes"], # AC_MSG_NOTICE( [x11... Deprecated option ignored] ), # AC_MSG_NOTICE( [x11... disabled] ) # ) if test "x$enable_x11" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: x11... enabled (provisional) " >&5 printf "%s\n" "$as_me: x11... enabled (provisional) " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: x11... disabled " >&5 printf "%s\n" "$as_me: x11... disabled " >&6;} ;; esac fi # Check whether --enable-static-functions-visible was given. if test ${enable_static_functions_visible+y} then : enableval=$enable_static_functions_visible; enable_static_functions_visible=${enableval} else case e in #( e) enable_static_functions_visible=no ;; esac fi if test "x$enable_static_functions_visible" = "xyes" ; then STATIC_FUNCTIONS_VISIBLE_COND_TRUE= STATIC_FUNCTIONS_VISIBLE_COND_FALSE='#' else STATIC_FUNCTIONS_VISIBLE_COND_TRUE='#' STATIC_FUNCTIONS_VISIBLE_COND_FALSE= fi if test "x$enable_static_functions_visible" = "xyes" then : printf "%s\n" "#define STATIC_FUNCTIONS_VISIBLE 1" >>confdefs.h { printf "%s\n" "$as_me:${as_lineno-$LINENO}: static_functions_visible... enabled " >&5 printf "%s\n" "$as_me: static_functions_visible... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: static_functions_visible... disabled " >&5 printf "%s\n" "$as_me: static_functions_visible... disabled " >&6;} ;; esac fi # Check whether --enable-asan was given. if test ${enable_asan+y} then : enableval=$enable_asan; enable_asan=${enableval} else case e in #( e) enable_asan=no ;; esac fi if test "x$enable_asan" = "xyes" ; then ASAN_COND_TRUE= ASAN_COND_FALSE='#' else ASAN_COND_TRUE='#' ASAN_COND_FALSE= fi if test "x$enable_asan" = "xyes" then : printf "%s\n" "#define WITH_ASAN 1" >>confdefs.h { printf "%s\n" "$as_me:${as_lineno-$LINENO}: asan... enabled " >&5 printf "%s\n" "$as_me: asan... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: asan... disabled " >&5 printf "%s\n" "$as_me: asan... disabled " >&6;} ;; esac fi # Check whether --enable-targetbsd was given. if test ${enable_targetbsd+y} then : enableval=$enable_targetbsd; enable_targetbsd=${enableval} else case e in #( e) enable_targetbsd=no ;; esac fi # Check whether --enable-doxygen was given. if test ${enable_doxygen+y} then : enableval=$enable_doxygen; enable_doxygen=${enableval} else case e in #( e) enable_doxygen=no ;; esac fi if test "x$enable_doxygen" = "xyes" ; then ENABLE_DOXYGEN_COND_TRUE= ENABLE_DOXYGEN_COND_FALSE='#' else ENABLE_DOXYGEN_COND_TRUE='#' ENABLE_DOXYGEN_COND_FALSE= fi if test "x$enable_doxygen" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: doxygen... enabled " >&5 printf "%s\n" "$as_me: doxygen... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: doxygen... disabled " >&5 printf "%s\n" "$as_me: doxygen... disabled " >&6;} ;; esac fi ### ### Resolve choices for public options ### { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Resolving options... " >&5 printf "%s\n" "$as_me: Resolving options... " >&6;} if test "x$enable_targetbsd" = "xyes" -a "x$enable_envcmds" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --enable-targetbsd forces --disable-envcmds " >&5 printf "%s\n" "$as_me: --enable-targetbsd forces --disable-envcmds " >&6;} enable_envcmds=no fi if test "x$enable_targetbsd" = "xyes" -a "x$enable_udev" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --enable-targetbsd forces --disable-udev " >&5 printf "%s\n" "$as_me: --enable-targetbsd forces --disable-udev " >&6;} enable_udev=no fi if test "x$enable_targetbsd" = "xyes" -a "x$enable_usb" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --enable-targetbsd forces --disable-usb " >&5 printf "%s\n" "$as_me: --enable-targetbsd forces --disable-usb " >&6;} enable_usb=no fi if test "x$enable_udev" != "xyes" -a "x$enable_usb" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --disable-udev forces --disable-usb " >&5 printf "%s\n" "$as_me: --disable-udev forces --disable-usb " >&6;} enable_usb=no fi # --enable-install-lib-only => --disable-envcmds if test "x$enable_install_lib_only" = "xyes" -a "x$enable_envcmds" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --enable-install-lib-only forces --disable-envcmds " >&5 printf "%s\n" "$as_me: --enable-install-lib-only forces --disable-envcmds " >&6;} enable_envcmds=no fi ### ### Report resolved options and set conditionals, substitutions, and defines ### if test "x$enable_targetbsd" = "xyes" ; then ENABLE_TARGETBSD_COND_TRUE= ENABLE_TARGETBSD_COND_FALSE='#' else ENABLE_TARGETBSD_COND_TRUE='#' ENABLE_TARGETBSD_COND_FALSE= fi if test "x$enable_targetbsd" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: targetbsd... enabled " >&5 printf "%s\n" "$as_me: targetbsd... enabled " >&6;} printf "%s\n" "#define TARGET_BSD 1" >>confdefs.h ENABLE_TARGETBSD_FLAG=1 else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: targetbsd... disabled " >&5 printf "%s\n" "$as_me: targetbsd... disabled " >&6;} ENABLE_TARGETBSD_FLAG=0 printf "%s\n" "#define TARGET_LINUX 1" >>confdefs.h ;; esac fi if test "x$enable_envcmds" = "xyes" ; then ENABLE_ENVCMDS_COND_TRUE= ENABLE_ENVCMDS_COND_FALSE='#' else ENABLE_ENVCMDS_COND_TRUE='#' ENABLE_ENVCMDS_COND_FALSE= fi if test "x$enable_envcmds" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: envcmds... enabled " >&5 printf "%s\n" "$as_me: envcmds... enabled " >&6;} printf "%s\n" "#define ENABLE_ENVCMDS 1" >>confdefs.h ENABLE_ENVCMDS_FLAG=1 else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: envcmds... disabled " >&5 printf "%s\n" "$as_me: envcmds... disabled " >&6;} ENABLE_ENVCMDS_FLAG=0 ;; esac fi if test "x$enable_udev" = "xyes" ; then ENABLE_UDEV_COND_TRUE= ENABLE_UDEV_COND_FALSE='#' else ENABLE_UDEV_COND_TRUE='#' ENABLE_UDEV_COND_FALSE= fi if test "x$enable_udev" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: udev... enabled " >&5 printf "%s\n" "$as_me: udev... enabled " >&6;} printf "%s\n" "#define ENABLE_UDEV 1" >>confdefs.h ENABLE_UDEV_FLAG=1 else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: udev... disabled " >&5 printf "%s\n" "$as_me: udev... disabled " >&6;} ENABLE_UDEV_FLAG=0 ;; esac fi if test "x$enable_usb" = "xyes" ; then ENABLE_USB_COND_TRUE= ENABLE_USB_COND_FALSE='#' else ENABLE_USB_COND_TRUE='#' ENABLE_USB_COND_FALSE= fi if test "x$enable_usb" = "xyes" then : printf "%s\n" "#define ENABLE_USB 1" >>confdefs.h ENABLE_USB_FLAG=1 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: usb... enabled " >&5 printf "%s\n" "$as_me: usb... enabled " >&6;} else case e in #( e) ENABLE_USB_FLAG=0 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: usb... disabled " >&5 printf "%s\n" "$as_me: usb... disabled " >&6;} ;; esac fi if test "x$enable_x11" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: x11... enabled " >&5 printf "%s\n" "$as_me: x11... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: x11... disabled " >&5 printf "%s\n" "$as_me: x11... disabled " >&6;} ;; esac fi ### Private options # Check whether --enable-testcases was given. if test ${enable_testcases+y} then : enableval=$enable_testcases; include_testcases=${enableval} else case e in #( e) include_testcases=no ;; esac fi if test "x$include_testcases" = "xyes" ; then INCLUDE_TESTCASES_COND_TRUE= INCLUDE_TESTCASES_COND_FALSE='#' else INCLUDE_TESTCASES_COND_TRUE='#' INCLUDE_TESTCASES_COND_FALSE= fi if test "x$include_testcases" = "xyes" then : printf "%s\n" "#define INCLUDE_TESTCASES 1" >>confdefs.h { printf "%s\n" "$as_me:${as_lineno-$LINENO}: testcases... enabled " >&5 printf "%s\n" "$as_me: testcases... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: testcases... disabled " >&5 printf "%s\n" "$as_me: testcases... disabled " >&6;} ;; esac fi # Check whether --enable-callgraph was given. if test ${enable_callgraph+y} then : enableval=$enable_callgraph; enable_callgraph=${enableval} else case e in #( e) enable_callgraph=no ;; esac fi if test "x$enable_callgraph" = "xyes" ; then ENABLE_CALLGRAPH_COND_TRUE= ENABLE_CALLGRAPH_COND_FALSE='#' else ENABLE_CALLGRAPH_COND_TRUE='#' ENABLE_CALLGRAPH_COND_FALSE= fi if test "x$enable_callgraph" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: callgraph... enabled " >&5 printf "%s\n" "$as_me: callgraph... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: callgraph... disabled " >&5 printf "%s\n" "$as_me: callgraph... disabled " >&6;} ;; esac fi # Check whether --enable-failsim was given. if test ${enable_failsim+y} then : enableval=$enable_failsim; enable_failsim=${enableval} else case e in #( e) enable_failsim=no ;; esac fi if test "x$enable_failsim" = "xyes" ; then ENABLE_FAILSIM_COND_TRUE= ENABLE_FAILSIM_COND_FALSE='#' else ENABLE_FAILSIM_COND_TRUE='#' ENABLE_FAILSIM_COND_FALSE= fi if test "x$enable_failsim" = "xyes" then : printf "%s\n" "#define ENABLE_FAILSIM 1" >>confdefs.h { printf "%s\n" "$as_me:${as_lineno-$LINENO}: failsim..... enabled " >&5 printf "%s\n" "$as_me: failsim..... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: failsim..... disabled " >&5 printf "%s\n" "$as_me: failsim..... disabled " >&6;} ;; esac fi # Check whether --enable-force-suse was given. if test ${enable_force_suse+y} then : enableval=$enable_force_suse; enable_force_suse=${enableval} else case e in #( e) enable_force_suse=no ;; esac fi if test "x$enable_force_suse" = "xyes" ; then ENABLE_FORCE_SUSE_COND_TRUE= ENABLE_FORCE_SUSE_COND_FALSE='#' else ENABLE_FORCE_SUSE_COND_TRUE='#' ENABLE_FORCE_SUSE_COND_FALSE= fi if test "x$enable_force_suse" = "xyes" then : printf "%s\n" "#define ENABLE_FORCE_SUSE 1" >>confdefs.h { printf "%s\n" "$as_me:${as_lineno-$LINENO}: force-suse....enabled " >&5 printf "%s\n" "$as_me: force-suse....enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: force-suse....disabled " >&5 printf "%s\n" "$as_me: force-suse....disabled " >&6;} ;; esac fi ### ### Checks for typedefs, structures, and compiler characteristics. ### ac_fn_c_check_type "$LINENO" "_Bool" "ac_cv_type__Bool" "$ac_includes_default" if test "x$ac_cv_type__Bool" = xyes then : printf "%s\n" "#define HAVE__BOOL 1" >>confdefs.h fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for stdbool.h that conforms to C99 or later" >&5 printf %s "checking for stdbool.h that conforms to C99 or later... " >&6; } if test ${ac_cv_header_stdbool_h+y} then : printf %s "(cached) " >&6 else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include /* "true" and "false" should be usable in #if expressions and integer constant expressions, and "bool" should be a valid type name. Although C99 requires bool, true, and false to be macros, C23 and C++11 overrule that, so do not test for that. Although C99 requires __bool_true_false_are_defined and _Bool, C23 says they are obsolescent, so do not require them. */ #if !true #error "'true' is not true" #endif #if true != 1 #error "'true' is not equal to 1" #endif char b[true == 1 ? 1 : -1]; char c[true]; #if false #error "'false' is not false" #endif #if false != 0 #error "'false' is not equal to 0" #endif char d[false == 0 ? 1 : -1]; enum { e = false, f = true, g = false * true, h = true * 256 }; char i[(bool) 0.5 == true ? 1 : -1]; char j[(bool) 0.0 == false ? 1 : -1]; char k[sizeof (bool) > 0 ? 1 : -1]; struct sb { bool s: 1; bool t; } s; char l[sizeof s.t > 0 ? 1 : -1]; /* The following fails for HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]. */ bool m[h]; char n[sizeof m == h * sizeof m[0] ? 1 : -1]; char o[-1 - (bool) 0 < 0 ? 1 : -1]; /* Catch a bug in an HP-UX C compiler. See https://gcc.gnu.org/ml/gcc-patches/2003-12/msg02303.html https://lists.gnu.org/r/bug-coreutils/2005-11/msg00161.html */ bool p = true; bool *pp = &p; int main (void) { bool ps = &s; *pp |= p; *pp |= ! p; /* Refer to every declared value, so they cannot be discarded as unused. */ return (!b + !c + !d + !e + !f + !g + !h + !i + !j + !k + !l + !m + !n + !o + !p + !pp + !ps); ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_header_stdbool_h=yes else case e in #( e) ac_cv_header_stdbool_h=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdbool_h" >&5 printf "%s\n" "$ac_cv_header_stdbool_h" >&6; } { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for inline" >&5 printf %s "checking for inline... " >&6; } if test ${ac_cv_c_inline+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_c_inline=no for ac_kw in inline __inline__ __inline; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifndef __cplusplus typedef int foo_t; static $ac_kw foo_t static_foo (void) {return 0; } $ac_kw foo_t foo (void) {return 0; } #endif _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_c_inline=$ac_kw fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext test "$ac_cv_c_inline" != no && break done ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5 printf "%s\n" "$ac_cv_c_inline" >&6; } case $ac_cv_c_inline in inline | yes) ;; *) case $ac_cv_c_inline in no) ac_val=;; *) ac_val=$ac_cv_c_inline;; esac cat >>confdefs.h <<_ACEOF #ifndef __cplusplus #define inline $ac_val #endif _ACEOF ;; esac { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 printf %s "checking whether byte ordering is bigendian... " >&6; } if test ${ac_cv_c_bigendian+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_c_bigendian=unknown # See if we're dealing with a universal compiler. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifndef __APPLE_CC__ not a universal capable compiler #endif typedef int dummy; _ACEOF if ac_fn_c_try_compile "$LINENO" then : # Check for potential -arch flags. It is not universal unless # there are at least two -arch flags with different values. ac_arch= ac_prev= for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do if test -n "$ac_prev"; then case $ac_word in i?86 | x86_64 | ppc | ppc64) if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then ac_arch=$ac_word else ac_cv_c_bigendian=universal break fi ;; esac ac_prev= elif test "x$ac_word" = "x-arch"; then ac_prev=arch fi done fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext if test $ac_cv_c_bigendian = unknown; then # See if sys/param.h defines the BYTE_ORDER macro. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main (void) { #if ! (defined BYTE_ORDER && defined BIG_ENDIAN \\ && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \\ && LITTLE_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : # It does; now see whether it defined to BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main (void) { #if BYTE_ORDER != BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_c_bigendian=yes else case e in #( e) ac_cv_c_bigendian=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main (void) { #if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : # It does; now see whether it defined to _BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main (void) { #ifndef _BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_c_bigendian=yes else case e in #( e) ac_cv_c_bigendian=no ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # Compile a test program. if test "$cross_compiling" = yes then : # Try to guess by grepping values from an object file. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ unsigned short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; unsigned short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; int use_ascii (int i) { return ascii_mm[i] + ascii_ii[i]; } unsigned short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; unsigned short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; int use_ebcdic (int i) { return ebcdic_mm[i] + ebcdic_ii[i]; } int main (int argc, char **argv) { /* Intimidate the compiler so that it does not optimize the arrays away. */ char *p = argv[0]; ascii_mm[1] = *p++; ebcdic_mm[1] = *p++; ascii_ii[1] = *p++; ebcdic_ii[1] = *p++; return use_ascii (argc) == use_ebcdic (*p); } _ACEOF if ac_fn_c_try_link "$LINENO" then : if grep BIGenDianSyS conftest$ac_exeext >/dev/null; then ac_cv_c_bigendian=yes fi if grep LiTTleEnDian conftest$ac_exeext >/dev/null ; then if test "$ac_cv_c_bigendian" = unknown; then ac_cv_c_bigendian=no else # finding both strings is unlikely to happen, but who knows? ac_cv_c_bigendian=unknown fi fi fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main (void) { /* Are we little or big endian? From Harbison&Steele. */ union { long int l; char c[sizeof (long int)]; } u; u.l = 1; return u.c[sizeof (long int) - 1] == 1; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO" then : ac_cv_c_bigendian=no else case e in #( e) ac_cv_c_bigendian=yes ;; esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 printf "%s\n" "$ac_cv_c_bigendian" >&6; } case $ac_cv_c_bigendian in #( yes) printf "%s\n" "#define WORDS_BIGENDIAN 1" >>confdefs.h ;; #( no) ;; #( universal) printf "%s\n" "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h ;; #( *) as_fn_error $? "unknown endianness presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; esac ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" if test "x$ac_cv_type_size_t" = xyes then : else case e in #( e) printf "%s\n" "#define size_t unsigned int" >>confdefs.h ;; esac fi ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" if test "x$ac_cv_type_ssize_t" = xyes then : else case e in #( e) printf "%s\n" "#define ssize_t int" >>confdefs.h ;; esac fi ac_fn_c_find_uintX_t "$LINENO" "16" "ac_cv_c_uint16_t" case $ac_cv_c_uint16_t in #( no|yes) ;; #( *) printf "%s\n" "#define uint16_t $ac_cv_c_uint16_t" >>confdefs.h ;; esac ac_fn_c_find_uintX_t "$LINENO" "32" "ac_cv_c_uint32_t" case $ac_cv_c_uint32_t in #( no|yes) ;; #( *) printf "%s\n" "#define _UINT32_T 1" >>confdefs.h printf "%s\n" "#define uint32_t $ac_cv_c_uint32_t" >>confdefs.h ;; esac ac_fn_c_find_uintX_t "$LINENO" "8" "ac_cv_c_uint8_t" case $ac_cv_c_uint8_t in #( no|yes) ;; #( *) printf "%s\n" "#define _UINT8_T 1" >>confdefs.h printf "%s\n" "#define uint8_t $ac_cv_c_uint8_t" >>confdefs.h ;; esac ### ### Checks for standard library functions. ### { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 printf %s "checking for GNU libc compatible malloc... " >&6; } if test ${ac_cv_func_malloc_0_nonnull+y} then : printf %s "(cached) " >&6 else case e in #( e) if test "$cross_compiling" = yes then : case "$host_os" in # (( # Guess yes on platforms where we know the result. *-gnu* | freebsd* | netbsd* | openbsd* | bitrig* \ | hpux* | solaris* | cygwin* | mingw* | windows* | msys* ) ac_cv_func_malloc_0_nonnull=yes ;; # If we don't know, assume the worst. *) ac_cv_func_malloc_0_nonnull=no ;; esac else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main (void) { void *p = malloc (0); int result = !p; free (p); return result; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO" then : ac_cv_func_malloc_0_nonnull=yes else case e in #( e) ac_cv_func_malloc_0_nonnull=no ;; esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 printf "%s\n" "$ac_cv_func_malloc_0_nonnull" >&6; } if test $ac_cv_func_malloc_0_nonnull = yes then : printf "%s\n" "#define HAVE_MALLOC 1" >>confdefs.h else case e in #( e) printf "%s\n" "#define HAVE_MALLOC 0" >>confdefs.h case " $LIBOBJS " in *" malloc.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS malloc.$ac_objext" ;; esac printf "%s\n" "#define malloc rpl_malloc" >>confdefs.h ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible realloc" >&5 printf %s "checking for GNU libc compatible realloc... " >&6; } if test ${ac_cv_func_realloc_0_nonnull+y} then : printf %s "(cached) " >&6 else case e in #( e) if test "$cross_compiling" = yes then : case "$host_os" in # (( # Guess yes on platforms where we know the result. *-gnu* | freebsd* | netbsd* | openbsd* | bitrig* \ | hpux* | solaris* | cygwin* | mingw* | windows* | msys* ) ac_cv_func_realloc_0_nonnull=yes ;; # If we don't know, assume the worst. *) ac_cv_func_realloc_0_nonnull=no ;; esac else case e in #( e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main (void) { void *p = realloc (0, 0); int result = !p; free (p); return result; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO" then : ac_cv_func_realloc_0_nonnull=yes else case e in #( e) ac_cv_func_realloc_0_nonnull=no ;; esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_realloc_0_nonnull" >&5 printf "%s\n" "$ac_cv_func_realloc_0_nonnull" >&6; } if test $ac_cv_func_realloc_0_nonnull = yes then : printf "%s\n" "#define HAVE_REALLOC 1" >>confdefs.h else case e in #( e) printf "%s\n" "#define HAVE_REALLOC 0" >>confdefs.h case " $LIBOBJS " in *" realloc.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS realloc.$ac_objext" ;; esac printf "%s\n" "#define realloc rpl_realloc" >>confdefs.h ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC options needed to detect all undeclared functions" >&5 printf %s "checking for $CC options needed to detect all undeclared functions... " >&6; } if test ${ac_cv_c_undeclared_builtin_options+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_save_CFLAGS=$CFLAGS ac_cv_c_undeclared_builtin_options='cannot detect' for ac_arg in '' -fno-builtin; do CFLAGS="$ac_save_CFLAGS $ac_arg" # This test program should *not* compile successfully. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main (void) { (void) strchr; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : else case e in #( e) # This test program should compile successfully. # No library function is consistently available on # freestanding implementations, so test against a dummy # declaration. Include always-available headers on the # off chance that they somehow elicit warnings. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include extern void ac_decl (int, char *); int main (void) { (void) ac_decl (0, (char *) 0); (void) ac_decl; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : if test x"$ac_arg" = x then : ac_cv_c_undeclared_builtin_options='none needed' else case e in #( e) ac_cv_c_undeclared_builtin_options=$ac_arg ;; esac fi break fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext done CFLAGS=$ac_save_CFLAGS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_undeclared_builtin_options" >&5 printf "%s\n" "$ac_cv_c_undeclared_builtin_options" >&6; } case $ac_cv_c_undeclared_builtin_options in #( 'cannot detect') : { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "cannot make $CC report undeclared builtins See 'config.log' for more details" "$LINENO" 5; } ;; #( 'none needed') : ac_c_undeclared_builtin_options='' ;; #( *) : ac_c_undeclared_builtin_options=$ac_cv_c_undeclared_builtin_options ;; esac ac_fn_check_decl "$LINENO" "strerror_r" "ac_cv_have_decl_strerror_r" "$ac_includes_default" "$ac_c_undeclared_builtin_options" "CFLAGS" if test "x$ac_cv_have_decl_strerror_r" = xyes then : ac_have_decl=1 else case e in #( e) ac_have_decl=0 ;; esac fi printf "%s\n" "#define HAVE_DECL_STRERROR_R $ac_have_decl" >>confdefs.h if test $ac_cv_have_decl_strerror_r = yes; then # For backward compatibility's sake, define HAVE_STRERROR_R. # (We used to run AC_CHECK_FUNCS_ONCE for strerror_r, as well # as AC_CHECK_DECLS_ONCE.) printf "%s\n" "#define HAVE_STRERROR_R 1" >>confdefs.h fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether strerror_r returns char *" >&5 printf %s "checking whether strerror_r returns char *... " >&6; } if test ${ac_cv_func_strerror_r_char_p+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_cv_func_strerror_r_char_p=no if test $ac_cv_have_decl_strerror_r = yes; then cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main (void) { char buf[100]; char x = *strerror_r (0, buf, sizeof buf); char *p = strerror_r (0, buf, sizeof buf); return !p || x; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_func_strerror_r_char_p=yes fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strerror_r_char_p" >&5 printf "%s\n" "$ac_cv_func_strerror_r_char_p" >&6; } if test $ac_cv_func_strerror_r_char_p = yes; then printf "%s\n" "#define STRERROR_R_CHAR_P 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "clock_gettime" "ac_cv_func_clock_gettime" if test "x$ac_cv_func_clock_gettime" = xyes then : printf "%s\n" "#define HAVE_CLOCK_GETTIME 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "memset" "ac_cv_func_memset" if test "x$ac_cv_func_memset" = xyes then : printf "%s\n" "#define HAVE_MEMSET 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "nl_langinfo" "ac_cv_func_nl_langinfo" if test "x$ac_cv_func_nl_langinfo" = xyes then : printf "%s\n" "#define HAVE_NL_LANGINFO 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "stpcpy" "ac_cv_func_stpcpy" if test "x$ac_cv_func_stpcpy" = xyes then : printf "%s\n" "#define HAVE_STPCPY 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "strchr" "ac_cv_func_strchr" if test "x$ac_cv_func_strchr" = xyes then : printf "%s\n" "#define HAVE_STRCHR 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "strdup" "ac_cv_func_strdup" if test "x$ac_cv_func_strdup" = xyes then : printf "%s\n" "#define HAVE_STRDUP 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "strerror" "ac_cv_func_strerror" if test "x$ac_cv_func_strerror" = xyes then : printf "%s\n" "#define HAVE_STRERROR 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "strrchr" "ac_cv_func_strrchr" if test "x$ac_cv_func_strrchr" = xyes then : printf "%s\n" "#define HAVE_STRRCHR 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "strtol" "ac_cv_func_strtol" if test "x$ac_cv_func_strtol" = xyes then : printf "%s\n" "#define HAVE_STRTOL 1" >>confdefs.h fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for library containing dlopen" >&5 printf %s "checking for library containing dlopen... " >&6; } if test ${ac_cv_search_dlopen+y} then : printf %s "(cached) " >&6 else case e in #( e) ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. The 'extern "C"' is for builds by C++ compilers; although this is not generally supported in C code supporting it here has little cost and some practical benefit (sr 110532). */ #ifdef __cplusplus extern "C" #endif char dlopen (void); int main (void) { return dlopen (); ; return 0; } _ACEOF for ac_lib in '' dl dld do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO" then : ac_cv_search_dlopen=$ac_res fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext if test ${ac_cv_search_dlopen+y} then : break fi done if test ${ac_cv_search_dlopen+y} then : else case e in #( e) ac_cv_search_dlopen=no ;; esac fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_dlopen" >&5 printf "%s\n" "$ac_cv_search_dlopen" >&6; } ac_res=$ac_cv_search_dlopen if test "$ac_res" != no then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" else case e in #( e) as_fn_error $? "unable to find the dlopen() function" "$LINENO" 5 ;; esac fi ### ### Checks for header files. ### ac_fn_c_check_header_compile "$LINENO" "fcntl.h" "ac_cv_header_fcntl_h" "$ac_includes_default" if test "x$ac_cv_header_fcntl_h" = xyes then : printf "%s\n" "#define HAVE_FCNTL_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "langinfo.h" "ac_cv_header_langinfo_h" "$ac_includes_default" if test "x$ac_cv_header_langinfo_h" = xyes then : printf "%s\n" "#define HAVE_LANGINFO_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "libintl.h" "ac_cv_header_libintl_h" "$ac_includes_default" if test "x$ac_cv_header_libintl_h" = xyes then : printf "%s\n" "#define HAVE_LIBINTL_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "limits.h" "ac_cv_header_limits_h" "$ac_includes_default" if test "x$ac_cv_header_limits_h" = xyes then : printf "%s\n" "#define HAVE_LIMITS_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "stdint.h" "ac_cv_header_stdint_h" "$ac_includes_default" if test "x$ac_cv_header_stdint_h" = xyes then : printf "%s\n" "#define HAVE_STDINT_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" if test "x$ac_cv_header_stdlib_h" = xyes then : printf "%s\n" "#define HAVE_STDLIB_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "string.h" "ac_cv_header_string_h" "$ac_includes_default" if test "x$ac_cv_header_string_h" = xyes then : printf "%s\n" "#define HAVE_STRING_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "sys/ioctl.h" "ac_cv_header_sys_ioctl_h" "$ac_includes_default" if test "x$ac_cv_header_sys_ioctl_h" = xyes then : printf "%s\n" "#define HAVE_SYS_IOCTL_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "termios.h" "ac_cv_header_termios_h" "$ac_includes_default" if test "x$ac_cv_header_termios_h" = xyes then : printf "%s\n" "#define HAVE_TERMIOS_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "unistd.h" "ac_cv_header_unistd_h" "$ac_includes_default" if test "x$ac_cv_header_unistd_h" = xyes then : printf "%s\n" "#define HAVE_UNISTD_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "wchar.h" "ac_cv_header_wchar_h" "$ac_includes_default" if test "x$ac_cv_header_wchar_h" = xyes then : printf "%s\n" "#define HAVE_WCHAR_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default" if test "x$ac_cv_header_dlfcn_h" = xyes then : printf "%s\n" "#define HAVE_DLFCN_H 1" >>confdefs.h fi ac_fn_c_check_header_compile "$LINENO" "execinfo.h" "ac_cv_header_execinfo_h" "$ac_includes_default" if test "x$ac_cv_header_execinfo_h" = xyes then : printf "%s\n" "#define HAVE_EXECINFO_H 1" >>confdefs.h fi ### ### Required library tests ### pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for glib-2.0 >= 2.40" >&5 printf %s "checking for glib-2.0 >= 2.40... " >&6; } if test -n "$GLIB_CFLAGS"; then pkg_cv_GLIB_CFLAGS="$GLIB_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"glib-2.0 >= 2.40\""; } >&5 ($PKG_CONFIG --exists --print-errors "glib-2.0 >= 2.40") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_GLIB_CFLAGS=`$PKG_CONFIG --cflags "glib-2.0 >= 2.40" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$GLIB_LIBS"; then pkg_cv_GLIB_LIBS="$GLIB_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"glib-2.0 >= 2.40\""; } >&5 ($PKG_CONFIG --exists --print-errors "glib-2.0 >= 2.40") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_GLIB_LIBS=`$PKG_CONFIG --libs "glib-2.0 >= 2.40" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then GLIB_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "glib-2.0 >= 2.40" 2>&1` else GLIB_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "glib-2.0 >= 2.40" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$GLIB_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (glib-2.0 >= 2.40) were not met: $GLIB_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables GLIB_CFLAGS and GLIB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables GLIB_CFLAGS and GLIB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See 'config.log' for more details" "$LINENO" 5; } else GLIB_CFLAGS=$pkg_cv_GLIB_CFLAGS GLIB_LIBS=$pkg_cv_GLIB_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } fi required_packages="$required_packages glib-2.0 >= 2.40" pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for jansson >= 2.0" >&5 printf %s "checking for jansson >= 2.0... " >&6; } if test -n "$JANSSON_CFLAGS"; then pkg_cv_JANSSON_CFLAGS="$JANSSON_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"jansson >= 2.0\""; } >&5 ($PKG_CONFIG --exists --print-errors "jansson >= 2.0") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JANSSON_CFLAGS=`$PKG_CONFIG --cflags "jansson >= 2.0" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$JANSSON_LIBS"; then pkg_cv_JANSSON_LIBS="$JANSSON_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"jansson >= 2.0\""; } >&5 ($PKG_CONFIG --exists --print-errors "jansson >= 2.0") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_JANSSON_LIBS=`$PKG_CONFIG --libs "jansson >= 2.0" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then JANSSON_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "jansson >= 2.0" 2>&1` else JANSSON_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "jansson >= 2.0" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$JANSSON_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (jansson >= 2.0) were not met: $JANSSON_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables JANSSON_CFLAGS and JANSSON_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables JANSSON_CFLAGS and JANSSON_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See 'config.log' for more details" "$LINENO" 5; } else JANSSON_CFLAGS=$pkg_cv_JANSSON_CFLAGS JANSSON_LIBS=$pkg_cv_JANSSON_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } fi required_packages="$required_packages jansson >= 2.0" if test "x$enable_udev" = "xyes" then : pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libudev" >&5 printf %s "checking for libudev... " >&6; } if test -n "$UDEV_CFLAGS"; then pkg_cv_UDEV_CFLAGS="$UDEV_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libudev\""; } >&5 ($PKG_CONFIG --exists --print-errors "libudev") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_UDEV_CFLAGS=`$PKG_CONFIG --cflags "libudev" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$UDEV_LIBS"; then pkg_cv_UDEV_LIBS="$UDEV_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libudev\""; } >&5 ($PKG_CONFIG --exists --print-errors "libudev") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_UDEV_LIBS=`$PKG_CONFIG --libs "libudev" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then UDEV_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libudev" 2>&1` else UDEV_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libudev" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$UDEV_PKG_ERRORS" >&5 libudev_found=0 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: The package providing libudev.h varies by Linux distribution and release. " >&5 printf "%s\n" "$as_me: The package providing libudev.h varies by Linux distribution and release. " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: It may be a udev specific package, e.g. libudev-dev, libudev-devel " >&5 printf "%s\n" "$as_me: It may be a udev specific package, e.g. libudev-dev, libudev-devel " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: or it may be part of systemd, e.g systemd-devel " >&5 printf "%s\n" "$as_me: or it may be part of systemd, e.g systemd-devel " >&6;} as_fn_error $? "libudev not found " "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } libudev_found=0 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: The package providing libudev.h varies by Linux distribution and release. " >&5 printf "%s\n" "$as_me: The package providing libudev.h varies by Linux distribution and release. " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: It may be a udev specific package, e.g. libudev-dev, libudev-devel " >&5 printf "%s\n" "$as_me: It may be a udev specific package, e.g. libudev-dev, libudev-devel " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: or it may be part of systemd, e.g systemd-devel " >&5 printf "%s\n" "$as_me: or it may be part of systemd, e.g systemd-devel " >&6;} as_fn_error $? "libudev not found " "$LINENO" 5 else UDEV_CFLAGS=$pkg_cv_UDEV_CFLAGS UDEV_LIBS=$pkg_cv_UDEV_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } libudev_found=1 fi fi ### ### Optional library tests ### ### libusb if test "x$enable_usb" = "xyes" then : pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libusb-1.0 >= 1.0.15" >&5 printf %s "checking for libusb-1.0 >= 1.0.15... " >&6; } if test -n "$LIBUSB_CFLAGS"; then pkg_cv_LIBUSB_CFLAGS="$LIBUSB_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libusb-1.0 >= 1.0.15\""; } >&5 ($PKG_CONFIG --exists --print-errors "libusb-1.0 >= 1.0.15") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_LIBUSB_CFLAGS=`$PKG_CONFIG --cflags "libusb-1.0 >= 1.0.15" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$LIBUSB_LIBS"; then pkg_cv_LIBUSB_LIBS="$LIBUSB_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libusb-1.0 >= 1.0.15\""; } >&5 ($PKG_CONFIG --exists --print-errors "libusb-1.0 >= 1.0.15") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_LIBUSB_LIBS=`$PKG_CONFIG --libs "libusb-1.0 >= 1.0.15" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then LIBUSB_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libusb-1.0 >= 1.0.15" 2>&1` else LIBUSB_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libusb-1.0 >= 1.0.15" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$LIBUSB_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (libusb-1.0 >= 1.0.15) were not met: $LIBUSB_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables LIBUSB_CFLAGS and LIBUSB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables LIBUSB_CFLAGS and LIBUSB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See 'config.log' for more details" "$LINENO" 5; } else LIBUSB_CFLAGS=$pkg_cv_LIBUSB_CFLAGS LIBUSB_LIBS=$pkg_cv_LIBUSB_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } libusb_found=yes fi else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: usb disabled, not checking for libusb " >&5 printf "%s\n" "$as_me: usb disabled, not checking for libusb " >&6;} ;; esac fi if test 0$DBG -ne 0 then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBUSB_CFLAGS: $LIBUSB_CFLAGS " >&5 printf "%s\n" "$as_me: LIBUSB_CFLAGS: $LIBUSB_CFLAGS " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBUSB_LIBS: $LIBUSB_LIBS " >&5 printf "%s\n" "$as_me: LIBUSB_LIBS: $LIBUSB_LIBS " >&6;} fi ### libdrm if test "x$enable_drm" = "xyes" then : pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for libdrm >= 2.4.67" >&5 printf %s "checking for libdrm >= 2.4.67... " >&6; } if test -n "$LIBDRM_CFLAGS"; then pkg_cv_LIBDRM_CFLAGS="$LIBDRM_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libdrm >= 2.4.67\""; } >&5 ($PKG_CONFIG --exists --print-errors "libdrm >= 2.4.67") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_LIBDRM_CFLAGS=`$PKG_CONFIG --cflags "libdrm >= 2.4.67" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$LIBDRM_LIBS"; then pkg_cv_LIBDRM_LIBS="$LIBDRM_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libdrm >= 2.4.67\""; } >&5 ($PKG_CONFIG --exists --print-errors "libdrm >= 2.4.67") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_LIBDRM_LIBS=`$PKG_CONFIG --libs "libdrm >= 2.4.67" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then LIBDRM_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libdrm >= 2.4.67" 2>&1` else LIBDRM_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libdrm >= 2.4.67" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$LIBDRM_PKG_ERRORS" >&5 libdrm_found=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: libdrm >= 2.4.67 not found. Forcing --disable-drm" >&5 printf "%s\n" "$as_me: WARNING: libdrm >= 2.4.67 not found. Forcing --disable-drm" >&2;} enable_drm=no elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } libdrm_found=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: libdrm >= 2.4.67 not found. Forcing --disable-drm" >&5 printf "%s\n" "$as_me: WARNING: libdrm >= 2.4.67 not found. Forcing --disable-drm" >&2;} enable_drm=no else LIBDRM_CFLAGS=$pkg_cv_LIBDRM_CFLAGS LIBDRM_LIBS=$pkg_cv_LIBDRM_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } libdrm_found=yes fi else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: drm disabled, not checking for libdrm " >&5 printf "%s\n" "$as_me: drm disabled, not checking for libdrm " >&6;} ;; esac fi if test "x$enable_drm" = "xyes" ; then USE_LIBDRM_COND_TRUE= USE_LIBDRM_COND_FALSE='#' else USE_LIBDRM_COND_TRUE='#' USE_LIBDRM_COND_FALSE= fi if test "x$enable_drm" = "xyes" then : printf "%s\n" "#define USE_LIBDRM 1" >>confdefs.h { printf "%s\n" "$as_me:${as_lineno-$LINENO}: drm... enabled " >&5 printf "%s\n" "$as_me: drm... enabled " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: drm... disabled " >&5 printf "%s\n" "$as_me: drm... disabled " >&6;} ;; esac fi if test 0$DBG -ne 0 then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBDRM_CFLAGS: $LIBDRM_CFLAGS " >&5 printf "%s\n" "$as_me: LIBDRM_CFLAGS: $LIBDRM_CFLAGS " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBDRM_LIBS: $LIBDRM_LIBS " >&5 printf "%s\n" "$as_me: LIBDRM_LIBS: $LIBDRM_LIBS " >&6;} fi ### X11 if test "x$enable_x11" = "xyes" then : pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for x11" >&5 printf %s "checking for x11... " >&6; } if test -n "$LIBX11_CFLAGS"; then pkg_cv_LIBX11_CFLAGS="$LIBX11_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"x11\""; } >&5 ($PKG_CONFIG --exists --print-errors "x11") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_LIBX11_CFLAGS=`$PKG_CONFIG --cflags "x11" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$LIBX11_LIBS"; then pkg_cv_LIBX11_LIBS="$LIBX11_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"x11\""; } >&5 ($PKG_CONFIG --exists --print-errors "x11") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_LIBX11_LIBS=`$PKG_CONFIG --libs "x11" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then LIBX11_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "x11" 2>&1` else LIBX11_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "x11" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$LIBX11_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (x11) were not met: $LIBX11_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables LIBX11_CFLAGS and LIBX11_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables LIBX11_CFLAGS and LIBX11_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See 'config.log' for more details" "$LINENO" 5; } else LIBX11_CFLAGS=$pkg_cv_LIBX11_CFLAGS LIBX11_LIBS=$pkg_cv_LIBX11_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } fi pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for xrandr" >&5 printf %s "checking for xrandr... " >&6; } if test -n "$XRANDR_CFLAGS"; then pkg_cv_XRANDR_CFLAGS="$XRANDR_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"xrandr\""; } >&5 ($PKG_CONFIG --exists --print-errors "xrandr") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_XRANDR_CFLAGS=`$PKG_CONFIG --cflags "xrandr" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$XRANDR_LIBS"; then pkg_cv_XRANDR_LIBS="$XRANDR_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"xrandr\""; } >&5 ($PKG_CONFIG --exists --print-errors "xrandr") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_XRANDR_LIBS=`$PKG_CONFIG --libs "xrandr" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then XRANDR_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "xrandr" 2>&1` else XRANDR_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "xrandr" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$XRANDR_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (xrandr) were not met: $XRANDR_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables XRANDR_CFLAGS and XRANDR_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables XRANDR_CFLAGS and XRANDR_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See 'config.log' for more details" "$LINENO" 5; } else XRANDR_CFLAGS=$pkg_cv_XRANDR_CFLAGS XRANDR_LIBS=$pkg_cv_XRANDR_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } fi pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for xext" >&5 printf %s "checking for xext... " >&6; } if test -n "$XEXT_CFLAGS"; then pkg_cv_XEXT_CFLAGS="$XEXT_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"xext\""; } >&5 ($PKG_CONFIG --exists --print-errors "xext") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_XEXT_CFLAGS=`$PKG_CONFIG --cflags "xext" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$XEXT_LIBS"; then pkg_cv_XEXT_LIBS="$XEXT_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"xext\""; } >&5 ($PKG_CONFIG --exists --print-errors "xext") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_XEXT_LIBS=`$PKG_CONFIG --libs "xext" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then XEXT_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "xext" 2>&1` else XEXT_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "xext" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$XEXT_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (xext) were not met: $XEXT_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables XEXT_CFLAGS and XEXT_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables XEXT_CFLAGS and XEXT_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See 'config.log' for more details" "$LINENO" 5; } else XEXT_CFLAGS=$pkg_cv_XEXT_CFLAGS XEXT_LIBS=$pkg_cv_XEXT_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } fi fi if test "x$enable_x11" = "xyes" ; then USE_X11_COND_TRUE= USE_X11_COND_FALSE='#' else USE_X11_COND_TRUE='#' USE_X11_COND_FALSE= fi if test "x$enable_x11" = "xyes" then : printf "%s\n" "#define USE_X11 1" >>confdefs.h { printf "%s\n" "$as_me:${as_lineno-$LINENO}: x11... enabled1 " >&5 printf "%s\n" "$as_me: x11... enabled1 " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: x11... disabled1 " >&5 printf "%s\n" "$as_me: x11... disabled1 " >&6;} ;; esac fi if test 0$DBG -ne 0 then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBX11_CFLAGS: $LIBX11_CFLAGS " >&5 printf "%s\n" "$as_me: LIBX11_CFLAGS: $LIBX11_CFLAGS " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: LIBX11_LIBS: $LIBX11_LIBS " >&5 printf "%s\n" "$as_me: LIBX11_LIBS: $LIBX11_LIBS " >&6;} fi ### DOXYGEN if test "x$enable_doxygen" = "xyes" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Checking for Doxygen..." >&5 printf "%s\n" "$as_me: Checking for Doxygen..." >&6;} for ac_prog in doxygen do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DOXYGEN+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$DOXYGEN"; then ac_cv_prog_DOXYGEN="$DOXYGEN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_DOXYGEN="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi DOXYGEN=$ac_cv_prog_DOXYGEN if test -n "$DOXYGEN"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5 printf "%s\n" "$DOXYGEN" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$DOXYGEN" && break done if test -z "$DOXYGEN"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: doxygen not found - continuing without Doxygen support" >&5 printf "%s\n" "$as_me: WARNING: doxygen not found - continuing without Doxygen support" >&2;} fi if test -n $DOXYGEN then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Calling dx_init_doxygen..." >&5 printf "%s\n" "$as_me: Calling dx_init_doxygen..." >&6;} # Files: DX_PROJECT=ddcutil DX_CONFIG='$(srcdir)/Doxyfile' DX_DOCDIR='doxygen-doc' # Environment variables used inside doxygen.cfg: DX_ENV="$DX_ENV SRCDIR='$srcdir'" SRCDIR=$srcdir DX_ENV="$DX_ENV PROJECT='$DX_PROJECT'" PROJECT=$DX_PROJECT DX_ENV="$DX_ENV VERSION='$PACKAGE_VERSION'" # Doxygen itself: # Check whether --enable-doxygen-doc was given. if test ${enable_doxygen_doc+y} then : enableval=$enable_doxygen_doc; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_doc=1 ;; #( n|N|no|No|NO) DX_FLAG_doc=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-doc" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_doc=1 ;; esac fi if test "$DX_FLAG_doc" = 1; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}doxygen", so it can be a program name with args. set dummy ${ac_tool_prefix}doxygen; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_DOXYGEN+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_DOXYGEN in [\\/]* | ?:[\\/]*) ac_cv_path_DX_DOXYGEN="$DX_DOXYGEN" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_DOXYGEN="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_DOXYGEN=$ac_cv_path_DX_DOXYGEN if test -n "$DX_DOXYGEN"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_DOXYGEN" >&5 printf "%s\n" "$DX_DOXYGEN" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_DOXYGEN"; then ac_pt_DX_DOXYGEN=$DX_DOXYGEN # Extract the first word of "doxygen", so it can be a program name with args. set dummy doxygen; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_DOXYGEN+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_DOXYGEN in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_DOXYGEN="$ac_pt_DX_DOXYGEN" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_DOXYGEN="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_DOXYGEN=$ac_cv_path_ac_pt_DX_DOXYGEN if test -n "$ac_pt_DX_DOXYGEN"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_DOXYGEN" >&5 printf "%s\n" "$ac_pt_DX_DOXYGEN" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_DOXYGEN" = x; then DX_DOXYGEN="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_DOXYGEN=$ac_pt_DX_DOXYGEN fi else DX_DOXYGEN="$ac_cv_path_DX_DOXYGEN" fi if test "$DX_FLAG_doc$DX_DOXYGEN" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: doxygen not found - will not generate any doxygen documentation" >&5 printf "%s\n" "$as_me: WARNING: doxygen not found - will not generate any doxygen documentation" >&2;} DX_FLAG_doc=0 fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}perl", so it can be a program name with args. set dummy ${ac_tool_prefix}perl; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_PERL+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_PERL in [\\/]* | ?:[\\/]*) ac_cv_path_DX_PERL="$DX_PERL" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_PERL="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_PERL=$ac_cv_path_DX_PERL if test -n "$DX_PERL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_PERL" >&5 printf "%s\n" "$DX_PERL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_PERL"; then ac_pt_DX_PERL=$DX_PERL # Extract the first word of "perl", so it can be a program name with args. set dummy perl; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_PERL+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_PERL in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_PERL="$ac_pt_DX_PERL" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_PERL="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_PERL=$ac_cv_path_ac_pt_DX_PERL if test -n "$ac_pt_DX_PERL"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_PERL" >&5 printf "%s\n" "$ac_pt_DX_PERL" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_PERL" = x; then DX_PERL="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_PERL=$ac_pt_DX_PERL fi else DX_PERL="$ac_cv_path_DX_PERL" fi if test "$DX_FLAG_doc$DX_PERL" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: perl not found - will not generate any doxygen documentation" >&5 printf "%s\n" "$as_me: WARNING: perl not found - will not generate any doxygen documentation" >&2;} DX_FLAG_doc=0 fi : fi if test "$DX_FLAG_doc" = 1; then DX_ENV="$DX_ENV PERL_PATH='$DX_PERL'" PERL_PATH=$DX_PERL : else : fi # Dot for graphics: # Check whether --enable-doxygen-dot was given. if test ${enable_doxygen_dot+y} then : enableval=$enable_doxygen_dot; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_dot=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-dot requires doxygen-dot" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_dot=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-dot" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_dot=0 test "$DX_FLAG_doc" = "1" || DX_FLAG_dot=0 ;; esac fi if test "$DX_FLAG_dot" = 1; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dot", so it can be a program name with args. set dummy ${ac_tool_prefix}dot; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_DOT+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_DOT in [\\/]* | ?:[\\/]*) ac_cv_path_DX_DOT="$DX_DOT" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_DOT="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_DOT=$ac_cv_path_DX_DOT if test -n "$DX_DOT"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_DOT" >&5 printf "%s\n" "$DX_DOT" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_DOT"; then ac_pt_DX_DOT=$DX_DOT # Extract the first word of "dot", so it can be a program name with args. set dummy dot; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_DOT+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_DOT in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_DOT="$ac_pt_DX_DOT" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_DOT="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_DOT=$ac_cv_path_ac_pt_DX_DOT if test -n "$ac_pt_DX_DOT"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_DOT" >&5 printf "%s\n" "$ac_pt_DX_DOT" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_DOT" = x; then DX_DOT="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_DOT=$ac_pt_DX_DOT fi else DX_DOT="$ac_cv_path_DX_DOT" fi if test "$DX_FLAG_dot$DX_DOT" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: dot not found - will not generate graphics for doxygen documentation" >&5 printf "%s\n" "$as_me: WARNING: dot not found - will not generate graphics for doxygen documentation" >&2;} DX_FLAG_dot=0 fi : fi if test "$DX_FLAG_dot" = 1; then DX_ENV="$DX_ENV HAVE_DOT='YES'" HAVE_DOT=YES DX_ENV="$DX_ENV DOT_PATH='`expr ".$DX_DOT" : '\(\.\)[^/]*$' \| "x$DX_DOT" : 'x\(.*\)/[^/]*$'`'" DOT_PATH=`expr ".$DX_DOT" : '\(\.\)[^/]*$' \| "x$DX_DOT" : 'x\(.*\)/[^/]*$'` : else DX_ENV="$DX_ENV HAVE_DOT='NO'" HAVE_DOT=NO : fi # Man pages generation: # Check whether --enable-doxygen-man was given. if test ${enable_doxygen_man+y} then : enableval=$enable_doxygen_man; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_man=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-man requires doxygen-man" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_man=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-man" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_man=0 test "$DX_FLAG_doc" = "1" || DX_FLAG_man=0 ;; esac fi if test "$DX_FLAG_man" = 1; then : fi if test "$DX_FLAG_man" = 1; then DX_ENV="$DX_ENV GENERATE_MAN='YES'" GENERATE_MAN=YES : else DX_ENV="$DX_ENV GENERATE_MAN='NO'" GENERATE_MAN=NO : fi # RTF file generation: # Check whether --enable-doxygen-rtf was given. if test ${enable_doxygen_rtf+y} then : enableval=$enable_doxygen_rtf; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_rtf=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-rtf requires doxygen-rtf" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_rtf=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-rtf" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_rtf=0 test "$DX_FLAG_doc" = "1" || DX_FLAG_rtf=0 ;; esac fi if test "$DX_FLAG_rtf" = 1; then : fi if test "$DX_FLAG_rtf" = 1; then DX_ENV="$DX_ENV GENERATE_RTF='YES'" GENERATE_RTF=YES : else DX_ENV="$DX_ENV GENERATE_RTF='NO'" GENERATE_RTF=NO : fi # XML file generation: # Check whether --enable-doxygen-xml was given. if test ${enable_doxygen_xml+y} then : enableval=$enable_doxygen_xml; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_xml=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-xml requires doxygen-xml" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_xml=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-xml" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_xml=0 test "$DX_FLAG_doc" = "1" || DX_FLAG_xml=0 ;; esac fi if test "$DX_FLAG_xml" = 1; then : fi if test "$DX_FLAG_xml" = 1; then DX_ENV="$DX_ENV GENERATE_XML='YES'" GENERATE_XML=YES : else DX_ENV="$DX_ENV GENERATE_XML='NO'" GENERATE_XML=NO : fi # (Compressed) HTML help generation: # Check whether --enable-doxygen-chm was given. if test ${enable_doxygen_chm+y} then : enableval=$enable_doxygen_chm; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_chm=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-chm requires doxygen-chm" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_chm=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-chm" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_chm=0 test "$DX_FLAG_doc" = "1" || DX_FLAG_chm=0 ;; esac fi if test "$DX_FLAG_chm" = 1; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}hhc", so it can be a program name with args. set dummy ${ac_tool_prefix}hhc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_HHC+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_HHC in [\\/]* | ?:[\\/]*) ac_cv_path_DX_HHC="$DX_HHC" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_HHC="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_HHC=$ac_cv_path_DX_HHC if test -n "$DX_HHC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_HHC" >&5 printf "%s\n" "$DX_HHC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_HHC"; then ac_pt_DX_HHC=$DX_HHC # Extract the first word of "hhc", so it can be a program name with args. set dummy hhc; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_HHC+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_HHC in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_HHC="$ac_pt_DX_HHC" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_HHC="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_HHC=$ac_cv_path_ac_pt_DX_HHC if test -n "$ac_pt_DX_HHC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_HHC" >&5 printf "%s\n" "$ac_pt_DX_HHC" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_HHC" = x; then DX_HHC="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_HHC=$ac_pt_DX_HHC fi else DX_HHC="$ac_cv_path_DX_HHC" fi if test "$DX_FLAG_chm$DX_HHC" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: hhc not found - will not generate doxygen compressed HTML help documentation" >&5 printf "%s\n" "$as_me: WARNING: hhc not found - will not generate doxygen compressed HTML help documentation" >&2;} DX_FLAG_chm=0 fi : fi if test "$DX_FLAG_chm" = 1; then DX_ENV="$DX_ENV HHC_PATH='$DX_HHC'" HHC_PATH=$DX_HHC DX_ENV="$DX_ENV GENERATE_HTML='YES'" GENERATE_HTML=YES DX_ENV="$DX_ENV GENERATE_HTMLHELP='YES'" GENERATE_HTMLHELP=YES : else DX_ENV="$DX_ENV GENERATE_HTMLHELP='NO'" GENERATE_HTMLHELP=NO : fi # Seperate CHI file generation. # Check whether --enable-doxygen-chi was given. if test ${enable_doxygen_chi+y} then : enableval=$enable_doxygen_chi; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_chi=1 test "$DX_FLAG_chm" = "1" \ || as_fn_error $? "doxygen-chi requires doxygen-chi" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_chi=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-chi" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_chi=0 test "$DX_FLAG_chm" = "1" || DX_FLAG_chi=0 ;; esac fi if test "$DX_FLAG_chi" = 1; then : fi if test "$DX_FLAG_chi" = 1; then DX_ENV="$DX_ENV GENERATE_CHI='YES'" GENERATE_CHI=YES : else DX_ENV="$DX_ENV GENERATE_CHI='NO'" GENERATE_CHI=NO : fi # Plain HTML pages generation: # Check whether --enable-doxygen-html was given. if test ${enable_doxygen_html+y} then : enableval=$enable_doxygen_html; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_html=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-html requires doxygen-html" "$LINENO" 5 test "$DX_FLAG_chm" = "0" \ || as_fn_error $? "doxygen-html contradicts doxygen-html" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_html=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-html" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_html=1 test "$DX_FLAG_doc" = "1" || DX_FLAG_html=0 test "$DX_FLAG_chm" = "0" || DX_FLAG_html=0 ;; esac fi if test "$DX_FLAG_html" = 1; then : fi if test "$DX_FLAG_html" = 1; then DX_ENV="$DX_ENV GENERATE_HTML='YES'" GENERATE_HTML=YES : else test "$DX_FLAG_chm" = 1 || DX_ENV="$DX_ENV GENERATE_HTML='NO'" GENERATE_HTML=NO : fi # PostScript file generation: # Check whether --enable-doxygen-ps was given. if test ${enable_doxygen_ps+y} then : enableval=$enable_doxygen_ps; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_ps=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-ps requires doxygen-ps" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_ps=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-ps" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_ps=1 test "$DX_FLAG_doc" = "1" || DX_FLAG_ps=0 ;; esac fi if test "$DX_FLAG_ps" = 1; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}latex", so it can be a program name with args. set dummy ${ac_tool_prefix}latex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_LATEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_LATEX in [\\/]* | ?:[\\/]*) ac_cv_path_DX_LATEX="$DX_LATEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_LATEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_LATEX=$ac_cv_path_DX_LATEX if test -n "$DX_LATEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_LATEX" >&5 printf "%s\n" "$DX_LATEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_LATEX"; then ac_pt_DX_LATEX=$DX_LATEX # Extract the first word of "latex", so it can be a program name with args. set dummy latex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_LATEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_LATEX in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_LATEX="$ac_pt_DX_LATEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_LATEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_LATEX=$ac_cv_path_ac_pt_DX_LATEX if test -n "$ac_pt_DX_LATEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_LATEX" >&5 printf "%s\n" "$ac_pt_DX_LATEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_LATEX" = x; then DX_LATEX="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_LATEX=$ac_pt_DX_LATEX fi else DX_LATEX="$ac_cv_path_DX_LATEX" fi if test "$DX_FLAG_ps$DX_LATEX" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: latex not found - will not generate doxygen PostScript documentation" >&5 printf "%s\n" "$as_me: WARNING: latex not found - will not generate doxygen PostScript documentation" >&2;} DX_FLAG_ps=0 fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}makeindex", so it can be a program name with args. set dummy ${ac_tool_prefix}makeindex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_MAKEINDEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_MAKEINDEX in [\\/]* | ?:[\\/]*) ac_cv_path_DX_MAKEINDEX="$DX_MAKEINDEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_MAKEINDEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_MAKEINDEX=$ac_cv_path_DX_MAKEINDEX if test -n "$DX_MAKEINDEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_MAKEINDEX" >&5 printf "%s\n" "$DX_MAKEINDEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_MAKEINDEX"; then ac_pt_DX_MAKEINDEX=$DX_MAKEINDEX # Extract the first word of "makeindex", so it can be a program name with args. set dummy makeindex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_MAKEINDEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_MAKEINDEX in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_MAKEINDEX="$ac_pt_DX_MAKEINDEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_MAKEINDEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_MAKEINDEX=$ac_cv_path_ac_pt_DX_MAKEINDEX if test -n "$ac_pt_DX_MAKEINDEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_MAKEINDEX" >&5 printf "%s\n" "$ac_pt_DX_MAKEINDEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_MAKEINDEX" = x; then DX_MAKEINDEX="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_MAKEINDEX=$ac_pt_DX_MAKEINDEX fi else DX_MAKEINDEX="$ac_cv_path_DX_MAKEINDEX" fi if test "$DX_FLAG_ps$DX_MAKEINDEX" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: makeindex not found - will not generate doxygen PostScript documentation" >&5 printf "%s\n" "$as_me: WARNING: makeindex not found - will not generate doxygen PostScript documentation" >&2;} DX_FLAG_ps=0 fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dvips", so it can be a program name with args. set dummy ${ac_tool_prefix}dvips; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_DVIPS+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_DVIPS in [\\/]* | ?:[\\/]*) ac_cv_path_DX_DVIPS="$DX_DVIPS" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_DVIPS="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_DVIPS=$ac_cv_path_DX_DVIPS if test -n "$DX_DVIPS"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_DVIPS" >&5 printf "%s\n" "$DX_DVIPS" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_DVIPS"; then ac_pt_DX_DVIPS=$DX_DVIPS # Extract the first word of "dvips", so it can be a program name with args. set dummy dvips; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_DVIPS+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_DVIPS in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_DVIPS="$ac_pt_DX_DVIPS" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_DVIPS="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_DVIPS=$ac_cv_path_ac_pt_DX_DVIPS if test -n "$ac_pt_DX_DVIPS"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_DVIPS" >&5 printf "%s\n" "$ac_pt_DX_DVIPS" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_DVIPS" = x; then DX_DVIPS="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_DVIPS=$ac_pt_DX_DVIPS fi else DX_DVIPS="$ac_cv_path_DX_DVIPS" fi if test "$DX_FLAG_ps$DX_DVIPS" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: dvips not found - will not generate doxygen PostScript documentation" >&5 printf "%s\n" "$as_me: WARNING: dvips not found - will not generate doxygen PostScript documentation" >&2;} DX_FLAG_ps=0 fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}egrep", so it can be a program name with args. set dummy ${ac_tool_prefix}egrep; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_EGREP+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_EGREP in [\\/]* | ?:[\\/]*) ac_cv_path_DX_EGREP="$DX_EGREP" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_EGREP="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_EGREP=$ac_cv_path_DX_EGREP if test -n "$DX_EGREP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_EGREP" >&5 printf "%s\n" "$DX_EGREP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_EGREP"; then ac_pt_DX_EGREP=$DX_EGREP # Extract the first word of "egrep", so it can be a program name with args. set dummy egrep; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_EGREP+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_EGREP in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_EGREP="$ac_pt_DX_EGREP" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_EGREP="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_EGREP=$ac_cv_path_ac_pt_DX_EGREP if test -n "$ac_pt_DX_EGREP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_EGREP" >&5 printf "%s\n" "$ac_pt_DX_EGREP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_EGREP" = x; then DX_EGREP="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_EGREP=$ac_pt_DX_EGREP fi else DX_EGREP="$ac_cv_path_DX_EGREP" fi if test "$DX_FLAG_ps$DX_EGREP" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: egrep not found - will not generate doxygen PostScript documentation" >&5 printf "%s\n" "$as_me: WARNING: egrep not found - will not generate doxygen PostScript documentation" >&2;} DX_FLAG_ps=0 fi : fi if test "$DX_FLAG_ps" = 1; then : else : fi # PDF file generation: # Check whether --enable-doxygen-pdf was given. if test ${enable_doxygen_pdf+y} then : enableval=$enable_doxygen_pdf; case "$enableval" in #( y|Y|yes|Yes|YES) DX_FLAG_pdf=1 test "$DX_FLAG_doc" = "1" \ || as_fn_error $? "doxygen-pdf requires doxygen-pdf" "$LINENO" 5 ;; #( n|N|no|No|NO) DX_FLAG_pdf=0 ;; #( *) as_fn_error $? "invalid value '$enableval' given to doxygen-pdf" "$LINENO" 5 ;; esac else case e in #( e) DX_FLAG_pdf=1 test "$DX_FLAG_doc" = "1" || DX_FLAG_pdf=0 ;; esac fi if test "$DX_FLAG_pdf" = 1; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}pdflatex", so it can be a program name with args. set dummy ${ac_tool_prefix}pdflatex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_PDFLATEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_PDFLATEX in [\\/]* | ?:[\\/]*) ac_cv_path_DX_PDFLATEX="$DX_PDFLATEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_PDFLATEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_PDFLATEX=$ac_cv_path_DX_PDFLATEX if test -n "$DX_PDFLATEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_PDFLATEX" >&5 printf "%s\n" "$DX_PDFLATEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_PDFLATEX"; then ac_pt_DX_PDFLATEX=$DX_PDFLATEX # Extract the first word of "pdflatex", so it can be a program name with args. set dummy pdflatex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_PDFLATEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_PDFLATEX in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_PDFLATEX="$ac_pt_DX_PDFLATEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_PDFLATEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_PDFLATEX=$ac_cv_path_ac_pt_DX_PDFLATEX if test -n "$ac_pt_DX_PDFLATEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_PDFLATEX" >&5 printf "%s\n" "$ac_pt_DX_PDFLATEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_PDFLATEX" = x; then DX_PDFLATEX="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_PDFLATEX=$ac_pt_DX_PDFLATEX fi else DX_PDFLATEX="$ac_cv_path_DX_PDFLATEX" fi if test "$DX_FLAG_pdf$DX_PDFLATEX" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: pdflatex not found - will not generate doxygen PDF documentation" >&5 printf "%s\n" "$as_me: WARNING: pdflatex not found - will not generate doxygen PDF documentation" >&2;} DX_FLAG_pdf=0 fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}makeindex", so it can be a program name with args. set dummy ${ac_tool_prefix}makeindex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_MAKEINDEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_MAKEINDEX in [\\/]* | ?:[\\/]*) ac_cv_path_DX_MAKEINDEX="$DX_MAKEINDEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_MAKEINDEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_MAKEINDEX=$ac_cv_path_DX_MAKEINDEX if test -n "$DX_MAKEINDEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_MAKEINDEX" >&5 printf "%s\n" "$DX_MAKEINDEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_MAKEINDEX"; then ac_pt_DX_MAKEINDEX=$DX_MAKEINDEX # Extract the first word of "makeindex", so it can be a program name with args. set dummy makeindex; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_MAKEINDEX+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_MAKEINDEX in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_MAKEINDEX="$ac_pt_DX_MAKEINDEX" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_MAKEINDEX="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_MAKEINDEX=$ac_cv_path_ac_pt_DX_MAKEINDEX if test -n "$ac_pt_DX_MAKEINDEX"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_MAKEINDEX" >&5 printf "%s\n" "$ac_pt_DX_MAKEINDEX" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_MAKEINDEX" = x; then DX_MAKEINDEX="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_MAKEINDEX=$ac_pt_DX_MAKEINDEX fi else DX_MAKEINDEX="$ac_cv_path_DX_MAKEINDEX" fi if test "$DX_FLAG_pdf$DX_MAKEINDEX" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: makeindex not found - will not generate doxygen PDF documentation" >&5 printf "%s\n" "$as_me: WARNING: makeindex not found - will not generate doxygen PDF documentation" >&2;} DX_FLAG_pdf=0 fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}egrep", so it can be a program name with args. set dummy ${ac_tool_prefix}egrep; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_DX_EGREP+y} then : printf %s "(cached) " >&6 else case e in #( e) case $DX_EGREP in [\\/]* | ?:[\\/]*) ac_cv_path_DX_EGREP="$DX_EGREP" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_DX_EGREP="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi DX_EGREP=$ac_cv_path_DX_EGREP if test -n "$DX_EGREP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DX_EGREP" >&5 printf "%s\n" "$DX_EGREP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi fi if test -z "$ac_cv_path_DX_EGREP"; then ac_pt_DX_EGREP=$DX_EGREP # Extract the first word of "egrep", so it can be a program name with args. set dummy egrep; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ac_pt_DX_EGREP+y} then : printf %s "(cached) " >&6 else case e in #( e) case $ac_pt_DX_EGREP in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_DX_EGREP="$ac_pt_DX_EGREP" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_DX_EGREP="$as_dir$ac_word$ac_exec_ext" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac ;; esac fi ac_pt_DX_EGREP=$ac_cv_path_ac_pt_DX_EGREP if test -n "$ac_pt_DX_EGREP"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_pt_DX_EGREP" >&5 printf "%s\n" "$ac_pt_DX_EGREP" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi if test "x$ac_pt_DX_EGREP" = x; then DX_EGREP="" else case $cross_compiling:$ac_tool_warned in yes:) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DX_EGREP=$ac_pt_DX_EGREP fi else DX_EGREP="$ac_cv_path_DX_EGREP" fi if test "$DX_FLAG_pdf$DX_EGREP" = 1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: egrep not found - will not generate doxygen PDF documentation" >&5 printf "%s\n" "$as_me: WARNING: egrep not found - will not generate doxygen PDF documentation" >&2;} DX_FLAG_pdf=0 fi : fi if test "$DX_FLAG_pdf" = 1; then : else : fi # LaTeX generation for PS and/or PDF: if test "$DX_FLAG_ps" = 1 || test "$DX_FLAG_pdf" = 1; then DX_ENV="$DX_ENV GENERATE_LATEX='YES'" GENERATE_LATEX=YES else DX_ENV="$DX_ENV GENERATE_LATEX='NO'" GENERATE_LATEX=NO fi # Paper size for PS and/or PDF: case "$DOXYGEN_PAPER_SIZE" in #( "") DOXYGEN_PAPER_SIZE="" ;; #( a4wide|a4|letter|legal|executive) DX_ENV="$DX_ENV PAPER_SIZE='$DOXYGEN_PAPER_SIZE'" PAPER_SIZE=$DOXYGEN_PAPER_SIZE ;; #( *) as_fn_error $? "unknown DOXYGEN_PAPER_SIZE='$DOXYGEN_PAPER_SIZE'" "$LINENO" 5 ;; esac # Rules: if test $DX_FLAG_html -eq 1 then : DX_SNIPPET_html="## ------------------------------- ## ## Rules specific for HTML output. ## ## ------------------------------- ## DX_CLEAN_HTML = \$(DX_DOCDIR)/html\\ \$(DX_DOCDIR)/html " else case e in #( e) DX_SNIPPET_html="" ;; esac fi if test $DX_FLAG_chi -eq 1 then : DX_SNIPPET_chi=" DX_CLEAN_CHI = \$(DX_DOCDIR)/\$(PACKAGE).chi\\ \$(DX_DOCDIR)/\$(PACKAGE).chi" else case e in #( e) DX_SNIPPET_chi="" ;; esac fi if test $DX_FLAG_chm -eq 1 then : DX_SNIPPET_chm="## ------------------------------ ## ## Rules specific for CHM output. ## ## ------------------------------ ## DX_CLEAN_CHM = \$(DX_DOCDIR)/chm\\ \$(DX_DOCDIR)/chm\ ${DX_SNIPPET_chi} " else case e in #( e) DX_SNIPPET_chm="" ;; esac fi if test $DX_FLAG_man -eq 1 then : DX_SNIPPET_man="## ------------------------------ ## ## Rules specific for MAN output. ## ## ------------------------------ ## DX_CLEAN_MAN = \$(DX_DOCDIR)/man\\ \$(DX_DOCDIR)/man " else case e in #( e) DX_SNIPPET_man="" ;; esac fi if test $DX_FLAG_rtf -eq 1 then : DX_SNIPPET_rtf="## ------------------------------ ## ## Rules specific for RTF output. ## ## ------------------------------ ## DX_CLEAN_RTF = \$(DX_DOCDIR)/rtf\\ \$(DX_DOCDIR)/rtf " else case e in #( e) DX_SNIPPET_rtf="" ;; esac fi if test $DX_FLAG_xml -eq 1 then : DX_SNIPPET_xml="## ------------------------------ ## ## Rules specific for XML output. ## ## ------------------------------ ## DX_CLEAN_XML = \$(DX_DOCDIR)/xml\\ \$(DX_DOCDIR)/xml " else case e in #( e) DX_SNIPPET_xml="" ;; esac fi if test $DX_FLAG_ps -eq 1 then : DX_SNIPPET_ps="## ----------------------------- ## ## Rules specific for PS output. ## ## ----------------------------- ## DX_CLEAN_PS = \$(DX_DOCDIR)/\$(PACKAGE).ps\\ \$(DX_DOCDIR)/\$(PACKAGE).ps DX_PS_GOAL = doxygen-ps doxygen-ps: \$(DX_CLEAN_PS) \$(DX_DOCDIR)/\$(PACKAGE).ps: \$(DX_DOCDIR)/\$(PACKAGE).tag \$(DX_V_LATEX)cd \$(DX_DOCDIR)/latex; \\ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\ \$(DX_LATEX) refman.tex; \\ \$(DX_MAKEINDEX) refman.idx; \\ \$(DX_LATEX) refman.tex; \\ countdown=5; \\ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\ refman.log > /dev/null 2>&1 \\ && test \$\$countdown -gt 0; do \\ \$(DX_LATEX) refman.tex; \\ countdown=\`expr \$\$countdown - 1\`; \\ done; \\ \$(DX_DVIPS) -o ../\$(PACKAGE).ps refman.dvi " else case e in #( e) DX_SNIPPET_ps="" ;; esac fi if test $DX_FLAG_pdf -eq 1 then : DX_SNIPPET_pdf="## ------------------------------ ## ## Rules specific for PDF output. ## ## ------------------------------ ## DX_CLEAN_PDF = \$(DX_DOCDIR)/\$(PACKAGE).pdf\\ \$(DX_DOCDIR)/\$(PACKAGE).pdf DX_PDF_GOAL = doxygen-pdf doxygen-pdf: \$(DX_CLEAN_PDF) \$(DX_DOCDIR)/\$(PACKAGE).pdf: \$(DX_DOCDIR)/\$(PACKAGE).tag \$(DX_V_LATEX)cd \$(DX_DOCDIR)/latex; \\ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\ \$(DX_PDFLATEX) refman.tex; \\ \$(DX_MAKEINDEX) refman.idx; \\ \$(DX_PDFLATEX) refman.tex; \\ countdown=5; \\ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\ refman.log > /dev/null 2>&1 \\ && test \$\$countdown -gt 0; do \\ \$(DX_PDFLATEX) refman.tex; \\ countdown=\`expr \$\$countdown - 1\`; \\ done; \\ mv refman.pdf ../\$(PACKAGE).pdf " else case e in #( e) DX_SNIPPET_pdf="" ;; esac fi if test $DX_FLAG_ps -eq 1 -o $DX_FLAG_pdf -eq 1 then : DX_SNIPPET_latex="## ------------------------------------------------- ## ## Rules specific for LaTeX (shared for PS and PDF). ## ## ------------------------------------------------- ## DX_V_LATEX = \$(_DX_v_LATEX_\$(V)) _DX_v_LATEX_ = \$(_DX_v_LATEX_\$(AM_DEFAULT_VERBOSITY)) _DX_v_LATEX_0 = @echo \" LATEX \" \$@; DX_CLEAN_LATEX = \$(DX_DOCDIR)/latex\\ \$(DX_DOCDIR)/latex " else case e in #( e) DX_SNIPPET_latex="" ;; esac fi if test $DX_FLAG_doc -eq 1 then : DX_SNIPPET_doc="## --------------------------------- ## ## Format-independent Doxygen rules. ## ## --------------------------------- ## ${DX_SNIPPET_html}\ ${DX_SNIPPET_chm}\ ${DX_SNIPPET_man}\ ${DX_SNIPPET_rtf}\ ${DX_SNIPPET_xml}\ ${DX_SNIPPET_ps}\ ${DX_SNIPPET_pdf}\ ${DX_SNIPPET_latex}\ DX_V_DXGEN = \$(_DX_v_DXGEN_\$(V)) _DX_v_DXGEN_ = \$(_DX_v_DXGEN_\$(AM_DEFAULT_VERBOSITY)) _DX_v_DXGEN_0 = @echo \" DXGEN \" \$<; .PHONY: doxygen-run doxygen-doc \$(DX_PS_GOAL) \$(DX_PDF_GOAL) .INTERMEDIATE: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL) doxygen-run: \$(DX_DOCDIR)/\$(PACKAGE).tag doxygen-doc: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL) \$(DX_DOCDIR)/\$(PACKAGE).tag: \$(DX_CONFIG) \$(pkginclude_HEADERS) \$(A""M_V_at)rm -rf \$(DX_DOCDIR) \$(DX_V_DXGEN)\$(DX_ENV) DOCDIR=\$(DX_DOCDIR) \$(DX_DOXYGEN) \$(DX_CONFIG) \$(A""M_V_at)echo Timestamp >\$@ DX_CLEANFILES = \\ \$(DX_DOCDIR)/doxygen_sqlite3.db \\ \$(DX_DOCDIR)/\$(PACKAGE).tag \\ -r \\ \$(DX_CLEAN_HTML) \\ \$(DX_CLEAN_CHM) \\ \$(DX_CLEAN_CHI) \\ \$(DX_CLEAN_MAN) \\ \$(DX_CLEAN_RTF) \\ \$(DX_CLEAN_XML) \\ \$(DX_CLEAN_PS) \\ \$(DX_CLEAN_PDF) \\ \$(DX_CLEAN_LATEX)" else case e in #( e) DX_SNIPPET_doc="" ;; esac fi DX_RULES="${DX_SNIPPET_doc}" #For debugging: #echo DX_FLAG_doc=$DX_FLAG_doc #echo DX_FLAG_dot=$DX_FLAG_dot #echo DX_FLAG_man=$DX_FLAG_man #echo DX_FLAG_html=$DX_FLAG_html #echo DX_FLAG_chm=$DX_FLAG_chm #echo DX_FLAG_chi=$DX_FLAG_chi #echo DX_FLAG_rtf=$DX_FLAG_rtf #echo DX_FLAG_xml=$DX_FLAG_xml #echo DX_FLAG_pdf=$DX_FLAG_pdf #echo DX_FLAG_ps=$DX_FLAG_ps #echo DX_ENV=$DX_ENV if test 0$DBG -ne 0 then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Set by dx_init_doxygen:" >&5 printf "%s\n" "$as_me: Set by dx_init_doxygen:" >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: DOXYGEN: $DOXYGEN " >&5 printf "%s\n" "$as_me: DOXYGEN: $DOXYGEN " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: dx_DOT_FEATURE: $ " >&5 printf "%s\n" "$as_me: dx_DOT_FEATURE: $ " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: dx_FEATURE_doc $ON " >&5 printf "%s\n" "$as_me: dx_FEATURE_doc $ON " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: dx_DOXYGEN_FEATURE: $ " >&5 printf "%s\n" "$as_me: dx_DOXYGEN_FEATURE: $ " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: dx_HTML_FEATURE: $ " >&5 printf "%s\n" "$as_me: dx_HTML_FEATURE: $ " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: dx_FLAG_html: $DX_FLAG_HTML " >&5 printf "%s\n" "$as_me: dx_FLAG_html: $DX_FLAG_HTML " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: dx_PDF_FEATURE: $ " >&5 printf "%s\n" "$as_me: dx_PDF_FEATURE: $ " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: DX_PROJECT: $DX_PROJECT " >&5 printf "%s\n" "$as_me: DX_PROJECT: $DX_PROJECT " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: DX_CONFIG: $DX_CONFIG " >&5 printf "%s\n" "$as_me: DX_CONFIG: $DX_CONFIG " >&6;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: DX_DOCDIR: $DX_DOCDIR " >&5 printf "%s\n" "$as_me: DX_DOCDIR: $DX_DOCDIR " >&6;} fi ac_config_files="$ac_config_files docs/doxygen/doxyfile" else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: doxygen not found" >&5 printf "%s\n" "$as_me: doxygen not found" >&6;} enable_doxygen=no ;; esac fi else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: doxygen disabled, not checking for Doxygen" >&5 printf "%s\n" "$as_me: doxygen disabled, not checking for Doxygen" >&6;} ;; esac fi if test "x$enable_doxygen" = "xyes"; then USE_DOXYGEN_TRUE= USE_DOXYGEN_FALSE='#' else USE_DOXYGEN_TRUE='#' USE_DOXYGEN_FALSE= fi if test -z "$USE_DOXYGEN_TRUE"; then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: USE_DOXYGEN is set" >&5 printf "%s\n" "$as_me: USE_DOXYGEN is set" >&6;} else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: USE_DOXYGEN not set" >&5 printf "%s\n" "$as_me: USE_DOXYGEN not set" >&6;} fi ### DOC-BASE for ac_prog in install-docs do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DOCBASE_INSTALL_DOCS+y} then : printf %s "(cached) " >&6 else case e in #( e) if test -n "$DOCBASE_INSTALL_DOCS"; then ac_cv_prog_DOCBASE_INSTALL_DOCS="$DOCBASE_INSTALL_DOCS" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then ac_cv_prog_DOCBASE_INSTALL_DOCS="$ac_prog" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi ;; esac fi DOCBASE_INSTALL_DOCS=$ac_cv_prog_DOCBASE_INSTALL_DOCS if test -n "$DOCBASE_INSTALL_DOCS"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $DOCBASE_INSTALL_DOCS" >&5 printf "%s\n" "$DOCBASE_INSTALL_DOCS" >&6; } else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } fi test -n "$DOCBASE_INSTALL_DOCS" && break done if test -n "$DOCBASE_INSTALL_DOCS" then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: doc-base execuable found" >&5 printf "%s\n" "$as_me: doc-base execuable found" >&6;} ac_config_files="$ac_config_files docs/ddcutil-c-api" else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: doc-base not installed - continuing without doc-base support" >&5 printf "%s\n" "$as_me: WARNING: doc-base not installed - continuing without doc-base support" >&2;} ;; esac fi if test -n "$DOCBASE_INSTALL_DOCS"; then HAVE_DOCBASE_TRUE= HAVE_DOCBASE_FALSE='#' else HAVE_DOCBASE_TRUE='#' HAVE_DOCBASE_FALSE= fi ### Library if test "x$enable_lib" = "xyes" then : pkg_failed=no { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for zlib" >&5 printf %s "checking for zlib... " >&6; } if test -n "$ZLIB_CFLAGS"; then pkg_cv_ZLIB_CFLAGS="$ZLIB_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"zlib\""; } >&5 ($PKG_CONFIG --exists --print-errors "zlib") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_ZLIB_CFLAGS=`$PKG_CONFIG --cflags "zlib" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$ZLIB_LIBS"; then pkg_cv_ZLIB_LIBS="$ZLIB_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"zlib\""; } >&5 ($PKG_CONFIG --exists --print-errors "zlib") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_ZLIB_LIBS=`$PKG_CONFIG --libs "zlib" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then ZLIB_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "zlib" 2>&1` else ZLIB_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "zlib" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$ZLIB_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (zlib) were not met: $ZLIB_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables ZLIB_CFLAGS and ZLIB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 printf "%s\n" "no" >&6; } { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables ZLIB_CFLAGS and ZLIB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See 'config.log' for more details" "$LINENO" 5; } else ZLIB_CFLAGS=$pkg_cv_ZLIB_CFLAGS ZLIB_LIBS=$pkg_cv_ZLIB_LIBS { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 printf "%s\n" "yes" >&6; } fi fi if test "x$enable_asan" = "xyes" then : required_packages="asan $required_packages" # has no effect on $CFLAGS CFLAGS="$CFLAGS -fsanitize=address" CFLAGS="$CFLAGS -fsanitize-address-use-after-scope -fno-omit-frame-pointer" fi REQUIRED_PACKAGES=$required_packages ### Opsys variability { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking target OS using /etc/os-release " >&5 printf %s "checking target OS using /etc/os-release ... " >&6; } if grep suse /etc/os-release > /dev/null then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: target is SUSE" >&5 printf "%s\n" "target is SUSE" >&6; } docdir=\${datarootdir}/doc/packages/\${PACKAGE_TARNAME} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: ..Forcing docdir to ${docdir} " >&5 printf "%s\n" "$as_me: ..Forcing docdir to ${docdir} " >&6;} else case e in #( e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: target is not SUSE " >&5 printf "%s\n" "target is not SUSE " >&6; } ;; esac fi ### ### Generate output ### cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # 'ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* 'ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # 'set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # 'set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test ${\1+y} || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 printf "%s\n" "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { printf "%s\n" "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 printf "%s\n" "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`printf "%s\n" "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs if test -z "${WARNINGS_ARE_ERRORS_COND_TRUE}" && test -z "${WARNINGS_ARE_ERRORS_COND_FALSE}"; then as_fn_error $? "conditional \"WARNINGS_ARE_ERRORS_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking that generated files are newer than configure" >&5 printf %s "checking that generated files are newer than configure... " >&6; } if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: done" >&5 printf "%s\n" "done" >&6; } if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' else am__EXEEXT_TRUE='#' am__EXEEXT_FALSE= fi if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${HAVE_ADL_COND_TRUE}" && test -z "${HAVE_ADL_COND_FALSE}"; then as_fn_error $? "conditional \"HAVE_ADL_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_SHARED_LIB_COND_TRUE}" && test -z "${ENABLE_SHARED_LIB_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_SHARED_LIB_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${INSTALL_LIB_ONLY_COND_TRUE}" && test -z "${INSTALL_LIB_ONLY_COND_FALSE}"; then as_fn_error $? "conditional \"INSTALL_LIB_ONLY_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_BUILD_TIMESTAMP_COND_TRUE}" && test -z "${ENABLE_BUILD_TIMESTAMP_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_BUILD_TIMESTAMP_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${STATIC_FUNCTIONS_VISIBLE_COND_TRUE}" && test -z "${STATIC_FUNCTIONS_VISIBLE_COND_FALSE}"; then as_fn_error $? "conditional \"STATIC_FUNCTIONS_VISIBLE_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ASAN_COND_TRUE}" && test -z "${ASAN_COND_FALSE}"; then as_fn_error $? "conditional \"ASAN_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_DOXYGEN_COND_TRUE}" && test -z "${ENABLE_DOXYGEN_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_DOXYGEN_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_TARGETBSD_COND_TRUE}" && test -z "${ENABLE_TARGETBSD_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_TARGETBSD_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_ENVCMDS_COND_TRUE}" && test -z "${ENABLE_ENVCMDS_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_ENVCMDS_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_UDEV_COND_TRUE}" && test -z "${ENABLE_UDEV_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_UDEV_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_USB_COND_TRUE}" && test -z "${ENABLE_USB_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_USB_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${INCLUDE_TESTCASES_COND_TRUE}" && test -z "${INCLUDE_TESTCASES_COND_FALSE}"; then as_fn_error $? "conditional \"INCLUDE_TESTCASES_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_CALLGRAPH_COND_TRUE}" && test -z "${ENABLE_CALLGRAPH_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_CALLGRAPH_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_FAILSIM_COND_TRUE}" && test -z "${ENABLE_FAILSIM_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_FAILSIM_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_FORCE_SUSE_COND_TRUE}" && test -z "${ENABLE_FORCE_SUSE_COND_FALSE}"; then as_fn_error $? "conditional \"ENABLE_FORCE_SUSE_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_LIBDRM_COND_TRUE}" && test -z "${USE_LIBDRM_COND_FALSE}"; then as_fn_error $? "conditional \"USE_LIBDRM_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_X11_COND_TRUE}" && test -z "${USE_X11_COND_FALSE}"; then as_fn_error $? "conditional \"USE_X11_COND\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_DOXYGEN_TRUE}" && test -z "${USE_DOXYGEN_FALSE}"; then as_fn_error $? "conditional \"USE_DOXYGEN\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${HAVE_DOCBASE_TRUE}" && test -z "${HAVE_DOCBASE_FALSE}"; then as_fn_error $? "conditional \"HAVE_DOCBASE\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 printf "%s\n" "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case e in #( e) case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac ;; esac fi # Reset variables that may have inherited troublesome values from # the environment. # IFS needs to be set, to space, tab, and newline, in precisely that order. # (If _AS_PATH_WALK were called with IFS unset, it would have the # side effect of setting IFS to empty, thus disabling word splitting.) # Quoting is to prevent editors from complaining about space-tab. as_nl=' ' export as_nl IFS=" "" $as_nl" PS1='$ ' PS2='> ' PS4='+ ' # Ensure predictable behavior from utilities with locale-dependent output. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # We cannot yet rely on "unset" to work, but we need these variables # to be unset--not just set to an empty or harmless value--now, to # avoid bugs in old shells (e.g. pre-3.0 UWIN ksh). This construct # also avoids known problems related to "unset" and subshell syntax # in other old shells (e.g. bash 2.01 and pdksh 5.2.14). for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH do eval test \${$as_var+y} \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done # Ensure that fds 0, 1, and 2 are open. if (exec 3>&0) 2>/dev/null; then :; else exec 0&1) 2>/dev/null; then :; else exec 1>/dev/null; fi if (exec 3>&2) ; then :; else exec 2>/dev/null; fi # The user is always right. if ${PATH_SEPARATOR+false} :; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS case $as_dir in #((( '') as_dir=./ ;; */) ;; *) as_dir=$as_dir/ ;; esac test -r "$as_dir$0" && as_myself=$as_dir$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as 'sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi printf "%s\n" "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null then : eval 'as_fn_append () { eval $1+=\$2 }' else case e in #( e) as_fn_append () { eval $1=\$$1\$2 } ;; esac fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null then : eval 'as_fn_arith () { as_val=$(( $* )) }' else case e in #( e) as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } ;; esac fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits # Determine whether it's possible to make 'echo' print without a newline. # These variables are no longer used directly by Autoconf, but are AC_SUBSTed # for compatibility with existing Makefiles. ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac # For backward compatibility with old third-party macros, we provide # the shell variables $as_echo and $as_echo_n. New code should use # AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively. as_echo='printf %s\n' as_echo_n='printf %s' rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both 'ln -s file dir' and 'ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; 'ln -s' creates a wrapper executable. # In both cases, we have to default to 'cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_sed_cpp="y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g" as_tr_cpp="eval sed '$as_sed_cpp'" # deprecated # Sed expression to map a string onto a valid variable name. as_sed_sh="y%*+%pp%;s%[^_$as_cr_alnum]%_%g" as_tr_sh="eval sed '$as_sed_sh'" # deprecated exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by ddcutil $as_me 2.2.0, which was generated by GNU Autoconf 2.72. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" config_commands="$ac_config_commands" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ '$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Configuration commands: $config_commands Report bugs to ." _ACEOF ac_cs_config=`printf "%s\n" "$ac_configure_args" | sed "$ac_safe_unquote"` ac_cs_config_escaped=`printf "%s\n" "$ac_cs_config" | sed "s/^ //; s/'/'\\\\\\\\''/g"` cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config='$ac_cs_config_escaped' ac_cs_version="\\ ddcutil config.status 2.2.0 configured by $0, generated by GNU Autoconf 2.72, with options \\"\$ac_cs_config\\" Copyright (C) 2023 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) printf "%s\n" "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) printf "%s\n" "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`printf "%s\n" "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`printf "%s\n" "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: '$1' Try '$0 --help' for more information.";; --help | --hel | -h ) printf "%s\n" "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: '$1' Try '$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \printf "%s\n" "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX printf "%s\n" "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # # INIT-COMMANDS # AMDEP_TRUE="$AMDEP_TRUE" MAKE="${MAKE-make}" # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' shared_archive_member_spec='`$ECHO "$shared_archive_member_spec" | $SED "$delay_single_quote_subst"`' SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' FILECMD='`$ECHO "$FILECMD" | $SED "$delay_single_quote_subst"`' OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' lt_ar_flags='`$ECHO "$lt_ar_flags" | $SED "$delay_single_quote_subst"`' AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_import='`$ECHO "$lt_cv_sys_global_symbol_to_import" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' lt_cv_nm_interface='`$ECHO "$lt_cv_nm_interface" | $SED "$delay_single_quote_subst"`' nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' lt_cv_truncate_bin='`$ECHO "$lt_cv_truncate_bin" | $SED "$delay_single_quote_subst"`' objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' configure_time_dlsearch_path='`$ECHO "$configure_time_dlsearch_path" | $SED "$delay_single_quote_subst"`' configure_time_lt_sys_library_path='`$ECHO "$configure_time_lt_sys_library_path" | $SED "$delay_single_quote_subst"`' hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } # Quote evaled strings. for var in SHELL \ ECHO \ PATH_SEPARATOR \ SED \ GREP \ EGREP \ FGREP \ LD \ NM \ LN_S \ lt_SP2NL \ lt_NL2SP \ reload_flag \ FILECMD \ OBJDUMP \ deplibs_check_method \ file_magic_cmd \ file_magic_glob \ want_nocaseglob \ DLLTOOL \ sharedlib_from_linklib_cmd \ AR \ archiver_list_spec \ STRIP \ RANLIB \ CC \ CFLAGS \ compiler \ lt_cv_sys_global_symbol_pipe \ lt_cv_sys_global_symbol_to_cdecl \ lt_cv_sys_global_symbol_to_import \ lt_cv_sys_global_symbol_to_c_name_address \ lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ lt_cv_nm_interface \ nm_file_list_spec \ lt_cv_truncate_bin \ lt_prog_compiler_no_builtin_flag \ lt_prog_compiler_pic \ lt_prog_compiler_wl \ lt_prog_compiler_static \ lt_cv_prog_compiler_c_o \ need_locks \ MANIFEST_TOOL \ DSYMUTIL \ NMEDIT \ LIPO \ OTOOL \ OTOOL64 \ shrext_cmds \ export_dynamic_flag_spec \ whole_archive_flag_spec \ compiler_needs_object \ with_gnu_ld \ allow_undefined_flag \ no_undefined_flag \ hardcode_libdir_flag_spec \ hardcode_libdir_separator \ exclude_expsyms \ include_expsyms \ file_list_spec \ variables_saved_for_relink \ libname_spec \ library_names_spec \ soname_spec \ install_override_mode \ finish_eval \ old_striplib \ striplib; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in reload_cmds \ old_postinstall_cmds \ old_postuninstall_cmds \ old_archive_cmds \ extract_expsyms_cmds \ old_archive_from_new_cmds \ old_archive_from_expsyms_cmds \ archive_cmds \ archive_expsym_cmds \ module_cmds \ module_expsym_cmds \ export_symbols_cmds \ prelink_cmds \ postlink_cmds \ postinstall_cmds \ postuninstall_cmds \ finish_cmds \ sys_lib_search_path_spec \ configure_time_dlsearch_path \ configure_time_lt_sys_library_path; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done ac_aux_dir='$ac_aux_dir' # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi PACKAGE='$PACKAGE' VERSION='$VERSION' RM='$RM' ofile='$ofile' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; "src/util/Makefile") CONFIG_FILES="$CONFIG_FILES src/util/Makefile" ;; "src/usb_util/Makefile") CONFIG_FILES="$CONFIG_FILES src/usb_util/Makefile" ;; "src/base/Makefile") CONFIG_FILES="$CONFIG_FILES src/base/Makefile" ;; "src/vcp/Makefile") CONFIG_FILES="$CONFIG_FILES src/vcp/Makefile" ;; "src/dynvcp/Makefile") CONFIG_FILES="$CONFIG_FILES src/dynvcp/Makefile" ;; "src/sysfs/Makefile") CONFIG_FILES="$CONFIG_FILES src/sysfs/Makefile" ;; "src/i2c/Makefile") CONFIG_FILES="$CONFIG_FILES src/i2c/Makefile" ;; "src/usb/Makefile") CONFIG_FILES="$CONFIG_FILES src/usb/Makefile" ;; "src/ddc/Makefile") CONFIG_FILES="$CONFIG_FILES src/ddc/Makefile" ;; "src/dw/Makefile") CONFIG_FILES="$CONFIG_FILES src/dw/Makefile" ;; "src/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/test/Makefile" ;; "src/cmdline/Makefile") CONFIG_FILES="$CONFIG_FILES src/cmdline/Makefile" ;; "src/app_sysenv/Makefile") CONFIG_FILES="$CONFIG_FILES src/app_sysenv/Makefile" ;; "src/app_ddcutil/Makefile") CONFIG_FILES="$CONFIG_FILES src/app_ddcutil/Makefile" ;; "src/libmain/Makefile") CONFIG_FILES="$CONFIG_FILES src/libmain/Makefile" ;; "src/sample_clients/Makefile") CONFIG_FILES="$CONFIG_FILES src/sample_clients/Makefile" ;; "man/Makefile") CONFIG_FILES="$CONFIG_FILES man/Makefile" ;; "data/Makefile") CONFIG_FILES="$CONFIG_FILES data/Makefile" ;; "docs/Makefile") CONFIG_FILES="$CONFIG_FILES docs/Makefile" ;; "docs/doxygen/Makefile") CONFIG_FILES="$CONFIG_FILES docs/doxygen/Makefile" ;; "src/public/ddcutil_macros.h") CONFIG_FILES="$CONFIG_FILES src/public/ddcutil_macros.h" ;; "data/ddcutil.pc") CONFIG_FILES="$CONFIG_FILES data/ddcutil.pc" ;; "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; "docs/doxygen/doxyfile") CONFIG_FILES="$CONFIG_FILES docs/doxygen/doxyfile" ;; "docs/ddcutil-c-api") CONFIG_FILES="$CONFIG_FILES docs/ddcutil-c-api" ;; *) as_fn_error $? "invalid argument: '$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test ${CONFIG_FILES+y} || CONFIG_FILES=$config_files test ${CONFIG_HEADERS+y} || CONFIG_HEADERS=$config_headers test ${CONFIG_COMMANDS+y} || CONFIG_COMMANDS=$config_commands fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to '$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with './config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with './config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script 'defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag '$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain ':'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: '$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`printf "%s\n" "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is 'configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` printf "%s\n" "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 printf "%s\n" "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`printf "%s\n" "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac ac_MKDIR_P=$MKDIR_P case $MKDIR_P in [\\/$]* | ?:[\\/]* ) ;; */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 printf "%s\n" "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when '$srcdir' = '.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable 'datarootdir' which seems to be undefined. Please make sure it is defined" >&5 printf "%s\n" "$as_me: WARNING: $ac_file contains a reference to the variable 'datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { printf "%s\n" "/* $configure_input */" >&1 \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 printf "%s\n" "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else printf "%s\n" "/* $configure_input */" >&1 \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi # Compute "$ac_file"'s index in $config_headers. _am_arg="$ac_file" _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || $as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$_am_arg" : 'X\(//\)[^/]' \| \ X"$_am_arg" : 'X\(//\)$' \| \ X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X"$_am_arg" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'`/stamp-h$_am_stamp_count ;; :C) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 printf "%s\n" "$as_me: executing $ac_file commands" >&6;} ;; esac case $ac_file$ac_mode in "depfiles":C) test x"$AMDEP_TRUE" != x"" || { # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. # TODO: see whether this extra hack can be removed once we start # requiring Autoconf 2.70 or later. case $CONFIG_FILES in #( *\'*) : eval set x "$CONFIG_FILES" ;; #( *) : set x $CONFIG_FILES ;; #( *) : ;; esac shift # Used to flag and report bootstrapping failures. am_rc=0 for am_mf do # Strip MF so we end up with the name of the file. am_mf=`printf "%s\n" "$am_mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile which includes # dependency-tracking related rules and includes. # Grep'ing the whole file directly is not great: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. sed -n 's,^am--depfiles:.*,X,p' "$am_mf" | grep X >/dev/null 2>&1 \ || continue am_dirpart=`$as_dirname -- "$am_mf" || $as_expr X"$am_mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$am_mf" : 'X\(//\)[^/]' \| \ X"$am_mf" : 'X\(//\)$' \| \ X"$am_mf" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X"$am_mf" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` am_filepart=`$as_basename -- "$am_mf" || $as_expr X/"$am_mf" : '.*/\([^/][^/]*\)/*$' \| \ X"$am_mf" : 'X\(//\)$' \| \ X"$am_mf" : 'X\(/\)' \| . 2>/dev/null || printf "%s\n" X/"$am_mf" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` { echo "$as_me:$LINENO: cd "$am_dirpart" \ && sed -e '/# am--include-marker/d' "$am_filepart" \ | $MAKE -f - am--depfiles" >&5 (cd "$am_dirpart" \ && sed -e '/# am--include-marker/d' "$am_filepart" \ | $MAKE -f - am--depfiles) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } || am_rc=$? done if test $am_rc -ne 0; then { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "Something went wrong bootstrapping makefile fragments for automatic dependency tracking. If GNU make was not used, consider re-running the configure script with MAKE=\"gmake\" (or whatever is necessary). You can also try re-running configure with the '--disable-dependency-tracking' option to at least be able to build the package (albeit without support for automatic dependency tracking). See 'config.log' for more details" "$LINENO" 5; } fi { am_dirpart=; unset am_dirpart;} { am_filepart=; unset am_filepart;} { am_mf=; unset am_mf;} { am_rc=; unset am_rc;} rm -f conftest-deps.mk } ;; "libtool":C) # See if we are running on zsh, and set the options that allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}"; then setopt NO_GLOB_SUBST fi cfgfile=${ofile}T trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # Generated automatically by $as_me ($PACKAGE) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # Provide generalized library-building support services. # Written by Gordon Matzigkeit, 1996 # Copyright (C) 2014 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program or library that is built # using GNU Libtool, you may include this file under the same # distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # The names of the tagged configurations supported by this script. available_tags='' # Configured defaults for sys_lib_dlsearch_path munging. : \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"} # ### BEGIN LIBTOOL CONFIG # Which release of libtool.m4 was used? macro_version=$macro_version macro_revision=$macro_revision # Whether or not to build static libraries. build_old_libs=$enable_static # Whether or not to build shared libraries. build_libtool_libs=$enable_shared # What type of objects to build. pic_mode=$pic_mode # Whether or not to optimize for fast installation. fast_install=$enable_fast_install # Shared archive member basename,for filename based shared library versioning on AIX. shared_archive_member_spec=$shared_archive_member_spec # Shell to use when invoking shell scripts. SHELL=$lt_SHELL # An echo program that protects backslashes. ECHO=$lt_ECHO # The PATH separator for the build system. PATH_SEPARATOR=$lt_PATH_SEPARATOR # The host system. host_alias=$host_alias host=$host host_os=$host_os # The build system. build_alias=$build_alias build=$build build_os=$build_os # A sed program that does not truncate output. SED=$lt_SED # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="\$SED -e 1s/^X//" # A grep program that handles long lines. GREP=$lt_GREP # An ERE matcher. EGREP=$lt_EGREP # A literal string matcher. FGREP=$lt_FGREP # A BSD- or MS-compatible name lister. NM=$lt_NM # Whether we need soft or hard links. LN_S=$lt_LN_S # What is the maximum length of a command? max_cmd_len=$max_cmd_len # Object file suffix (normally "o"). objext=$ac_objext # Executable file suffix (normally ""). exeext=$exeext # whether the shell understands "unset". lt_unset=$lt_unset # turn spaces into newlines. SP2NL=$lt_lt_SP2NL # turn newlines into spaces. NL2SP=$lt_lt_NL2SP # convert \$build file names to \$host format. to_host_file_cmd=$lt_cv_to_host_file_cmd # convert \$build files to toolchain format. to_tool_file_cmd=$lt_cv_to_tool_file_cmd # A file(cmd) program that detects file types. FILECMD=$lt_FILECMD # An object symbol dumper. OBJDUMP=$lt_OBJDUMP # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method # Command to use when deplibs_check_method = "file_magic". file_magic_cmd=$lt_file_magic_cmd # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob=$lt_file_magic_glob # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob=$lt_want_nocaseglob # DLL creation program. DLLTOOL=$lt_DLLTOOL # Command to associate shared and link libraries. sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd # The archiver. AR=$lt_AR # Flags to create an archive (by configure). lt_ar_flags=$lt_ar_flags # Flags to create an archive. AR_FLAGS=\${ARFLAGS-"\$lt_ar_flags"} # How to feed a file listing to the archiver. archiver_list_spec=$lt_archiver_list_spec # A symbol stripping program. STRIP=$lt_STRIP # Commands used to install an old-style archive. RANLIB=$lt_RANLIB old_postinstall_cmds=$lt_old_postinstall_cmds old_postuninstall_cmds=$lt_old_postuninstall_cmds # Whether to use a lock for old archive extraction. lock_old_archive_extraction=$lock_old_archive_extraction # A C compiler. LTCC=$lt_CC # LTCC compiler flags. LTCFLAGS=$lt_CFLAGS # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl # Transform the output of nm into a list of symbols to manually relocate. global_symbol_to_import=$lt_lt_cv_sys_global_symbol_to_import # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix # The name lister interface. nm_interface=$lt_lt_cv_nm_interface # Specify filename containing input files for \$NM. nm_file_list_spec=$lt_nm_file_list_spec # The root where to search for dependent libraries,and where our libraries should be installed. lt_sysroot=$lt_sysroot # Command to truncate a binary pipe. lt_truncate_bin=$lt_lt_cv_truncate_bin # The name of the directory that contains temporary libtool files. objdir=$objdir # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=$MAGIC_CMD # Must we lock files when doing compilation? need_locks=$lt_need_locks # Manifest tool. MANIFEST_TOOL=$lt_MANIFEST_TOOL # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL=$lt_DSYMUTIL # Tool to change global to local symbols on Mac OS X. NMEDIT=$lt_NMEDIT # Tool to manipulate fat objects and archives on Mac OS X. LIPO=$lt_LIPO # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL=$lt_OTOOL # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64=$lt_OTOOL64 # Old archive suffix (normally "a"). libext=$libext # Shared library suffix (normally ".so"). shrext_cmds=$lt_shrext_cmds # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds=$lt_extract_expsyms_cmds # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink=$lt_variables_saved_for_relink # Do we need the "lib" prefix for modules? need_lib_prefix=$need_lib_prefix # Do we need a version for libraries? need_version=$need_version # Library versioning type. version_type=$version_type # Shared library runtime path variable. runpath_var=$runpath_var # Shared library path variable. shlibpath_var=$shlibpath_var # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=$shlibpath_overrides_runpath # Format of library name prefix. libname_spec=$lt_libname_spec # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec=$lt_library_names_spec # The coded name of the library, if different from the real name. soname_spec=$lt_soname_spec # Permission mode override for installation of shared libraries. install_override_mode=$lt_install_override_mode # Command to use after installation of a shared archive. postinstall_cmds=$lt_postinstall_cmds # Command to use after uninstallation of a shared archive. postuninstall_cmds=$lt_postuninstall_cmds # Commands used to finish a libtool library installation in a directory. finish_cmds=$lt_finish_cmds # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval=$lt_finish_eval # Whether we should hardcode library paths into libraries. hardcode_into_libs=$hardcode_into_libs # Compile-time system search path for libraries. sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Detected run-time system search path for libraries. sys_lib_dlsearch_path_spec=$lt_configure_time_dlsearch_path # Explicit LT_SYS_LIBRARY_PATH set during ./configure time. configure_time_lt_sys_library_path=$lt_configure_time_lt_sys_library_path # Whether dlopen is supported. dlopen_support=$enable_dlopen # Whether dlopen of programs is supported. dlopen_self=$enable_dlopen_self # Whether dlopen of statically linked programs is supported. dlopen_self_static=$enable_dlopen_self_static # Commands to strip libraries. old_striplib=$lt_old_striplib striplib=$lt_striplib # The linker used to build libraries. LD=$lt_LD # How to create reloadable object files. reload_flag=$lt_reload_flag reload_cmds=$lt_reload_cmds # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds # A language specific compiler. CC=$lt_compiler # Is the compiler the GNU compiler? with_gcc=$GCC # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds archive_expsym_cmds=$lt_archive_expsym_cmds # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds module_expsym_cmds=$lt_module_expsym_cmds # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator # Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \$shlibpath_var if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms # Symbols that must always be exported. include_expsyms=$lt_include_expsyms # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds # Specify filename containing input files. file_list_spec=$lt_file_list_spec # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action # ### END LIBTOOL CONFIG _LT_EOF cat <<'_LT_EOF' >> "$cfgfile" # ### BEGIN FUNCTIONS SHARED WITH CONFIGURE # func_munge_path_list VARIABLE PATH # ----------------------------------- # VARIABLE is name of variable containing _space_ separated list of # directories to be munged by the contents of PATH, which is string # having a format: # "DIR[:DIR]:" # string "DIR[ DIR]" will be prepended to VARIABLE # ":DIR[:DIR]" # string "DIR[ DIR]" will be appended to VARIABLE # "DIRP[:DIRP]::[DIRA:]DIRA" # string "DIRP[ DIRP]" will be prepended to VARIABLE and string # "DIRA[ DIRA]" will be appended to VARIABLE # "DIR[:DIR]" # VARIABLE will be replaced by "DIR[ DIR]" func_munge_path_list () { case x$2 in x) ;; *:) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\" ;; x:*) eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\" ;; *::*) eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\" eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\" ;; *) eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\" ;; esac } # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. func_cc_basename () { for cc_temp in $*""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` } # ### END FUNCTIONS SHARED WITH CONFIGURE _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test set != "${COLLECT_NAMES+set}"; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac ltmain=$ac_aux_dir/ltmain.sh # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? $SED '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ddcutil $VERSION version suffix: "dev" ============= libtool version ${LT_CURRENT}:${LT_REVISION}:${LT_AGE} prefix: ${prefix} exec_prefix: ${exec_prefix} libexecdir: ${libexecdir} bindir: ${bindir} libdir: ${libdir} datarootdir: ${datarootdir} datadir: ${datadir} docdir: ${docdir} mandir: ${mandir} includedir: ${includedir} pkgconfigdir: ${pkgconfigdir} required_packages: ${required_packages} enable_lib: ${enable_lib} enable_install_lib_only ${enable_install_lib_only} enable_build_timestamp ${enable_build_timestamp} enable_envcmds ${enable_envcmds} enable_udev ${enable_udev} enable_usb: ${enable_usb} enable_drm: ${enable_drm} enable_x11: ${enable_x11} enable_asan: ${enable_asan} enable_static_functions_visible: ${enable_static_functions_visible} Developer-only options: enable_targetbsd: ${enable_targetbsd} enable_doxygen: ${enable_doxygen} enable_failsim: ${enable_failsim} include_testcases: ${include_testcases} compiler: ${CC} CFLAGS: ${CFLAGS} CPPFLAGS: ${CPPFLAGS} LDFLAGS: ${LDFLAGS} " >&5 printf "%s\n" " ddcutil $VERSION version suffix: "dev" ============= libtool version ${LT_CURRENT}:${LT_REVISION}:${LT_AGE} prefix: ${prefix} exec_prefix: ${exec_prefix} libexecdir: ${libexecdir} bindir: ${bindir} libdir: ${libdir} datarootdir: ${datarootdir} datadir: ${datadir} docdir: ${docdir} mandir: ${mandir} includedir: ${includedir} pkgconfigdir: ${pkgconfigdir} required_packages: ${required_packages} enable_lib: ${enable_lib} enable_install_lib_only ${enable_install_lib_only} enable_build_timestamp ${enable_build_timestamp} enable_envcmds ${enable_envcmds} enable_udev ${enable_udev} enable_usb: ${enable_usb} enable_drm: ${enable_drm} enable_x11: ${enable_x11} enable_asan: ${enable_asan} enable_static_functions_visible: ${enable_static_functions_visible} Developer-only options: enable_targetbsd: ${enable_targetbsd} enable_doxygen: ${enable_doxygen} enable_failsim: ${enable_failsim} include_testcases: ${include_testcases} compiler: ${CC} CFLAGS: ${CFLAGS} CPPFLAGS: ${CPPFLAGS} LDFLAGS: ${LDFLAGS} " >&6; } ddcutil-2.2.0/configure.ac0000644000175000001440000007731414754250207011130 # # ddcutil autotools configure script # # Copyright (C) 2014-2025 Sanford Rockowitz # SPDX-License-Identifier: GPL-2.0-or-later dnl General notes: dnl - Macro names in comments are written in lower case to avoid processing as actual macros ### ### Initial Setup ### AC_PREREQ([2.69]) m4_define([ddcutil_major_version], [2]) m4_define([ddcutil_minor_version], [2]) m4_define([ddcutil_micro_version], [0]) dnl ddcutil_version_suffix does not begin with hyphen, e.g. "dev", not "-dev" m4_define([ddcutil_version_suffix], ["dev"]) # m4_ifelse(ddcutil_version_suffix,[], m4_define([ddcutil_version], [a]),define([ddcutil_version],[b])) dnl mf_define( [ddcutil_version], m4_format([%s.%s.%s%s],[ddcutil_major_version],[ddcutil_minor_version],[ddcutil_micro_version],[ddcutil_version_suffix]) m4_define([ddcutil_version], [ddcutil_major_version.ddcutil_minor_version.ddcutil_micro_version]) dnl m4_ifdef('ddcutil_version_suffix' ,m4_define([ddcutil_version], [ddcutil_major_version.ddcutil_minor_version.ddcutil_micro_version])) dnl It should be possible to define here the "fully qualified" version name, conditionally dnl containing the version suffix, but after hours of trying to get that to work (5/2021) dnl I gave up. It will be handled in the C code. dnl process command line args, perform initializations dnl sets among several output vars including PACKAGE_NAME, PACKAGE_VERSION, dnl PACKAGE_TARNAME (name of output package) dnl causes VERSION to be set in config.h AC_INIT([ddcutil],[ddcutil_version],[rockowitz@minsoft.com]) dnl define preprocessor symbols dnl was AC_DEFINE_UNQUOTED, but don't need extra handling? dnl symbol value set by comment AC_DEFINE( [VERSION_VMAJOR], [ ddcutil_major_version ], [ddcutil major version] ) AC_DEFINE( [VERSION_VMINOR], [ ddcutil_minor_version ], [ddcutil minor version] ) AC_DEFINE( [VERSION_VMICRO], [ ddcutil_micro_version ], [ddcutil micro version] ) AC_DEFINE( [VERSION_VSUFFIX],[ ddcutil_version_suffix ], [ddcutil version suffix] ) dnl substitute @PACKAGE_MAJOR@ etc. in Makefile.am with the value of the environment variable AC_SUBST( VERSION_VMAJOR, [ddcutil_major_version] ) AC_SUBST( VERSION_VMINOR, [ddcutil_minor_version] ) AC_SUBST( VERSION_VMICRO, [ddcutil_micro_version] ) AC_SUBST( VERSION_VSUFFIX, [ddcutil_version_suffix] ) AC_ARG_VAR(DBG, [Turn on script debugging messages(0/1)]) dnl AC_MSG_NOTICE([DBG = |$DBG|]) AM_CONDITIONAL(WARNINGS_ARE_ERRORS_COND, [test "x$ddcutil_version_suffix" != "x"] ) AS_IF( [test 0$DBG -ne 0], AC_MSG_NOTICE([debug messages enabled]), AC_MSG_NOTICE([debug messages disabled]) ) dnl reduce clutter, save files litmain.sh, config.guess, missing etc. here instead of top directory AC_CONFIG_AUX_DIR(config) dnl sanity check: verify a unique file in source directory: AC_CONFIG_SRCDIR([src/util/coredefs.h]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_FILES([ Makefile src/Makefile src/util/Makefile src/usb_util/Makefile src/base/Makefile src/vcp/Makefile src/dynvcp/Makefile src/sysfs/Makefile src/i2c/Makefile src/usb/Makefile src/ddc/Makefile src/dw/Makefile src/test/Makefile src/cmdline/Makefile src/app_sysenv/Makefile src/app_ddcutil/Makefile src/libmain/Makefile src/sample_clients/Makefile man/Makefile data/Makefile docs/Makefile docs/doxygen/Makefile src/public/ddcutil_macros.h data/ddcutil.pc ], ) dnl AC_CONFIG_FILES(package/upload_obsrpm, [chmod +x package/upload_obsrpm] ) dnl dnl AC_CONFIG_FILES(package/build_dpkg, [chmod +x package/build_dpkg] ) dnl dnl cannot chmod on build_dpkg, upload_obsrpm, since they will not exist within dpkg build environment dnl not working, why? # AC_DEFINE_UNQUOTED([DDCUTIL_MAJOR_VERSION], [$ddcutil_major_version], [ddcutil major version]) dnl Automake options to be applied to every Makefile.am in the tree: dnl The effect is as if each option were listed in AUTOMAKE_OPTIONS dnl removed -Werror from AM_INIT_AUTOMAKE to allow compilation to proceed dnl n. first option in our list is the required automake version AM_INIT_AUTOMAKE([1.14 -Wall -Wno-extra-portability foreign subdir-objects ]) dnl alternatively, add "silent-rules" to AM_INIT_AUTOMAKE dnl Eclipse warns that as of 2.68, AM_SILENT_RULES takes 0 arguments dnl but in 2.69 it only defaults to silent with argument "yes" dnl with "yes" arg, silent rules is the default AM_SILENT_RULES([yes]) AM_PROG_AR dnl explicitly initialize pkg-config in case first call to pkg_check_modules is within an if test: PKG_PROG_PKG_CONFIG required_packages= dnl Determines C compiler to use, sets output variable cc, ac_cv_prog_cc_c89 dnl Called by other macros, but must be called explicitly at top level for proper initialization # AC_PROG_C99 for CENTOS 7 in OBS, EOL 6/30/2024 m4_version_prereq(2.70, [AC_PROG_CC], [AC_PROG_CC_C99]) dnl AC_PROG_LIBTOOL, AM_PROG_LIBTOOL are deprecated names for older versions of LT_INIT dnl adds support for --enable/disable -static/shared, -with/without-pic configure flags LT_INIT([disable-static]) dnl Automatically update libtool script if it becomes out of date: AC_SUBST([LIBTOOL_DEPS]) ### ### Version specification ### # libtool versioning - applies to libddcutil # # See http://sources.redhat.com/autobook/autobook/autobook_91.html#SEC91 for details # # increment; # CURRENT If the API or ABI interface has changed (reset REVISION to 0) # REVISION If the API and ABI remains the same, but bugs are fixed. # AGE backward compatibility (i.e. number of releases prior to current # for which this release is backward compatible) # # Alternative comments: # # Here are a set of rules to help you update your library version # information: # # 1. Start with version information of `0:0:0' for each libtool library. # 2. Update the version information only immediately before a public # release of your software. More frequent updates are unnecessary, and # only guarantee that the current interface number gets larger faster. # 3. If the library source code has changed at all since the last update, # then increment revision (`c:r:a' becomes `c:r+1:a'). # 4. If any interfaces have been added, removed, or changed since the last # update, increment current, and set revision to 0. # 5. If any interfaces have been added since the last public release, then # increment age. # 6. If any interfaces have been removed since the last public release, # then set age to 0. # # The LT_... values are used to create the argument for the --version-info parm. # Note that this parm is processed differently depending on operating system. # For Linux, the second and third fields in the shared object name's suffix are # taken directly from the command line, while the first is calculated as current-age. # For example, if LT_CURRENT=13, LT_REVISION=4, LT_AGE=4, the geneated parm # is --version-info "13:1:4", and the generated SO name looks like xxx.so.9.4.1 dnl 7/29/19 first use, LT_CURRENT set to 1 LT_CURRENT=7 LT_REVISION=0 LT_AGE=2 AC_SUBST(LT_CURRENT) AC_SUBST(LT_REVISION) AC_SUBST(LT_AGE) ### ### Recognize command options for configure script ### ### ### Documented options ### AC_MSG_NOTICE( [Checking configure command options...] ) dnl # residual setting so that Makefile.am files don't break adl_header_dir="" AM_CONDITIONAL([HAVE_ADL_COND], [test -n "$adl_header_dir"] ) dnl *** configure option: --enable-lib AC_ARG_ENABLE([lib], [ AS_HELP_STRING([--enable-lib=@<:@yes/no@:>@], [Build shared library and clients@<:@default=yes@:>@] )], [enable_lib=${enableval}], [enable_lib=yes] ) dnl Set flag for automake.am: AM_CONDITIONAL([ENABLE_SHARED_LIB_COND], [test "x$enable_lib" = "xyes"] ) dnl ENABLE_SHARED_LIB_FLAG used in package/ddcutil_spec.in AS_IF([test "x$enable_lib" = "xyes"], AC_MSG_NOTICE( [lib... enabled] ) AC_SUBST(ENABLE_SHARED_LIB_FLAG, 1) AC_DEFINE( [BUILD_SHARED_LIB], [1], [If defined, buid shared library.]) , AC_MSG_NOTICE( [lib... disabled] ) AC_SUBST(ENABLE_SHARED_LIB_FLAG, 0) ) dnl *** configure option: --install-lib-only AC_ARG_ENABLE([install-lib-only], [ AS_HELP_STRING([--enable-install-lib-only=@<:@yes/no@:>@], [Install only shared shared librarys@<:@default=no@:>@] )], [enable_install_lib_only=${enableval}], [enable_install_lib_only=no] ) AM_CONDITIONAL([INSTALL_LIB_ONLY_COND], [test "x$enable_install_lib_only" = "xyes"] ) AS_IF([test "x$enable_install_lib_only" = "xyes"], AC_MSG_NOTICE( [install_lib_only... enabled] ) , AC_MSG_NOTICE( [install_lib_only... disabled] ) ) AS_IF([test "x$enable_lib" = "xno" -a "x$enable_install_lib_only" = "xyes" ], AC_MSG_ERROR( [--disable-lib contradicts --enable-install-lib-only] ) ) dnl *** configure option: --enable-build-timestamp AC_ARG_ENABLE([build-timestamp], [ AS_HELP_STRING([--enable-build-timestamp=@<:@yes/no@:>@], [Insert build date/time in executables@<:@default=yes@:>@] )], [enable_build_timestamp=${enableval}], [enable_build_timestamp=yes] ) dnl Set flag for automake.am: AM_CONDITIONAL([ENABLE_BUILD_TIMESTAMP_COND], [test "x$enable_build_timestamp" = "xyes"] ) AS_IF([test "x$enable_build_timestamp" = "xyes"], AC_MSG_NOTICE( [build-timestamp... enabled] ) AC_SUBST(ENABLE_BUILD_TIMESTAMP_FLAG, 1) AC_DEFINE( [BUILD_TIMESTAMP], [1], [If defined, include build date/time in executables.]) , AC_MSG_NOTICE( [build-timestamp... disabled] ) AC_SUBST(ENABLE_BUILD_TIMESTAMP_FLAG, 0) ) dnl *** configure option: --enable-envcmds AC_ARG_ENABLE([envcmds], [ AS_HELP_STRING([--enable-envcmds=@<:@yes/no@:>@], [Include environment and usbenvironment@<:@default=yes@:>@] )], [enable_envcmds=${enableval}], [enable_envcmds=yes] ) AS_IF([test "x$enable_envcmds" = "xyes"], AC_MSG_NOTICE( [envcmds... enabled (provisional) ] ) , AC_MSG_NOTICE( [envcmds... disabled] ) ) dnl *** configure option: --enable-udev AC_ARG_ENABLE([udev], [ AS_HELP_STRING([--enable-udev=@<:@yes/no@:>@], [Use UDEV@<:@default=yes@:>@] )], [enable_udev=${enableval}], [enable_udev=yes] ) dnl AS_IF([test "x$enable_udev" = "xyes"], dnl AC_MSG_NOTICE( [udev... enabled (provisional) ] ) dnl , dnl AC_MSG_NOTICE( [udev... disabled] ) dnl ) dnl *** configure option: --enable-usb AC_ARG_ENABLE([usb], [ AS_HELP_STRING( [--enable-usb=@<:@yes/no@:>@], [Support USB connected displays@<:@default=yes@:>@] )], [enable_usb=${enableval}], [enable_usb=yes] ) AS_IF([test "x$enable_usb" = "xyes"], AC_MSG_NOTICE( [usb... enabled (provisional) ] ) , AC_MSG_NOTICE( [usb... disabled] ) ) dnl *** configure option: --enable-drm AC_ARG_ENABLE([drm], [ AS_HELP_STRING( [--enable-drm=@<:@yes/no@:>@], [Use DRM@<:@default=yes@:>@] )], [enable_drm=${enableval}], [enable_drm=yes] ) AS_IF([test "x$enable_drm" = "xyes"], AC_MSG_NOTICE( [drm... enabled (provisional) ] ) , AC_MSG_NOTICE( [drm... disabled] ) ) dnl *** configure option: --enable-x11 AC_ARG_ENABLE([x11], [ AS_HELP_STRING( [--enable-x11=@<:@yes/no@:>@], [Use X11@<:@default=yes@:>@] )], [enable_x11=${enableval}], [enable_x11=yes] ) # enable_x11=no # AS_IF([test "x$enable_x11" = "xyes"], # AC_MSG_NOTICE( [x11... Deprecated option ignored] ), # AC_MSG_NOTICE( [x11... disabled] ) # ) AS_IF([test "x$enable_x11" = "xyes"], AC_MSG_NOTICE( [x11... enabled (provisional) ] ) , AC_MSG_NOTICE( [x11... disabled] ) ) dnl *** configure option: --enable-static-functions-visible AC_ARG_ENABLE([static-functions-visible], [ AS_HELP_STRING( [--enable-static-functions-visible=@<:@no/yes@:>@], [Remove static qualifier from functions@<:@default=no@:>@] )], [enable_static_functions_visible=${enableval}], [enable_static_functions_visible=no] ) AM_CONDITIONAL([STATIC_FUNCTIONS_VISIBLE_COND], [test "x$enable_static_functions_visible" = "xyes"] ) AS_IF( [test "x$enable_static_functions_visible" = "xyes"], AC_DEFINE( [STATIC_FUNCTIONS_VISIBLE], [1], [If defined, remove static qualifier from function declarations and definitions.]) AC_MSG_NOTICE( [static_functions_visible... enabled] ) , AC_MSG_NOTICE( [static_functions_visible... disabled] ) ) dnl *** configure option: --enable-asan AC_ARG_ENABLE([asan], [ AS_HELP_STRING( [--enable-asan=@<:@no/yes@:>@], [Build for asan (address sanitizer)@<:@default=no@:>@] )], [enable_asan=${enableval}], [enable_asan=no] ) AM_CONDITIONAL([ASAN_COND], [test "x$enable_asan" = "xyes"] ) AS_IF( [test "x$enable_asan" = "xyes"], AC_DEFINE( [WITH_ASAN], [1], [If defined, building for Asan instrumentation.]) AC_MSG_NOTICE( [asan... enabled] ) , AC_MSG_NOTICE( [asan... disabled] ) ) dnl dnl *** configure option: --enable-trace dnl AC_ARG_ENABLE([trace], dnl [ AS_HELP_STRING( [--enable-trace=@<:@yes/no@:>@], [Output trace messages@<:@default=yes@:>@] )], dnl [enable_trace=${enableval}], dnl [enable_trace=yes] ) dnl AS_IF([test "x$enable_trace" = "xyes"], dnl AC_MSG_NOTICE( [trace... enabled] ) dnl AC_DEFINE([ENABLE_TRACE], [1], [If defined, enable trace messages.]) dnl , dnl AC_MSG_NOTICE( [TRACE... disabled] ) dnl ) dnl *** configure option: --enable-targetbsd AC_ARG_ENABLE([targetbsd], [ AS_HELP_STRING([--enable-targetbsd=@<:@no/yes@:>@], [Build for BSD@<:@default=no@:>@ (Developer-only)] )], [enable_targetbsd=${enableval}], [enable_targetbsd=no] ) dnl *** configure option: --enable-doxygen AC_ARG_ENABLE([doxygen], [ AS_HELP_STRING( [--enable-doxygen=@<:@no/yes@:>@], [Build API documentation using Doxygen (if it is installed)@<:@default=no@:>@ (Developer-only)] )], [enable_doxygen=${enableval}], [enable_doxygen=no] ) AM_CONDITIONAL([ENABLE_DOXYGEN_COND], [test "x$enable_doxygen" = "xyes"] ) AS_IF([test "x$enable_doxygen" = "xyes"], AC_MSG_NOTICE( [doxygen... enabled] ) , AC_MSG_NOTICE( [doxygen... disabled] ) ) ### ### Resolve choices for public options ### AC_MSG_NOTICE( [Resolving options...] ) dnl --enable-targetbsd => --disable-envcmds, --disable-usb, --disable-udev AS_IF([test "x$enable_targetbsd" = "xyes" -a "x$enable_envcmds" = "xyes" ], [ AC_MSG_NOTICE( [--enable-targetbsd forces --disable-envcmds] ) enable_envcmds=no ] ) AS_IF([test "x$enable_targetbsd" = "xyes" -a "x$enable_udev" = "xyes" ], [ AC_MSG_NOTICE( [--enable-targetbsd forces --disable-udev] ) enable_udev=no ] ) AS_IF([test "x$enable_targetbsd" = "xyes" -a "x$enable_usb" = "xyes" ], [ AC_MSG_NOTICE( [--enable-targetbsd forces --disable-usb] ) enable_usb=no ] ) AS_IF([test "x$enable_udev" != "xyes" -a "x$enable_usb" = "xyes" ], [ AC_MSG_NOTICE( [--disable-udev forces --disable-usb] ) enable_usb=no ] ) # --enable-install-lib-only => --disable-envcmds AS_IF([test "x$enable_install_lib_only" = "xyes" -a "x$enable_envcmds" = "xyes" ], [ AC_MSG_NOTICE( [--enable-install-lib-only forces --disable-envcmds] ) enable_envcmds=no ] ) ### ### Report resolved options and set conditionals, substitutions, and defines ### AM_CONDITIONAL([ENABLE_TARGETBSD_COND], [test "x$enable_targetbsd" = "xyes"] ) AS_IF([test "x$enable_targetbsd" = "xyes"], AC_MSG_NOTICE( [targetbsd... enabled] ) AC_DEFINE( [TARGET_BSD], [1], [If defined, building for BSD.]) AC_SUBST(ENABLE_TARGETBSD_FLAG, 1) , AC_MSG_NOTICE( [targetbsd... disabled] ) AC_SUBST(ENABLE_TARGETBSD_FLAG, 0) AC_DEFINE( [TARGET_LINUX], [1], [If defined, building for Linux.]) ) AM_CONDITIONAL([ENABLE_ENVCMDS_COND], [test "x$enable_envcmds" = "xyes"] ) AS_IF([test "x$enable_envcmds" = "xyes"], AC_MSG_NOTICE( [envcmds... enabled] ) AC_DEFINE( [ENABLE_ENVCMDS], [1], [If defined, enable environment commands.]) AC_SUBST(ENABLE_ENVCMDS_FLAG, 1) , AC_MSG_NOTICE( [envcmds... disabled] ) AC_SUBST(ENABLE_ENVCMDS_FLAG, 0) ) AM_CONDITIONAL([ENABLE_UDEV_COND], [test "x$enable_udev" = "xyes"] ) AS_IF([test "x$enable_udev" = "xyes"], AC_MSG_NOTICE( [udev... enabled] ) AC_DEFINE( [ENABLE_UDEV], [1], [If defined, use UDEV.]) AC_SUBST(ENABLE_UDEV_FLAG, 1) , AC_MSG_NOTICE( [udev... disabled] ) AC_SUBST(ENABLE_UDEV_FLAG, 0) ) AM_CONDITIONAL([ENABLE_USB_COND], [test "x$enable_usb" = "xyes"] ) AS_IF([test "x$enable_usb" = "xyes"], AC_DEFINE( [ENABLE_USB], [1], [If defined, enable USB communication.]) AC_SUBST( ENABLE_USB_FLAG, [1] ) AC_MSG_NOTICE( [usb... enabled] ) , AC_SUBST( ENABLE_USB_FLAG, [0] ) AC_MSG_NOTICE( [usb... disabled] ) ) AS_IF([test "x$enable_x11" = "xyes"], AC_MSG_NOTICE( [x11... enabled] ) , AC_MSG_NOTICE( [x11... disabled] ) ) ### Private options dnl dnl *** configure option: --enable-yaml dnl AC_ARG_ENABLE([yaml], dnl [ AS_HELP_STRING( [--enable-yaml=@<:@no/yes@:>@], [Enable YAML for external file parsing @<:@default=no@:>@] )], dnl [enable_yaml=${enableval}], dnl [enable_yaml=no] ) dnl AM_CONDITIONAL([ENABLE_YAML_COND], [test "x$enable_yaml" = "xyes"] ) dnl AS_IF([test "x$enable_yaml" = "xyes"], dnl AC_DEFINE( [ENABLE_YAML], [1], [Enable YAML for parsing.]) dnl AC_MSG_NOTICE( [yaml... enabled] ) dnl , dnl AC_MSG_NOTICE( [yaml... disabled] ) dnl ) dnl *** configure option: --enable-testcases AC_ARG_ENABLE([testcases], [ AS_HELP_STRING( [--enable-testcases=@<:@no/yes@:>@], [Include test cases @<:@default=no@:>@] (Developer-only) )], [include_testcases=${enableval}], [include_testcases=no] ) AM_CONDITIONAL([INCLUDE_TESTCASES_COND], [test "x$include_testcases" = "xyes"] ) AS_IF([test "x$include_testcases" = "xyes"], AC_DEFINE( [INCLUDE_TESTCASES], [1], [If defined, build with test cases.]) AC_MSG_NOTICE( [testcases... enabled] ) , AC_MSG_NOTICE( [testcases... disabled] ) ) dnl *** configure option: --enable-callgraph AC_ARG_ENABLE([callgraph], [ AS_HELP_STRING( [--enable-callgraph=@<:@no/yes@:>@], [Create .expand files for static call graph@<:@default=no@:>@] (Developer-only) )], [enable_callgraph=${enableval}], [enable_callgraph=no] ) AM_CONDITIONAL([ENABLE_CALLGRAPH_COND], [test "x$enable_callgraph" = "xyes"] ) AS_IF([test "x$enable_callgraph" = "xyes"], AC_MSG_NOTICE( [callgraph... enabled] ), AC_MSG_NOTICE( [callgraph... disabled] ) ) dnl *** configure option: --enable-failsim AC_ARG_ENABLE([failsim], [ AS_HELP_STRING( [--enable-failsim=@<:@no/yes@:>@], [Build with failure simulation@<:@default=no@:>@ (Developer-only)] )], [enable_failsim=${enableval}], [enable_failsim=no] ) AM_CONDITIONAL([ENABLE_FAILSIM_COND], [test "x$enable_failsim" = "xyes"] ) AS_IF( [test "x$enable_failsim" = "xyes"], AC_DEFINE( [ENABLE_FAILSIM], [1], [If defined, enable failsim.]) AC_MSG_NOTICE( [failsim..... enabled] ) , AC_MSG_NOTICE( [failsim..... disabled] ) ) dnl *** configure option: --enable-force-suse AC_ARG_ENABLE([force-suse], [ AS_HELP_STRING( [--enable-force-suse=@<:@no/yes@:>@], [Force SUSE target directories@<:@default=no@:>@ (Developer-only)] )], [enable_force_suse=${enableval}], [enable_force_suse=no] ) AM_CONDITIONAL([ENABLE_FORCE_SUSE_COND], [test "x$enable_force_suse" = "xyes"] ) AS_IF( [test "x$enable_force_suse" = "xyes"], AC_DEFINE( [ENABLE_FORCE_SUSE], [1], [If defined, force SUSE target directories.]) AC_MSG_NOTICE( [force-suse....enabled] ) , AC_MSG_NOTICE( [force-suse....disabled] ) ) dnl Note to self: use autoheader to regenerate config.h.in whenever new defines added ### ### Checks for typedefs, structures, and compiler characteristics. ### AC_CHECK_HEADER_STDBOOL AC_C_INLINE AC_C_BIGENDIAN AC_TYPE_SIZE_T AC_TYPE_SSIZE_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT8_T ### ### Checks for standard library functions. ### AC_FUNC_MALLOC AC_FUNC_REALLOC AC_FUNC_STRERROR_R AC_CHECK_FUNCS([clock_gettime memset nl_langinfo stpcpy strchr strdup strerror strrchr strtol]) dnl The dlopen() function is in the C library for *BSD and in dnl libdl on GLIBC-based systems AC_SEARCH_LIBS([dlopen], [dl dld], [], [ AC_MSG_ERROR([unable to find the dlopen() function]) ]) ### ### Checks for header files. ### AC_CHECK_HEADERS([fcntl.h langinfo.h libintl.h limits.h stdint.h stdlib.h string.h sys/ioctl.h termios.h unistd.h wchar.h dlfcn.h execinfo.h]) dnl i2c-dev.h is in linux-headers dnl i2c-dev.h not found: dnl AC_CHECK_HEADERS([i2c-dev.h]) dnl dnl libi2c and libi2c-dev have no .pc files. Check for header file instead. dnl AC_CHECK_HEADER( [i2c/smbus.h], dnl AC_MSG_NOTICE( [header file i2c/smbus.h found.] ), dnl AC_MSG_ERROR( [libi2c development package (e.g. libi2c-dev, name varies by distribution) >= 4.0 required.] ) dnl ) ### ### Required library tests ### dnl Notes on pkg_check_modules: dnl 1) appends to xxx_CFLAGS and xxx_LIBS the output of pkg-config --cflags|--libs dnl 2) if no action-if-false branch defined, pkg_check_modules terminates execution if not found dnl 9/2017: need >= 2.32 for g_thread_...() functions PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.40) required_packages="$required_packages glib-2.0 >= 2.40" PKG_CHECK_MODULES(JANSSON, jansson >= 2.0) required_packages="$required_packages jansson >= 2.0" AS_IF( [test "x$enable_udev" = "xyes" ], [ PKG_CHECK_MODULES(UDEV, libudev, [ libudev_found=1], [ libudev_found=0 AC_MSG_NOTICE( [The package providing libudev.h varies by Linux distribution and release.] ) AC_MSG_NOTICE( [It may be a udev specific package, e.g. libudev-dev, libudev-devel] ) AC_MSG_NOTICE( [or it may be part of systemd, e.g systemd-devel] ) AC_MSG_ERROR( [libudev not found] ) ] ) ] , ) dnl required_packages="$required_packages xrandr x11" dnl how to handle libudev? punt for now ### ### Optional library tests ### dnl TODO: use consistent pattern ### libusb dnl know that 1.0.8 fails, 1.0.20 works AS_IF([test "x$enable_usb" = "xyes"], [ PKG_CHECK_MODULES(LIBUSB, libusb-1.0 >= 1.0.15, [libusb_found=yes] ) ], [ AC_MSG_NOTICE( [usb disabled, not checking for libusb] ) ] ) dnl Logically, these debug messages belong within the $enable_usb test, but the dnl nested brackests make the code hard to read. It's LISP all over again. AS_IF( [test 0$DBG -ne 0], [ AC_MSG_NOTICE( [LIBUSB_CFLAGS: $LIBUSB_CFLAGS] ) AC_MSG_NOTICE( [LIBUSB_LIBS: $LIBUSB_LIBS] ) ]) ### libdrm AS_IF([test "x$enable_drm" = "xyes"], [ PKG_CHECK_MODULES(LIBDRM, libdrm >= 2.4.67, [libdrm_found=yes], [libdrm_found=no AC_MSG_WARN( [libdrm >= 2.4.67 not found. Forcing --disable-drm]) enable_drm=no ] ) ], [ AC_MSG_NOTICE( [drm disabled, not checking for libdrm] ) ] ) AM_CONDITIONAL([USE_LIBDRM_COND], [test "x$enable_drm" = "xyes"] ) AS_IF([test "x$enable_drm" = "xyes"], AC_DEFINE([USE_LIBDRM], [1], [Use libdrm]) AC_MSG_NOTICE( [drm... enabled] ) , AC_MSG_NOTICE( [drm... disabled] ) ) AS_IF( [test 0$DBG -ne 0], [ AC_MSG_NOTICE( [LIBDRM_CFLAGS: $LIBDRM_CFLAGS] ) AC_MSG_NOTICE( [LIBDRM_LIBS: $LIBDRM_LIBS] ) ]) dnl ### libyaml dnl dnl PKG_CHECK_MODULES(YAML, yaml-0.1) dnl dnl AS_IF([test "x$enable_yaml" = "xyes"], dnl [ PKG_CHECK_MODULES(YAML, yaml-0.1, dnl [libyaml_found=yes], dnl [libyaml_found=no dnl AC_MSG_WARN( [yaml-0.1 not found. Forcing --disable-yaml]) dnl enable_yaml=no dnl ] dnl ) dnl ], dnl [ AC_MSG_NOTICE( [yaml disabled, not checking for libyaml] ) ] dnl ) dnl dnl AM_CONDITIONAL([ENABLE_YAML_COND], [test "x$enable_yaml" = "xyes"] ) dnl AS_IF([test "x$enable_yaml" = "xyes"], dnl AC_DEFINE([ENABLE_YAML], [1], [Use yaml]) dnl AC_MSG_NOTICE( [yaml... enabled] ) dnl , dnl AC_MSG_NOTICE( [yaml... disabled] ) dnl ) dnl dnl AS_IF( [test 0$DBG -ne 0], dnl [ dnl AC_MSG_NOTICE( [YAML_CFLAGS: $YAML_CFLAGS] ) dnl AC_MSG_NOTICE( [YAML_LIBS: $YAML_LIBS] ) dnl ]) ### X11 dnl Duplicate of next section? AS_IF([test "x$enable_x11" = "xyes"], [ PKG_CHECK_MODULES(LIBX11, x11) PKG_CHECK_MODULES(XRANDR, xrandr) PKG_CHECK_MODULES(XEXT, xext) ]) AM_CONDITIONAL([USE_X11_COND], [test "x$enable_x11" = "xyes"] ) AS_IF([test "x$enable_x11" = "xyes"], AC_DEFINE([USE_X11], [1], [Use X11]) AC_MSG_NOTICE( [x11... enabled1] ) , AC_MSG_NOTICE( [x11... disabled1] ) ) dnl Note cflags and libs, but don't need to use in makefiles AS_IF( [test 0$DBG -ne 0], [ AC_MSG_NOTICE( [LIBX11_CFLAGS: $LIBX11_CFLAGS] ) AC_MSG_NOTICE( [LIBX11_LIBS: $LIBX11_LIBS] ) ]) ### DOXYGEN dnl AC_MSG_NOTICE([Start of DOXYGEN]) dnl AS_IF( [test "x$enable_doxygen" = "xyes"], dnl AC_MSG_NOTICE( [doxygen... enabled] ) dnl , dnl AC_MSG_NOTICE( [doxygen... disabled] ) dnl ) AS_IF([test "x$enable_doxygen" = "xyes"], [ dnl checks for doxygen program, sets or uses environment variable DOXYGEN AC_MSG_NOTICE([Checking for Doxygen...]) FLM_PROG_TRY_DOXYGEN AS_IF( [test -n $DOXYGEN], [ AC_MSG_NOTICE([Calling dx_init_doxygen...]) DX_PDF_FEATURE(ON) DX_HTML_FEATURE(ON) DX_INIT_DOXYGEN(ddcutil) AS_IF( [test 0$DBG -ne 0], [ AC_MSG_NOTICE([Set by dx_init_doxygen:]) AC_MSG_NOTICE([ DOXYGEN: $DOXYGEN ]) AC_MSG_NOTICE([ dx_DOT_FEATURE: $DX_DOT_FEATURE ]) AC_MSG_NOTICE([ dx_FEATURE_doc $DX_FEATURE_doc ]) AC_MSG_NOTICE([ dx_DOXYGEN_FEATURE: $DX_DOXYGEN_FEATURE ]) AC_MSG_NOTICE([ dx_HTML_FEATURE: $DX_HTML_FEATURE ]) AC_MSG_NOTICE([ dx_FLAG_html: $DX_FLAG_HTML ]) AC_MSG_NOTICE([ dx_PDF_FEATURE: $DX_PDF_FEATURE ]) AC_MSG_NOTICE([ DX_PROJECT: $DX_PROJECT ]) AC_MSG_NOTICE([ DX_CONFIG: $DX_CONFIG ]) AC_MSG_NOTICE([ DX_DOCDIR: $DX_DOCDIR ]) ]) AC_CONFIG_FILES( [docs/doxygen/doxyfile] ) ] , [ AC_MSG_NOTICE([doxygen not found]) enable_doxygen=no ] ) ] , [ AC_MSG_NOTICE([doxygen disabled, not checking for Doxygen]) ] ) dnl AC_MSG_NOTICE([enable_doxygen = ${enable_doxygen}]) dnl AM_CONDITIONAL( [HAVE_DOXYGEN], [test -n "$DOXYGEN"] ) dnl AM_CONDITIONAL( [USE_DOXYGEN], [test -n "$DOXYGEN" -a "x$enable_doxygen" = "xyes"]) AM_CONDITIONAL( [USE_DOXYGEN], [test "x$enable_doxygen" = "xyes"]) AM_COND_IF([USE_DOXYGEN], AC_MSG_NOTICE([USE_DOXYGEN is set]) , AC_MSG_NOTICE([USE_DOXYGEN not set]) ) ### DOC-BASE dnl n. doc-base is Debian specific dnl doc-base does not have pc file. AC_CHECK_PROGS( [DOCBASE_INSTALL_DOCS], [install-docs]) AS_IF( [test -n "$DOCBASE_INSTALL_DOCS"], AC_MSG_NOTICE([doc-base execuable found]) AC_CONFIG_FILES([docs/ddcutil-c-api]), AC_MSG_WARN([doc-base not installed - continuing without doc-base support]) ) AM_CONDITIONAL( [HAVE_DOCBASE], [test -n "$DOCBASE_INSTALL_DOCS"]) ### Library AS_IF([test "x$enable_lib" = "xyes"], [ PKG_CHECK_MODULES(ZLIB, zlib) ], ) AS_IF( [test "x$enable_asan" = "xyes"], [ required_packages="asan $required_packages" # has no effect on $CFLAGS CFLAGS="$CFLAGS -fsanitize=address" CFLAGS="$CFLAGS -fsanitize-address-use-after-scope -fno-omit-frame-pointer" ]) dnl AC_MSG_NOTICE([======================== required_packages: $required_packages]) AC_SUBST(REQUIRED_PACKAGES,$required_packages) ### Opsys variability dnl Fails: if building in OBS, SUSE is in /proc/version, even when building for Fedora dnl TODO: do not modify if explicitly set dnl AC_MSG_NOTICE([Original docdir: ${docdir}]) dnl AS_IF( [ grep SUSE /proc/version ], [ dnl AC_MSG_NOTICE( [IS SUSE]) dnl docdir=\${datarootdir}/doc/packages/\${PACKAGE_TARNAME} dnl ], [ dnl AC_MSG_NOTICE( [NOT SUSE] ) dnl ] ) dnl AC_MSG_NOTICE([======> Tests for SUSE target:]) dnl test using [ grep SUSE /proc/version ] dnl always tests true on OBS, i.e reports the OS on which the build system is running, not the target os dnl test using [ ls -d /usr/share/doc/packages ] dnl always tests true on OBS dnl test using [test "x$enable_force_suse" = "xyes"], i.e. enable-force_suse parm passed to configure dnl works dnl test using [ grep suse /etc/os-release ] dnl successfully detects target OS when run on OBS dnl test using [lsb-release -i | grep SUSE ] dnl on OBS, command not found AC_MSG_CHECKING( [target OS using /etc/os-release] ) AS_IF( [ grep suse /etc/os-release > /dev/null], [ AC_MSG_RESULT( [target is SUSE]) docdir=\${datarootdir}/doc/packages/\${PACKAGE_TARNAME} AC_MSG_NOTICE( [..Forcing docdir to ${docdir}] ) ], [ AC_MSG_RESULT( [target is not SUSE ] ) ] ) ### ### Generate output ### dnl called once at end of configure.ac, generates and runs config.status AC_OUTPUT dnl a brief summary AC_MSG_RESULT([ ddcutil $VERSION version suffix: ddcutil_version_suffix ============= libtool version ${LT_CURRENT}:${LT_REVISION}:${LT_AGE} prefix: ${prefix} exec_prefix: ${exec_prefix} libexecdir: ${libexecdir} bindir: ${bindir} libdir: ${libdir} datarootdir: ${datarootdir} datadir: ${datadir} docdir: ${docdir} mandir: ${mandir} includedir: ${includedir} pkgconfigdir: ${pkgconfigdir} required_packages: ${required_packages} enable_lib: ${enable_lib} enable_install_lib_only ${enable_install_lib_only} enable_build_timestamp ${enable_build_timestamp} enable_envcmds ${enable_envcmds} enable_udev ${enable_udev} enable_usb: ${enable_usb} enable_drm: ${enable_drm} enable_x11: ${enable_x11} dnl enable_trace: ${enable_trace} enable_asan: ${enable_asan} enable_static_functions_visible: ${enable_static_functions_visible} Developer-only options: enable_targetbsd: ${enable_targetbsd} enable_doxygen: ${enable_doxygen} enable_failsim: ${enable_failsim} include_testcases: ${include_testcases} compiler: ${CC} CFLAGS: ${CFLAGS} CPPFLAGS: ${CPPFLAGS} LDFLAGS: ${LDFLAGS} ]) dnl cat config.h ddcutil-2.2.0/aclocal.m40000664000175000001440000016264714754576143010522 # generated automatically by aclocal 1.16.5 -*- Autoconf -*- # Copyright (C) 1996-2021 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.72],, [m4_warning([this file was generated for autoconf 2.72. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically 'autoreconf'.])]) # pkg.m4 - Macros to locate and use pkg-config. -*- Autoconf -*- # serial 12 (pkg-config-0.29.2) dnl Copyright © 2004 Scott James Remnant . dnl Copyright © 2012-2015 Dan Nicholson dnl dnl This program is free software; you can redistribute it and/or modify dnl it under the terms of the GNU General Public License as published by dnl the Free Software Foundation; either version 2 of the License, or dnl (at your option) any later version. dnl dnl This program is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl General Public License for more details. dnl dnl You should have received a copy of the GNU General Public License dnl along with this program; if not, write to the Free Software dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA dnl 02111-1307, USA. dnl dnl As a special exception to the GNU General Public License, if you dnl distribute this file as part of a program that contains a dnl configuration script generated by Autoconf, you may include it under dnl the same distribution terms that you use for the rest of that dnl program. dnl PKG_PREREQ(MIN-VERSION) dnl ----------------------- dnl Since: 0.29 dnl dnl Verify that the version of the pkg-config macros are at least dnl MIN-VERSION. Unlike PKG_PROG_PKG_CONFIG, which checks the user's dnl installed version of pkg-config, this checks the developer's version dnl of pkg.m4 when generating configure. dnl dnl To ensure that this macro is defined, also add: dnl m4_ifndef([PKG_PREREQ], dnl [m4_fatal([must install pkg-config 0.29 or later before running autoconf/autogen])]) dnl dnl See the "Since" comment for each macro you use to see what version dnl of the macros you require. m4_defun([PKG_PREREQ], [m4_define([PKG_MACROS_VERSION], [0.29.2]) m4_if(m4_version_compare(PKG_MACROS_VERSION, [$1]), -1, [m4_fatal([pkg.m4 version $1 or higher is required but ]PKG_MACROS_VERSION[ found])]) ])dnl PKG_PREREQ dnl PKG_PROG_PKG_CONFIG([MIN-VERSION], [ACTION-IF-NOT-FOUND]) dnl --------------------------------------------------------- dnl Since: 0.16 dnl dnl Search for the pkg-config tool and set the PKG_CONFIG variable to dnl first found in the path. Checks that the version of pkg-config found dnl is at least MIN-VERSION. If MIN-VERSION is not specified, 0.9.0 is dnl used since that's the first version where most current features of dnl pkg-config existed. dnl dnl If pkg-config is not found or older than specified, it will result dnl in an empty PKG_CONFIG variable. To avoid widespread issues with dnl scripts not checking it, ACTION-IF-NOT-FOUND defaults to aborting. dnl You can specify [PKG_CONFIG=false] as an action instead, which would dnl result in pkg-config tests failing, but no bogus error messages. AC_DEFUN([PKG_PROG_PKG_CONFIG], [m4_pattern_forbid([^_?PKG_[A-Z_]+$]) m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$]) m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$]) AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility]) AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path]) AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path]) if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) fi if test -n "$PKG_CONFIG"; then _pkg_min_version=m4_default([$1], [0.9.0]) AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) PKG_CONFIG="" fi fi if test -z "$PKG_CONFIG"; then m4_default([$2], [AC_MSG_ERROR([pkg-config not found])]) fi[]dnl ])dnl PKG_PROG_PKG_CONFIG dnl PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) dnl ------------------------------------------------------------------- dnl Since: 0.18 dnl dnl Check to see whether a particular set of modules exists. Similar to dnl PKG_CHECK_MODULES(), but does not set variables or print errors. dnl dnl Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG]) dnl only at the first occurrence in configure.ac, so if the first place dnl it's called might be skipped (such as if it is within an "if", you dnl have to call PKG_CHECK_EXISTS manually AC_DEFUN([PKG_CHECK_EXISTS], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl if test -n "$PKG_CONFIG" && \ AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then m4_default([$2], [:]) m4_ifvaln([$3], [else $3])dnl fi]) dnl _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) dnl --------------------------------------------- dnl Internal wrapper calling pkg-config via PKG_CONFIG and setting dnl pkg_failed based on the result. m4_define([_PKG_CONFIG], [if test -n "$$1"; then pkg_cv_[]$1="$$1" elif test -n "$PKG_CONFIG"; then PKG_CHECK_EXISTS([$3], [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes ], [pkg_failed=yes]) else pkg_failed=untried fi[]dnl ])dnl _PKG_CONFIG dnl _PKG_SHORT_ERRORS_SUPPORTED dnl --------------------------- dnl Internal check to see if pkg-config supports short errors. AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], [AC_REQUIRE([PKG_PROG_PKG_CONFIG]) if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi[]dnl ])dnl _PKG_SHORT_ERRORS_SUPPORTED dnl PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], dnl [ACTION-IF-NOT-FOUND]) dnl -------------------------------------------------------------- dnl Since: 0.4.0 dnl dnl Note that if there is a possibility the first call to dnl PKG_CHECK_MODULES might not happen, you should be sure to include an dnl explicit call to PKG_PROG_PKG_CONFIG in your configure.ac AC_DEFUN([PKG_CHECK_MODULES], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl pkg_failed=no AC_MSG_CHECKING([for $2]) _PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) _PKG_CONFIG([$1][_LIBS], [libs], [$2]) m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS and $1[]_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details.]) if test $pkg_failed = yes; then AC_MSG_RESULT([no]) _PKG_SHORT_ERRORS_SUPPORTED if test $_pkg_short_errors_supported = yes; then $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1` else $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD m4_default([$4], [AC_MSG_ERROR( [Package requirements ($2) were not met: $$1_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. _PKG_TEXT])[]dnl ]) elif test $pkg_failed = untried; then AC_MSG_RESULT([no]) m4_default([$4], [AC_MSG_FAILURE( [The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. _PKG_TEXT To get pkg-config, see .])[]dnl ]) else $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS $1[]_LIBS=$pkg_cv_[]$1[]_LIBS AC_MSG_RESULT([yes]) $3 fi[]dnl ])dnl PKG_CHECK_MODULES dnl PKG_CHECK_MODULES_STATIC(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], dnl [ACTION-IF-NOT-FOUND]) dnl --------------------------------------------------------------------- dnl Since: 0.29 dnl dnl Checks for existence of MODULES and gathers its build flags with dnl static libraries enabled. Sets VARIABLE-PREFIX_CFLAGS from --cflags dnl and VARIABLE-PREFIX_LIBS from --libs. dnl dnl Note that if there is a possibility the first call to dnl PKG_CHECK_MODULES_STATIC might not happen, you should be sure to dnl include an explicit call to PKG_PROG_PKG_CONFIG in your dnl configure.ac. AC_DEFUN([PKG_CHECK_MODULES_STATIC], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl _save_PKG_CONFIG=$PKG_CONFIG PKG_CONFIG="$PKG_CONFIG --static" PKG_CHECK_MODULES($@) PKG_CONFIG=$_save_PKG_CONFIG[]dnl ])dnl PKG_CHECK_MODULES_STATIC dnl PKG_INSTALLDIR([DIRECTORY]) dnl ------------------------- dnl Since: 0.27 dnl dnl Substitutes the variable pkgconfigdir as the location where a module dnl should install pkg-config .pc files. By default the directory is dnl $libdir/pkgconfig, but the default can be changed by passing dnl DIRECTORY. The user can override through the --with-pkgconfigdir dnl parameter. AC_DEFUN([PKG_INSTALLDIR], [m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])]) m4_pushdef([pkg_description], [pkg-config installation directory @<:@]pkg_default[@:>@]) AC_ARG_WITH([pkgconfigdir], [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],, [with_pkgconfigdir=]pkg_default) AC_SUBST([pkgconfigdir], [$with_pkgconfigdir]) m4_popdef([pkg_default]) m4_popdef([pkg_description]) ])dnl PKG_INSTALLDIR dnl PKG_NOARCH_INSTALLDIR([DIRECTORY]) dnl -------------------------------- dnl Since: 0.27 dnl dnl Substitutes the variable noarch_pkgconfigdir as the location where a dnl module should install arch-independent pkg-config .pc files. By dnl default the directory is $datadir/pkgconfig, but the default can be dnl changed by passing DIRECTORY. The user can override through the dnl --with-noarch-pkgconfigdir parameter. AC_DEFUN([PKG_NOARCH_INSTALLDIR], [m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])]) m4_pushdef([pkg_description], [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@]) AC_ARG_WITH([noarch-pkgconfigdir], [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],, [with_noarch_pkgconfigdir=]pkg_default) AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir]) m4_popdef([pkg_default]) m4_popdef([pkg_description]) ])dnl PKG_NOARCH_INSTALLDIR dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE, dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) dnl ------------------------------------------- dnl Since: 0.28 dnl dnl Retrieves the value of the pkg-config variable for the given module. AC_DEFUN([PKG_CHECK_VAR], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl _PKG_CONFIG([$1], [variable="][$3]["], [$2]) AS_VAR_COPY([$1], [pkg_cv_][$1]) AS_VAR_IF([$1], [""], [$5], [$4])dnl ])dnl PKG_CHECK_VAR dnl PKG_WITH_MODULES(VARIABLE-PREFIX, MODULES, dnl [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], dnl [DESCRIPTION], [DEFAULT]) dnl ------------------------------------------ dnl dnl Prepare a "--with-" configure option using the lowercase dnl [VARIABLE-PREFIX] name, merging the behaviour of AC_ARG_WITH and dnl PKG_CHECK_MODULES in a single macro. AC_DEFUN([PKG_WITH_MODULES], [ m4_pushdef([with_arg], m4_tolower([$1])) m4_pushdef([description], [m4_default([$5], [build with ]with_arg[ support])]) m4_pushdef([def_arg], [m4_default([$6], [auto])]) m4_pushdef([def_action_if_found], [AS_TR_SH([with_]with_arg)=yes]) m4_pushdef([def_action_if_not_found], [AS_TR_SH([with_]with_arg)=no]) m4_case(def_arg, [yes],[m4_pushdef([with_without], [--without-]with_arg)], [m4_pushdef([with_without],[--with-]with_arg)]) AC_ARG_WITH(with_arg, AS_HELP_STRING(with_without, description[ @<:@default=]def_arg[@:>@]),, [AS_TR_SH([with_]with_arg)=def_arg]) AS_CASE([$AS_TR_SH([with_]with_arg)], [yes],[PKG_CHECK_MODULES([$1],[$2],$3,$4)], [auto],[PKG_CHECK_MODULES([$1],[$2], [m4_n([def_action_if_found]) $3], [m4_n([def_action_if_not_found]) $4])]) m4_popdef([with_arg]) m4_popdef([description]) m4_popdef([def_arg]) ])dnl PKG_WITH_MODULES dnl PKG_HAVE_WITH_MODULES(VARIABLE-PREFIX, MODULES, dnl [DESCRIPTION], [DEFAULT]) dnl ----------------------------------------------- dnl dnl Convenience macro to trigger AM_CONDITIONAL after PKG_WITH_MODULES dnl check._[VARIABLE-PREFIX] is exported as make variable. AC_DEFUN([PKG_HAVE_WITH_MODULES], [ PKG_WITH_MODULES([$1],[$2],,,[$3],[$4]) AM_CONDITIONAL([HAVE_][$1], [test "$AS_TR_SH([with_]m4_tolower([$1]))" = "yes"]) ])dnl PKG_HAVE_WITH_MODULES dnl PKG_HAVE_DEFINE_WITH_MODULES(VARIABLE-PREFIX, MODULES, dnl [DESCRIPTION], [DEFAULT]) dnl ------------------------------------------------------ dnl dnl Convenience macro to run AM_CONDITIONAL and AC_DEFINE after dnl PKG_WITH_MODULES check. HAVE_[VARIABLE-PREFIX] is exported as make dnl and preprocessor variable. AC_DEFUN([PKG_HAVE_DEFINE_WITH_MODULES], [ PKG_HAVE_WITH_MODULES([$1],[$2],[$3],[$4]) AS_IF([test "$AS_TR_SH([with_]m4_tolower([$1]))" = "yes"], [AC_DEFINE([HAVE_][$1], 1, [Enable ]m4_tolower([$1])[ support])]) ])dnl PKG_HAVE_DEFINE_WITH_MODULES # Copyright (C) 2002-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.16' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.16.5], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.16.5])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # Copyright (C) 2011-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_AR([ACT-IF-FAIL]) # ------------------------- # Try to determine the archiver interface, and trigger the ar-lib wrapper # if it is needed. If the detection of archiver interface fails, run # ACT-IF-FAIL (default is to abort configure with a proper error message). AC_DEFUN([AM_PROG_AR], [AC_BEFORE([$0], [LT_INIT])dnl AC_BEFORE([$0], [AC_PROG_LIBTOOL])dnl AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([ar-lib])dnl AC_CHECK_TOOLS([AR], [ar lib "link -lib"], [false]) : ${AR=ar} AC_CACHE_CHECK([the archiver ($AR) interface], [am_cv_ar_interface], [AC_LANG_PUSH([C]) am_cv_ar_interface=ar AC_COMPILE_IFELSE([AC_LANG_SOURCE([[int some_variable = 0;]])], [am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([am_ar_try]) if test "$ac_status" -eq 0; then am_cv_ar_interface=ar else am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([am_ar_try]) if test "$ac_status" -eq 0; then am_cv_ar_interface=lib else am_cv_ar_interface=unknown fi fi rm -f conftest.lib libconftest.a ]) AC_LANG_POP([C])]) case $am_cv_ar_interface in ar) ;; lib) # Microsoft lib, so override with the ar-lib wrapper script. # FIXME: It is wrong to rewrite AR. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__AR in this case, # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something # similar. AR="$am_aux_dir/ar-lib $AR" ;; unknown) m4_default([$1], [AC_MSG_ERROR([could not determine $AR interface])]) ;; esac AC_SUBST([AR])dnl ]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to '$srcdir/foo'. In other projects, it is set to # '$srcdir', '$srcdir/..', or '$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is '.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl # Expand $ac_aux_dir to an absolute path. am_aux_dir=`cd "$ac_aux_dir" && pwd` ]) # AM_COND_IF -*- Autoconf -*- # Copyright (C) 2008-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_COND_IF # _AM_COND_ELSE # _AM_COND_ENDIF # -------------- # These macros are only used for tracing. m4_define([_AM_COND_IF]) m4_define([_AM_COND_ELSE]) m4_define([_AM_COND_ENDIF]) # AM_COND_IF(COND, [IF-TRUE], [IF-FALSE]) # --------------------------------------- # If the shell condition COND is true, execute IF-TRUE, otherwise execute # IF-FALSE. Allow automake to learn about conditional instantiating macros # (the AC_CONFIG_FOOS). AC_DEFUN([AM_COND_IF], [m4_ifndef([_AM_COND_VALUE_$1], [m4_fatal([$0: no such condition "$1"])])dnl _AM_COND_IF([$1])dnl if test -z "$$1_TRUE"; then : m4_n([$2])[]dnl m4_ifval([$3], [_AM_COND_ELSE([$1])dnl else $3 ])dnl _AM_COND_ENDIF([$1])dnl fi[]dnl ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ([2.52])dnl m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], [$1], [CXX], [depcc="$CXX" am_compiler_list=], [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'], [$1], [UPC], [depcc="$UPC" am_compiler_list=], [$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES. AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE([dependency-tracking], [dnl AS_HELP_STRING( [--enable-dependency-tracking], [do not reject slow dependency extractors]) AS_HELP_STRING( [--disable-dependency-tracking], [speeds up one-time build])]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. # TODO: see whether this extra hack can be removed once we start # requiring Autoconf 2.70 or later. AS_CASE([$CONFIG_FILES], [*\'*], [eval set x "$CONFIG_FILES"], [*], [set x $CONFIG_FILES]) shift # Used to flag and report bootstrapping failures. am_rc=0 for am_mf do # Strip MF so we end up with the name of the file. am_mf=`AS_ECHO(["$am_mf"]) | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile which includes # dependency-tracking related rules and includes. # Grep'ing the whole file directly is not great: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. sed -n 's,^am--depfiles:.*,X,p' "$am_mf" | grep X >/dev/null 2>&1 \ || continue am_dirpart=`AS_DIRNAME(["$am_mf"])` am_filepart=`AS_BASENAME(["$am_mf"])` AM_RUN_LOG([cd "$am_dirpart" \ && sed -e '/# am--include-marker/d' "$am_filepart" \ | $MAKE -f - am--depfiles]) || am_rc=$? done if test $am_rc -ne 0; then AC_MSG_FAILURE([Something went wrong bootstrapping makefile fragments for automatic dependency tracking. If GNU make was not used, consider re-running the configure script with MAKE="gmake" (or whatever is necessary). You can also try re-running configure with the '--disable-dependency-tracking' option to at least be able to build the package (albeit without support for automatic dependency tracking).]) fi AS_UNSET([am_dirpart]) AS_UNSET([am_filepart]) AS_UNSET([am_mf]) AS_UNSET([am_rc]) rm -f conftest-deps.mk } ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking is enabled. # This creates each '.Po' and '.Plo' makefile fragment that we'll need in # order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" MAKE="${MAKE-make}"])]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O. m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC]) [_AM_PROG_CC_C_O ]) # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.65])dnl m4_ifdef([_$0_ALREADY_INIT], [m4_fatal([$0 expanded multiple times ]m4_defn([_$0_ALREADY_INIT]))], [m4_define([_$0_ALREADY_INIT], m4_expansion_stack)])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [AC_DIAGNOSE([obsolete], [$0: two- and three-arguments forms are deprecated.]) m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if( m4_ifset([AC_PACKAGE_NAME], [ok]):m4_ifset([AC_PACKAGE_VERSION], [ok]), [ok:ok],, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) AM_MISSING_PROG([AUTOCONF], [autoconf]) AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) AM_MISSING_PROG([AUTOHEADER], [autoheader]) AM_MISSING_PROG([MAKEINFO], [makeinfo]) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # AC_SUBST([mkdir_p], ['$(MKDIR_P)']) # We need awk for the "check" target (and possibly the TAP driver). The # system "awk" is bad on some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES([CC])], [m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES([CXX])], [m4_define([AC_PROG_CXX], m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES([OBJC])], [m4_define([AC_PROG_OBJC], m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], [_AM_DEPENDENCIES([OBJCXX])], [m4_define([AC_PROG_OBJCXX], m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) # Variables for tags utilities; see am/tags.am if test -z "$CTAGS"; then CTAGS=ctags fi AC_SUBST([CTAGS]) if test -z "$ETAGS"; then ETAGS=etags fi AC_SUBST([ETAGS]) if test -z "$CSCOPE"; then CSCOPE=cscope fi AC_SUBST([CSCOPE]) AC_REQUIRE([AM_SILENT_RULES])dnl dnl The testsuite driver may need to know about EXEEXT, so add the dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) fi fi dnl The trailing newline in this macro's definition is deliberate, for dnl backward compatibility and to allow trailing 'dnl'-style comments dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. ]) dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further dnl mangled by Autoconf and run in a shell conditional statement. m4_define([_AC_COMPILER_EXEEXT], m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST([install_sh])]) # Copyright (C) 2003-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MAKE_INCLUDE() # ----------------- # Check whether make has an 'include' directive that can support all # the idioms we need for our automatic dependency tracking code. AC_DEFUN([AM_MAKE_INCLUDE], [AC_MSG_CHECKING([whether ${MAKE-make} supports the include directive]) cat > confinc.mk << 'END' am__doit: @echo this is the am__doit target >confinc.out .PHONY: am__doit END am__include="#" am__quote= # BSD make does it like this. echo '.include "confinc.mk" # ignored' > confmf.BSD # Other make implementations (GNU, Solaris 10, AIX) do it like this. echo 'include confinc.mk # ignored' > confmf.GNU _am_result=no for s in GNU BSD; do AM_RUN_LOG([${MAKE-make} -f confmf.$s && cat confinc.out]) AS_CASE([$?:`cat confinc.out 2>/dev/null`], ['0:this is the am__doit target'], [AS_CASE([$s], [BSD], [am__include='.include' am__quote='"'], [am__include='include' am__quote=''])]) if test "$am__include" != "#"; then _am_result="yes ($s style)" break fi done rm -f confinc.* confmf.* AC_MSG_RESULT([${_am_result}]) AC_SUBST([am__include])]) AC_SUBST([am__quote])]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- # Copyright (C) 1997-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) # AM_MISSING_HAS_RUN # ------------------ # Define MISSING if not defined so far and test if it is modern enough. # If it is, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl if test x"${MISSING+set}" != xset; then MISSING="\${SHELL} '$am_aux_dir/missing'" fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= AC_MSG_WARN(['missing' script is too old or missing]) fi ]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_MANGLE_OPTION(NAME) # ----------------------- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) # -------------------- # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), [1])]) # _AM_SET_OPTIONS(OPTIONS) # ------------------------ # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) # Copyright (C) 1999-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_CC_C_O # --------------- # Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC # to automatically call this. AC_DEFUN([_AM_PROG_CC_C_O], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([compile])dnl AC_LANG_PUSH([C])dnl AC_CACHE_CHECK( [whether $CC understands -c and -o together], [am_cv_prog_cc_c_o], [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i]) if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi AC_LANG_POP([C])]) # For backward compatibility. AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) # Copyright (C) 2001-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_RUN_LOG(COMMAND) # ------------------- # Run COMMAND, save the exit status in ac_status, and log it. # (This has been adapted from Autoconf's _AC_RUN_LOG macro.) AC_DEFUN([AM_RUN_LOG], [{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD (exit $ac_status); }]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi if test "$[2]" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT([yes]) # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi AC_CONFIG_COMMANDS_PRE( [AC_MSG_CHECKING([that generated files are newer than configure]) if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi AC_MSG_RESULT([done])]) rm -f conftest.file ]) # Copyright (C) 2009-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SILENT_RULES([DEFAULT]) # -------------------------- # Enable less verbose build rules; with the default set to DEFAULT # ("yes" being less verbose, "no" or empty being verbose). AC_DEFUN([AM_SILENT_RULES], [AC_ARG_ENABLE([silent-rules], [dnl AS_HELP_STRING( [--enable-silent-rules], [less verbose build output (undo: "make V=1")]) AS_HELP_STRING( [--disable-silent-rules], [verbose build output (undo: "make V=0")])dnl ]) case $enable_silent_rules in @%:@ ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; esac dnl dnl A few 'make' implementations (e.g., NonStop OS and NextStep) dnl do not support nested variable expansions. dnl See automake bug#9928 and bug#10237. am_make=${MAKE-make} AC_CACHE_CHECK([whether $am_make supports nested variables], [am_cv_make_support_nested_variables], [if AS_ECHO([['TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi]) if test $am_cv_make_support_nested_variables = yes; then dnl Using '$V' instead of '$(V)' breaks IRIX make. AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AC_SUBST([AM_V])dnl AM_SUBST_NOTMAKE([AM_V])dnl AC_SUBST([AM_DEFAULT_V])dnl AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl AC_SUBST([AM_DEFAULT_VERBOSITY])dnl AM_BACKSLASH='\' AC_SUBST([AM_BACKSLASH])dnl _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl ]) # Copyright (C) 2001-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_STRIP # --------------------- # One issue with vendor 'install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we # always use install-sh in "make install-strip", and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be 'maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) # Copyright (C) 2006-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_SUBST_NOTMAKE(VARIABLE) # --------------------------- # Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. # This macro is traced by Automake. AC_DEFUN([_AM_SUBST_NOTMAKE]) # AM_SUBST_NOTMAKE(VARIABLE) # -------------------------- # Public sister of _AM_SUBST_NOTMAKE. AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004-2021 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_TAR(FORMAT) # -------------------- # Check how to create a tarball in format FORMAT. # FORMAT should be one of 'v7', 'ustar', or 'pax'. # # Substitute a variable $(am__tar) that is a command # writing to stdout a FORMAT-tarball containing the directory # $tardir. # tardir=directory && $(am__tar) > result.tar # # Substitute a variable $(am__untar) that extract such # a tarball read from stdin. # $(am__untar) < result.tar # AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar], [# The POSIX 1988 'ustar' format is defined with fixed-size fields. # There is notably a 21 bits limit for the UID and the GID. In fact, # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 # and bug#13588). am_max_uid=2097151 # 2^21 - 1 am_max_gid=$am_max_uid # The $UID and $GID variables are not portable, so we need to resort # to the POSIX-mandated id(1) utility. Errors in the 'id' calls # below are definitely unexpected, so allow the users to see them # (that is, avoid stderr redirection). am_uid=`id -u || echo unknown` am_gid=`id -g || echo unknown` AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) if test $am_uid -le $am_max_uid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) if test $am_gid -le $am_max_gid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi], [pax], [], [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Go ahead even if we have the value already cached. We do so because we # need to set the values for the 'am__tar' and 'am__untar' variables. _am_tools=${am_cv_prog_tar_$1-$_am_tools} for _am_tool in $_am_tools; do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works. rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar /dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR m4_include([m4/ax_prog_doxygen.m4]) m4_include([m4/flm_prog_try_doxygen.m4]) m4_include([m4/libtool.m4]) m4_include([m4/ltoptions.m4]) m4_include([m4/ltsugar.m4]) m4_include([m4/ltversion.m4]) m4_include([m4/lt~obsolete.m4]) ddcutil-2.2.0/Makefile.in0000664000175000001440000010043214754576155010712 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # Top level Makefile.am # Copyright (C) 2014-2023 Sanford Rockowitz # SPDX-License-Identifier: GPL-2.0-or-later VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = . ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \ $(am__configure_deps) $(am__DIST_COMMON) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = src/public/ddcutil_macros.h CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ cscope distdir distdir-am dist dist-all distcheck am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) \ config.h.in # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in \ $(top_srcdir)/config/ar-lib $(top_srcdir)/config/compile \ $(top_srcdir)/config/config.guess \ $(top_srcdir)/config/config.sub \ $(top_srcdir)/config/install-sh $(top_srcdir)/config/ltmain.sh \ $(top_srcdir)/config/missing \ $(top_srcdir)/src/public/ddcutil_macros.h.in AUTHORS COPYING \ NEWS.md README.md config/ar-lib config/compile \ config/config.guess config/config.sub config/depcomp \ config/install-sh config/ltmain.sh config/missing \ config/py-compile DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__post_remove_distdir = $(am__remove_distdir) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best DIST_TARGETS = dist-gzip # Exists only to be overridden by the user if desired. AM_DISTCHECK_DVI_TARGET = dvi distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ # To automatically update libtool script if it becomes out of date LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # From autoconf manual: # ... if you use aclocal from Automake to generate aclocal.m4, you must also # set ACLOCAL_AMFLAGS = -I dir in your top-level Makefile.am. # Due to a limitation in the Autoconf implementation of autoreconf, these # include directives currently must be set on a single line in Makefile.am, # without any backslash-newlines # Introspection does this. ACLOCAL_AMFLAGS = -I m4 ${ACLOCAL_FLAGS} DIST_SUBDIRS = src man data docs # endif EXTRA_DIST = README.md NEWS.md CHANGELOG.md m4/ax_prog_doxygen.m4 \ m4/introspection.m4 @USE_DOXYGEN_TRUE@DOXYDIR = docs SUBDIRS = src man data $(DOXYDIR) # if ENABLE_GOBJECT_COND DISTCHECK_CONFIGURE_FLAGS = --enable-introspection # install-data-local: # @echo "(Makefile) install-data-local):" # @echo " docdir = $(docdir)" @ENABLE_SHARED_LIB_COND_TRUE@libddcdocdir = $(datarootdir)/doc/libddcutil all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @test -f $@ || rm -f stamp-h1 @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 src/public/ddcutil_macros.h: $(top_builddir)/config.status $(top_srcdir)/src/public/ddcutil_macros.h.in cd $(top_builddir) && $(SHELL) ./config.status $@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscope: cscope.files test ! -s cscope.files \ || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) clean-cscope: -rm -f cscope.files cscope.files: clean-cscope cscopelist cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags -rm -f cscope.out cscope.in.out cscope.po.out cscope.files distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz $(am__post_remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__post_remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__post_remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__post_remove_distdir) dist-zstd: distdir tardir=$(distdir) && $(am__tar) | zstd -c $${ZSTD_CLEVEL-$${ZSTD_OPT--19}} >$(distdir).tar.zst $(am__post_remove_distdir) dist-tarZ: distdir @echo WARNING: "Support for distribution archives compressed with" \ "legacy program 'compress' is deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__post_remove_distdir) dist-shar: distdir @echo WARNING: "Support for shar distribution archives is" \ "deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz $(am__post_remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__post_remove_distdir) dist dist-all: $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' $(am__post_remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ *.tar.zst*) \ zstd -dc $(distdir).tar.zst | $(am__untar) ;;\ esac chmod -R a-w $(distdir) chmod u+w $(distdir) mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build/sub \ && ../../configure \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ --srcdir=../.. --prefix="$$dc_install_base" \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) $(AM_DISTCHECK_DVI_TARGET) \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__post_remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-recursive all-am: Makefile config.h installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -f Makefile distclean-am: clean-am distclean-generic distclean-hdr \ distclean-libtool distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) all install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--refresh check check-am clean clean-cscope clean-generic \ clean-libtool cscope cscopelist-am ctags ctags-am dist \ dist-all dist-bzip2 dist-gzip dist-hook dist-lzip dist-shar \ dist-tarZ dist-xz dist-zip dist-zstd distcheck distclean \ distclean-generic distclean-hdr distclean-libtool \ distclean-tags distcleancheck distdir distuninstallcheck dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs installdirs-am \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # libddcdoc_DATA = AUTHORS dist-hook: echo "(Makefile) Executing dist-hook..." chmod a-x ${distdir}/AUTHORS ${distdir}/COPYING ${distdir}/README.md find ${distdir} -name "*~" -exec rm -v {} \; find ${distdir} -name "*.ctl" -exec rm -v {} \; find ${distdir} -name "*.lst" -exec rm -v {} \; find ${distdir} -name "*.la" -exec rm -v {} \; find ${distdir} -name "*.old" -exec rm -v {} \; find ${distdir} -name "*.new" -exec rm -v {} \; find ${distdir} -name "*.tmp" -exec rm -v {} \; find ${distdir} -name "*old" -type d -prune -exec rm -fv {} \; find ${distdir} -name "*new" -type d -prune -exec rm -fv {} \; find ${distdir} -name ".gitignore" -exec rm -v {} \; rm -rfv ${distdir}/.github # Too many false positives: # alpha.clone.CloneChecker # alpha.deadcode.UnreachableCode # alpha.core.CastToStruct # Copied and adapted from colord # is calling autogen.sh within this file dangerous? clang: $(MAKE) clean; \ rm -rf clang; \ scan-build --use-analyzer=/usr/bin/clang \ -o clang-report \ ./autogen.sh \ --disable_gobject_api \ --enable-cffi \ --enable-cython \ ; \ scan-build --use-analyzer=/usr/bin/clang \ -o clang-report \ -enable-checker alpha.core.CastSize \ -enable-checker alpha.core.BoolAssignment \ -enable-checker alpha.core.Conversion \ -enable-checker alpha.core.SizeofPtr \ make # $(foreach v, $(.VARIABLES), @echo "$v = $$v") show: @echo "---> Show variables" @echo "" @echo "Set by PKG_CHECK_MODULES:" @echo " GLIB_CFLAGS = $(GLIB_CFLAGS) " @echo " GLIB_LIBS = $(GLIB_LIBS)" @echo " JANSSON_LIBS = $(JANSSON_LIBS)" @echo " JANSSON_CFLAGS = $(JANSSON_CFLAGS)" @echo " UDEV_CFLAGS = $(UDEV_CFLAGS)" @echo " UDEV_LIBS = $(UDEV_LIBS)" @echo " SYSTEMD_CFLAGS = $(SYSTEMD_CFLAGS)" @echo " SYSTEMD_LIBS = $(SYSTEMD_LIBS)" @echo " LIBUSB_CFLAGS = $(LIBUSB_CFLAGS)" @echo " LIBUSB_LIBS = $(LIBUSB_LIBS)" @echo "" @echo "Addtional:" @echo " prefix = $(prefix)" @echo " exec_prefix = $(exec_prefix)" @echo " libdir = $(libdir)" @echo " libexecdir = $(libexecdir)" @echo " top_srcdir = $(top_srcdir)" @echo " srcdir = $(srcdir)" @echo " pkgconfigdir: = ${pkgconfigdir}" @echo "" @echo " CFLAGS = $(CFLAGS)" @echo " CPPFLAGS = $(CPPFLAGS)" @echo " LDFLAGS = $(LDFLAGS)" .PHONY: clang show # ldconfig fails when executed in pbuilder due to permissions # just have to tell users to run it manually # install-exec-local: # @echo "(install-exec-local):" # ldconfig # uninstall-local: # @echo "(uninstall-local):=" # ldconfig # Rename to "all-local" for development all-local-disabled: @echo "" @echo "(Makefile:all-local) Variable values:" @echo " CLEANFILES: $(CLEANFILES)" @echo " CFLAGS: $(CFLAGS)" @echo " AM_CFLAGS: $(AM_CFLAGS)" @echo " CPPFLAGS: $(CPPFLAGS)" @echo " AM_CPPFLAGS: $(AM_CPPFLAGS)" @echo " AUTOMAKE_OPTIONS: $(AUTOMAKE_OPTIONS)" @echo " MAKELEVEL: $(MAKELEVEL)" @echo " MAKEFLAGS: $(MAKEFLAGS)" @echo " V: $(V)" @echo " AM_CFLAGS_STD: $(AM_CFLAGS_STD)" @echo "" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/config.h.in0000664000175000001440000001473014754576200010664 /* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* If defined, buid shared library. */ #undef BUILD_SHARED_LIB /* If defined, include build date/time in executables. */ #undef BUILD_TIMESTAMP /* If defined, enable environment commands. */ #undef ENABLE_ENVCMDS /* If defined, enable failsim. */ #undef ENABLE_FAILSIM /* If defined, force SUSE target directories. */ #undef ENABLE_FORCE_SUSE /* If defined, use UDEV. */ #undef ENABLE_UDEV /* If defined, enable USB communication. */ #undef ENABLE_USB /* Define to 1 if you have the 'clock_gettime' function. */ #undef HAVE_CLOCK_GETTIME /* Define to 1 if you have the declaration of 'strerror_r', and to 0 if you don't. */ #undef HAVE_DECL_STRERROR_R /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H /* Define to 1 if you have the header file. */ #undef HAVE_EXECINFO_H /* Define to 1 if you have the header file. */ #undef HAVE_FCNTL_H /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_LANGINFO_H /* Define to 1 if you have the header file. */ #undef HAVE_LIBINTL_H /* Define to 1 if you have the header file. */ #undef HAVE_LIMITS_H /* Define to 1 if your system has a GNU libc compatible 'malloc' function, and to 0 otherwise. */ #undef HAVE_MALLOC /* Define to 1 if you have the 'memset' function. */ #undef HAVE_MEMSET /* Define to 1 if you have the 'nl_langinfo' function. */ #undef HAVE_NL_LANGINFO /* Define to 1 if your system has a GNU libc compatible 'realloc' function, and to 0 otherwise. */ #undef HAVE_REALLOC /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDIO_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the 'stpcpy' function. */ #undef HAVE_STPCPY /* Define to 1 if you have the 'strchr' function. */ #undef HAVE_STRCHR /* Define to 1 if you have the 'strdup' function. */ #undef HAVE_STRDUP /* Define to 1 if you have the 'strerror' function. */ #undef HAVE_STRERROR /* Define if you have 'strerror_r'. */ #undef HAVE_STRERROR_R /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the 'strrchr' function. */ #undef HAVE_STRRCHR /* Define to 1 if you have the 'strtol' function. */ #undef HAVE_STRTOL /* Define to 1 if you have the header file. */ #undef HAVE_SYS_IOCTL_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_TERMIOS_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the header file. */ #undef HAVE_WCHAR_H /* Define to 1 if the system has the type '_Bool'. */ #undef HAVE__BOOL /* If defined, build with test cases. */ #undef INCLUDE_TESTCASES /* Define to the sub-directory where libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* If defined, remove static qualifier from function declarations and definitions. */ #undef STATIC_FUNCTIONS_VISIBLE /* Define to 1 if all of the C89 standard headers exist (not just the ones required in a freestanding environment). This macro is provided for backward compatibility; new code need not use it. */ #undef STDC_HEADERS /* Define to 1 if strerror_r returns char *. */ #undef STRERROR_R_CHAR_P /* If defined, building for BSD. */ #undef TARGET_BSD /* If defined, building for Linux. */ #undef TARGET_LINUX /* Use libdrm */ #undef USE_LIBDRM /* Use X11 */ #undef USE_X11 /* Version number of package */ #undef VERSION /* ddcutil major version */ #undef VERSION_VMAJOR /* ddcutil micro version */ #undef VERSION_VMICRO /* ddcutil minor version */ #undef VERSION_VMINOR /* ddcutil version suffix */ #undef VERSION_VSUFFIX /* If defined, building for Asan instrumentation. */ #undef WITH_ASAN /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define for Solaris 2.5.1 so the uint32_t typedef from , , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ #undef _UINT32_T /* Define for Solaris 2.5.1 so the uint8_t typedef from , , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ #undef _UINT8_T /* Define to '__inline__' or '__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus #undef inline #endif /* Define to rpl_malloc if the replacement function should be used. */ #undef malloc /* Define to rpl_realloc if the replacement function should be used. */ #undef realloc /* Define as 'unsigned int' if doesn't define. */ #undef size_t /* Define as 'int' if doesn't define. */ #undef ssize_t /* Define to the type of an unsigned integer type of width exactly 16 bits if such a type exists and the standard includes do not define it. */ #undef uint16_t /* Define to the type of an unsigned integer type of width exactly 32 bits if such a type exists and the standard includes do not define it. */ #undef uint32_t /* Define to the type of an unsigned integer type of width exactly 8 bits if such a type exists and the standard includes do not define it. */ #undef uint8_t ddcutil-2.2.0/AUTHORS0000666000175000001440000000005212630214264007671 Sanford Rockowitz ddcutil-2.2.0/COPYING0000666000175000001440000004325412303542700007663 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ddcutil-2.2.0/NEWS.md0000644000175000001440000000066713203271475007733 ddcutil ======= The [ddcutil website](http://www.ddcutil.com) is the primary location of information for ddcutil users. Recent announcements can be found on the [home page](http://www.ddcutil.com). Earlier announcements are located at [prior announcements](http://www.ddcutil.prior_announcements). Detailed information about user-visible changes for each release are located at [release notes](http://www.ddcutil.com/release_notes). ddcutil-2.2.0/README.md0000644000175000001440000000566614754153540010124 ddcutil ======= **ddcutil** is a Linux program for querying and changing monitor settings, such as brightness and color levels. Most monitors, other than laptop displays, have a Virtual Control Panel (VCP), which implements features defined in the Monitor Control Command Set (MCCS). Typically, **ddcutil** communicates with the monitor's VCP over an I2C bus, as per the Display Data Channel/Command Interface Standard (DDC/CI). Alternatively, some monitors (e.g. Eizo ColorEdge, Apple Cinema) provide a USB interface to the VCP, as described in the USB Monitor Control Class Specification. **ddcutil** can communicate with these monitors over USB instead of I2C. A particular use case for **ddcutil** is as part of color profile management. Monitor calibration is relative to the monitor color settings currently in effect, e.g. red gain. **ddcutil** allows color related settings to be saved at the time a monitor is calibrated, and then restored when the calibration is applied. The tarball/github project builds both command line (**ddcutil**) and shared library (**libddcutil**) executables. The command line executable does not depend on the shared library. For detailed information about **ddcutil**, see the project website: www.ddcutil.com. In particular, for a summary of key post-installation steps, including loading driver i2c-dev, see [Post-Installation Checklist](https://www.ddcutil.com/config_steps). More generally, for instructions on building and configuring **ddcutil**, see [Installation and Configuration](https://www.ddcutil.com/install_config_main/) The [ddcutil FAQ](https://ddcutil.com/faq) describes the causes and workarounds for many common (and not so common) issues. Once **ddcutil** is installed, online help is also available. Use the --help option or see the man page: ~~~: $ ddcutil --help $ man 1 ddcutil ~~~ References to the relevant specifictions can be found at www.ddcutil.com/bibliography. ### Installation Diagnostics If **ddcutil** is successfully built but execution fails, command `ddcutil environment` probes the I2C environment and may provide clues as to the problem. ### User Support Please direct technical support questions, bug reports, and feature requests to the [Issue Tracker](https://github.com/rockowitz/ddcutil/issues) on the github repository. Use of this forum allows everyone to benefit from individual questions and ideas. When posting questions regarding **ddcutil** configuration, please execute the following command, capture its output in a file, and submit the output as an attachement. ~~~ $ ddcutil interrogate ~~~ For further information about technical support, see https://www.ddcutil.com/tech_support. ### Maintaining **ddcutil** in Linux Distributions Those responsible for maintaining **ddcutil** related packages in Linux distributions should see [Notes for Linux Distribution Maintainers](https://www.ddcutil.com/mult_shared_libs). ## Author Sanford Rockowitz ddcutil-2.2.0/CHANGELOG.md0000644000175000001440000013260114754153540010444 ## [2.2.0] 2024-02-10 ### General #### Added - Support DisplayLink devices - Add command **noop**, which allows for executing options such as ***--settings*** without having to execute a real command. - As an aid to development, the build date and time are normally embedded in the ddcutil and libddcutil executables. This is reported using command **ddcutil --version --verbose". **libddcutil** reports this to the system log. If reproducible builds are required, use **configure** option ***--disable-build-timestamp***. (For reproducible builds, building typically is performed using a script or build system, so it's not inconvenient to specify ***--disable-build-timestamp*** in this situation.) - Add ***--enable-flock*** and ***--disable-flock*** as aliases for ***--enable-cross-instance-locks*** and ***--disable-cross-instance-locks*** - Add option ***--ignore-mmid*** to ignore problematic monitor models. Takes a Monitor Model Id, e.g. SAM-U32H75x-3587 as an argument. Indicates that DDC/CI communication is disabled for monitors with this id. Typically, this will be added to the [libddcutil] section of configuration file ddcutilrc. It can also be included in the options string passed in the opts argument to ddca_init2(). Addresses issue #446. - Maintain a stack of traced functions for debugging. Turned on by option ***--enable-traced-function-stack*** #### Changed - User Defined Features: - Add XNC (Extended Non-Continous) like simple NC, but the SH byte is also reported. - Allow SNC (Simple Non-Continuous) as alternative name for NC. - Report user defined features as part of parsed capabilities. - Commands recognizing user defined features now fail if there's an error loading a user defined feature file. These are **capabilities**, **setvcp**, **dumpvcp**, and **probe**. - /usr/lib/udev/rules.d/60-ddcutil-i2c-rules: - Give logged on user r/w access to /dev/dri/cardN, needed to allow logged on user to probe connectors using DRM. - Do not install /usr/lib/udev/rules.d/60-ddcutil-usb.rules, delete it if previously installed. Addresses issues #405, #428, #437 - Command **ddcutil chkusbmon**: - Skip processing and always return 1 (failure) if option ***--disable-usb*** is in effect. - Command **detect**: - Only show communication error detail if --verbose - Provide a clearer message if slave address x37 is inactive: - "Monitor does not support DDC" instead of generic "DDC_commnication failed" - If option ***--verbose*** is in effect, emit an additional message to check the monitor's OSD. - Parser changes: - Add alternative option names for symmetry with other options: - ***--discard-capabilities-cache*** is an alias for ***--discard-cache capabilities*** - ***--discard-sleep-cache*** is an alias for ***--discard cache dsa*** - ***--discard-dsa-cache*** is an alias for ***--discard cache dsa*** - Eliminate --enable-dsa-cache as alias for --enable-dynamic-sleep-cache - Improve handling of --verify/--noverify, error if both specified - File .gitignore: - Add: *.tar.gz, docs/ddcutil-c-api - Commands **interrogate** and **environment --verbose**: - Force settings --disable-cross-instance-locking, --disable-dynamic-sleep (VERIFY) - Forced settings apply to **environment --verbose** as well as **interrogate** - When probing DRM, recognize bus types DRM_BUS_PLATFORM, DRM_BUS_HOST1X, report as "platform", "host1x" - Change the system log message level when sleep time is adjusted from WARNING to VERBOSE. Addresses issue #427: Adjusting multiplier message fills system log when libddcutil used by clightd - Configuration file ddcutilrc: If there is a pound sign "#" on a line, the remainder of the line is treated as a comment. - Add -Wformat-security to compiler options. Addresses issue #458. - If option --bus specified, only check accessability for that bus, avoiding irrelevant warning messages regarding other buses. Addresses issue #461. - Return DDCRC_CONFIG_ERROR instead of DDCRC_BAD_DATA for User Defined Feature File errors. - Report the Monitor Model Id in the ***--verbose*** output to **ddcutil detect**. - Command **setvcp**: Do not report "Interpretation may not be accurate.", which is irrelevant for this command. Partially addresses issue #454. - rpt...() functions can redirect output to syslog, making lines coming from multiple threads more coherent - Enable additional compiler warnings to tighten the code. - Additional trace groups SYSFS, CONN #### Fixed - Rework laptop detection. A non-laptop display can have an eDP connector. This is an i915 video driver bug that will not be fixed. See freedesktop.org issue "DRM connector for external monitor has name card1-eDP-1" https://gitlab.freedesktop.org/drm/i915/kernel/-/issues/10389 - When processing environment variable user $XDG_DATA_DIRS, or $XDG_CONFIG_DIRS, the final directory in the list was ignored. Issue #438 - When processing a user defined feature file, recognize any whitespace character (e.g. tab), not just space. - Fix core dump on ddcutil getvcp. Issue #407 - Commands **interrogate** and **environment --verbose** - Simple getvcp test was not reporting the bytes of the response packet. - If no device with class x03 was found, the user's home directory was dumped. Issue #413. - Remove "-i" option on get-edid command. Does not exist on some versions. - Fix display not found on Raspberry Pi. Do not rely on /sys/class/drm to read EDID, which is not valid for some drivers. Addresses issue #403 - Fix DDC communication failed on Raspberry Pi. Do not rely on sysfs attributes that do not exist for ARM devices. Resolves issue #413. - User Define Features file: fix error msg when nothing follow VALUE - Convert CRLF line endings to LF - Use printf() formats %jd and %zd to portably print variables of type ssize_t, time_t, so as to build unchanged on architectures such as armel, armhf. - Avoid compiler warning possible depending on compiler configuration when a switch() construct is used. Replaced with if/else if/else. Resolves issue #458. - Do not use function strerrrorname_np(). Requires glibc >= 2.32. - Miscellaneous changes to allow for building on raspbian (debian bullseye). - Replace function sysfs_find_adapter(). Fixes display detection problem aspect of issue #465. - Dump information to syslog instead of asserting failure if unable to get flock on /dev/i2c device. - Option ***--skip-ddc-checks*** set vcp version in Display_Ref to DDCA_VSPEC_UNKNOWN to avoid possible assert failure. - Prepend thread id to most syslog messages. - Make syslog messages more consistent in form. - Memory leaks. ### Building - Re-enable autoconf/configure option --enable-x11/--disable-x11. X11 specific code is used in display change and sleep state detection. The default is --enable-x11. - Add autoconf/configure option ***--enable-static-functions-visible***. If set, storage class specifier "static" is removed from many functions so that their names appear in backtrace reports from valgrind, asan, and glibc function backtrace(). ### Shared Library The shared library **libddcutil** is backwardly compatible with the one in ddcutil 2.1.x. The SONAME is unchanged as libddcutil.so.5. The released library file is libddcutil.so.5.2.0. #### Added - Option ***--disable-api*** completely disables the API. Most API calls, including those performing DDC communications, will fail. This can be useful for testing whether **libddcutil** is the source of a system error in the case of client applications, e.g. KDE PowerDevil, that will not build without the shared library. - Add libddcutil only option ***--disable-watch-displays***, which unconditionally blocks **ddca_start_watch_displays()** from starting the thread that watches for display changes. Workaround for issue #470. - **ddca_get_display_watch_settings()**, **ddca_set_display_watch_settings()** #### Changed - **ddca_start_watch_displays()**: - The only event class that can currently be enabled is DDCA_EVENT_CLASS_DISPLAY_CONNECTION. Watching for sleep state changes is not currently supported. - Regards DDCA_EVENT_CLASS_ALL as same as DDCA_EVENT_CLASS_DISPLAY_CONNECTION - Error if either DDCA_EVENT_CLASS_DPMS or DDCA_EVENT_CLASS_NONE are specified. - Status code DDCRC_INVALID_CONFIG_FILE renamed to more general DDCRC_CONFIG_ERROR. DDCRC_INVALID_CONFIG_FILE is a valid alias. - Write build date and time to system log when starting libddcutil. - Rework libdccutil output to avoid duplicate msgs in system log when all terminal output is directed to the log, as with KDE Plasma - Most API functions that specify a display reference now return status code DDCRC_DISCONNECTED if the display reference is no longer valid. - Quiesce the API during **ddca_redetect_displays()**. Operations that access display state are not permitted, and return DDCRC_QUIESCED. - Add DDCA_STATS_API to enum DDCA_Stats_Type, for reporting API specific stats. - Compile using option -Wformat-security. Issue #458. - Opaque pointer DDCA_Display_Ref now contains a display reference id instead of an actual pointer. It's type continues to be void* so client program use of this type is unchanged. - **libddcutil** maintains a table of DDCA_Display_Refs that have been "published" by the API, for validating DDCA_Display_Ref args on API function calls. - The opaque value in DDCA_Display_Ref is now an integer id number instead of pointer into the libddcutil data structures, making it slightly more opaque. The type of DDCA_Display_Ref remains "void*", so no client changes are needed - syslog output is generally prefixed with date and thread id #### Fixed - Whan a display is connected, the display number assigned to its display reference is one greater than the highest already assigned, instead of 99. - **ddca_start_watch_displays()**: Fixed segfault that occured with driver nvidia when checking if all video adapters implement drm. Issue #390. - Ignore phantom displays when searching for a display reference. Issue #412. - **ddca_get_display_refs()**, **ddca_get_display_info_list2()** always return 0, even if an error occured when examining a particular monitor. Addresses issue #417. - Errors that occur opening individual displays or reading their EDIDs are are still reported using **ddca_get_error_detail()**. In addition, error messages are written to the terminal and, depending on the current syslog level, to the system log. - **ddca_get_display_refs()** and **ddac_get_display_info_list2()** do not include display references for displays that are no longer connected. - **ddca_get_display_info()** succeeds even if DDC communication is not working. Addresses issue #???. - Display reference validation: Do not use dref->drm_connector, which may be invalid after hotplug. Addresses issue #418. - **ddca_dref_repr()**: Do not check that the display reference is still valid. It is meaningful to create a string representation of a display reference even if it is no longer usable. Addresses ddcui issue #55. - Protect hash table of open monitors to avoid a possible race condition. - Recover instead of abort when more than one non-removed display refs exist for the same display. - Do not call ddca_stop_watch_displays() at library termination if client has already called it. - Use mutexes to control access to corruptable data structures. - Memory leaks. #### Display Change Detection - Alternative algorithms for detecting display changes, specified by option ***--watch-mode*** - watch mode XEVENT - Scans for changes only when a X11 change notification occurs. (Uses X11 API extension RANDR, which is also implemented on Wayland.) - watch mode POLL - doesn't use X11 - doesn't rely on /sys - reads EDIDs in polling loop - can consume a significant amount of CPU time on older machines - watch mode DYNAMIC (the default) - resolves to XEVENT on X11 or Wayland, otherwise to POLL - Extensively reworked display change detection - use /sys to get EDID if possible - handle MST hub devices if driver/device allow - not all drivers work - only perform stabilization for removed display - not checking for asleep - Named options affecting display change detection: - --watch-mode POLL, XEVENT, DYNAMIC - --enable/disable-try-get-edid-from-sysfs (default is --enable-try-get-edid-from-sysfs) - options ***--xevent-watch-loop-millisec*** ***--poll-watch-loop-millisec*** - Added **ddca_get_display_watch_settings()**, **ddca_set_display_watch_settings()** - Use constants in parms.h to specify retry intevals and counts - Handle possible delay between time that EDID can be read and DDC becomes functional - Added **flags** field in unused secton of DDCA_Display_Status Event, with bit DDCA_DISPLAY_EVENT_DDC_WORKING. Normally, this bit is set on display connection events. In case DDC is not immediately available after EDID detection, this bit is not set. If DDC subsequently becomes enabled, and event of type DDCA_EVENT_DDC_ENABLED occurs. - It's possible that there's a delay between the time a monitor is turned on (and X11/Wayland generate a display change event) and the time that DDC becomes enabled. There's a newly added flags field in DDCA_Display_Status_Event, with one bit defined, DDCA_DISPLAY_EVENT_DDC_WORKING. Normally, this bit is set in the emitted DDCA_Display_Status_Event. However, if DDC is not immediately enabled the bit is not set, and the display reference goes onto a recheck queue to be processed by a separate thread. An event of type DDCA_EVENT_DDC_ENABLED will be emitted if and when the recheck thread determines that DDC is working. - There's a tension in display change detection between minimizing the time between when X11/Wayland detects a monitor having been turned on and libddcutil issuing an event of type DDCA_DISPLAY_EVENT_CONNECTED versus checking and rechecking failed states (e.g. DDC not working). In many caes, the frequency and wait intervals are controlled by settings in file src/base/parms.h. ## [2.1.4] 2024-02-17 ### Shared Library - Reinstall previously deprecated and removed **ddca_create_display_ref()**, allowing existing clients to build unchanged. ## [2.1.3] 2024-02-07 ### Changed - Option ***--settings*** reports build options. ### Fixed - Memory leaks ### Shared Library The shared library **libddcutil** is backwardly compatible with the one in ddcutil 2.1.0. The SONAME is unchanged as libddcutil.so.5. The released library file is libddcutil.so.5.2.0. ### Fixed - Due to overly aggressive DDCA_Display_Ref validation, ddca_get_display_info() returned status DDCRC_ARG when obtaining information about an invalid display (i.e. one for which the EDID is detected but DDC communication fails). This fixes ddcui issue #55, which reported an abort if a display was invalid. - Checking for whether the video adapter supports DRM was consolidated. This fixes a case where all displays were reported to support DRM when that was not the case, causing incorrect display status change monitoring. ## [2.1.2] 2024-01-27 ### General ### Added - Option ***--vstats*** reports minimum, maximum, and average successful sleep multiplier ### Changed - Make hidden option ***--min-dynamic-multiplier*** non-hidden - Revert **ddca_get/set_sleep_multiplier()** to 2.0.0 semantics - Allow for the fact that the proprietary Nvidia driver always reports the value of /sys/class/drm//enabled as "disabled" ### Fixed - Invalid assert when checking how monitor reports unsupported features. (Issue #371) - Segfault in environment command when examining procfs if compiled using clang option -flto (Issue #354) - Bring man page up to date (Issue #364) ### Shared Library The shared library **libddcutil** is backwardly compatible with the one in ddcutil 2.1.0. The SONAME is unchanged as libddcutil.so.5. The released library file is libddcutil.so.5.1.1. ### Changed - **ddca_start_watch_displays()** requires that all video drivers support DRM. If the API call fails, detailed error information is available using **ddca_get_error_detail()**. - Additional syslog messages ### Fixed - SIGABRT in API calls that have a display reference or handle argument if **ddca_init2()** (or **ddca_init()**) had not been called. This caused KDE PowerDevil to repeatedly crash and restart. - Fix the check of whether all video drivers implement DRM, required for display hotplug detection. ## [2.1.0] 2024-01-16 ### General #### Added - Option ***--skip-ddc-checks*** - Skips initialization checks to confirm that DDC communication is working and the monitor properly uses the unsupported feature bit in Get Feature Reply packets, thereby improving initialization time. - Cross-instance locking (experimental). Uses flock() to coordinate I2C bus access to /dev/i2c devices when multiple instances of ddcutil or libddcutil are executing. Enabled by option ***--enable-cross-instance-locks***. - Option ***--min-dynamic-multiplier*** Specifies a floor to how low dynamic sleep adjustment sets the sleep multiplier. (experimental) #### Changed - Multiple "Options:" lines in an ini file segment are combined - Option ***--help***: - Only show extended information when ***--verbose*** specified - Option ***--version***: - Show only the version, without prefix if ***--brief*** specified - Include detailed build information if ***--verbose** specified - I2C bus examination during initialization can be parallelized, improving performance (This is distinct from the ddc protocol checking.) This is an experimental feature. It can be enabled by using a low value as an argument to option ***--i2c-init-async-min***, e.g. ***--i2c-init-async-min 4***. THIS OPTION IS DISABLED BY DEFAULT AS IT OCCASIONALLY TRIGGERS A BUG IN DRIVER amdgpu THAT CAN CAUSE THE MOUSE AND KEYBOARD TO BECOME UNRESPONSIVE. See freedesktop.org bug report "lockup in dce_i2c_submit_command_hw" at https://gitlab.freedesktop.org/drm/amd/-/issues. - Command detect: better messages when laptop display detected - do not report "DDC communication failed" - report "Is laptop display" instead of "Is eDP device" or "Is LVDS device" - Better accomodate the variation in use of sysfs by different drivers - Turned off unconditional message that reported an elusive Nvidia/i2c-dev driver compatibility error. The incompatibility has been full diagnosed as being caused by use of a legacy proprietary Nvidia driver. A message is still written to the system log. - Make more extensive use of the system log. - Options ***--enable-displays-cache***, ***--disable-displays-cache*** are marked hidden since displays caching is not a released feature. - Deprecate vaguely named option ***--force***. Replace its single use with option ***--permit-unknown-feature***. - Deprecate vaguely named option ***--async***. Use ***--ddc-checks-async-min*** - Deprecate vaguely named option ***--ddc***. Use option ***--ddcdata***, which more clearly indicates that it causes DDC data errors to be reported. - **configure** option ***--enable-asan*** causes libasan to be linked into binaries - **configure** option ***--enable-x11*** is deprecated. The X11 API is no longer used. #### Fixed - Better handling of DDC Null Message recognition and adjustments - Dynamic sleep: make it easier to reduce time - once high didn't come down - Command detect: ensure output of model name, serial number, and extra display descriptor use only ASCII character in the range 0..127. - Some USB-only code was not iftested out when **configure** option ***--disable-usb*** was set. (Issue 355) - Always set sleep multiplier to at least 1.0 for commands **setvcp** and **scs**. Addresses reports that aggressive optimization caused setvcp to fail. - Cross-thread locking handles situtations where a display ref does not yet exist, e.g. reading EDID. - Memory leaks. ### Shared library The shared library **libddcutil** is backwardly compatible with the one in ddcutil 2.0.0. The SONAME is unchanged as libddcutil.so.5. The released library file is libddcutil.so.5.1.0. #### Added - Implemented display hotplug event detection - Requires DRM video drivers (e.g. amdgpu, i915) - Can detect physical connection/disconnection and DPMS sleep status chanes, but the effect of turning a monitor on or off is monitor dependant and cannot reliably be detected. - Enabled by libddcutil option ***--enable-watch-displays***, or API call **ddca_enable_start_watch_displays()** - API uses callbacks to report report status changes to client - new status codes possible for many current API functions: DDCRC_DISCONNECTED, DDCRC_DPMS_ASLEEP - When a display connection event is reported, the client should call **ddca_redetect_displays()** - **ddca_validate_display_ref()**: Exposes the validation that occurs on any API call that has a DDCA_Display_Ref argument. Can be used to check whether a monitor asleep, disconnected, etc. - New functions for sleep multiplier control: - **ddca_enable_dynamic_sleep() - **ddca_disable_dynamic_sleep() - **ddca_get_current_sleep_multiplier() - **ddca_set_display_sleep_multiplier() - **ddca_init2()** replaces **ddca_init()**, which is deprecated: Has an additional argument for collecting informational msgs. Allows for not issuing information messages regarding the assembly of options and parsing directly from libddcutil to the terminal (now enabled by setting flag DDCA_INIT_OPTIONS_ENABLE_INIT_MSGS), but instead gives client complete control as to what to do with the messages. #### Changed - Functions that depend on initialization and that return a status code now return DDCRC_UNINITIALIZED if ddca_init() failed. - Revert **ddca_get_sleep_multiplier()**, **ddca_set_sleep_multiplier()** to their pre 2.0 semantics changing the multiplier on the current thread. However, these functions are marked as deprecated. #### Fixed - Argument passing on **ddca_get_any_vcp_value_using_implicit_type()** - Fixed cause of assert() failure in **ddca_init()** when the libopts string argument has a value and the configuration file is enabled but no options are obtained from the configuation file. - Contents of the libopts arg were added twice to the string passed to the libddcutil parser. ## [2.0.0] 2023-09-25 Release 2.0.0 contains extensive changes. Shared library libddcutil is not backwards compatible. #### Added - Install /usr/lib/modules-load.d/ddcutil.conf. Ensures that driver i2c-dev is loaded. - Install file /usr/share/udev/rules.d/60-ddcutil-i2c.rules, autmatically granting the logged on user read/write access to /dev/i2c devices for video displays. For most configurations, use of group i2c is no longer necessary. - Command options not of interest to general users are now hidden when help is requested. Option ***--hh*** exposes them, and implies option ***--help***. - Option ***--noconfig***. Do not process the configuration file. - Option ***--verbose***. If specified on the command line, the options obtained from the configuration file are reported. - Added utility options --f7, --f8, --i2, --s1, --s2, --s3, --s4, --fl1, --fl2 These options are for temporary use during development. The current use of the utility options is reported by option ***--settings***. - Added utility command C1 for temporary use during development. - Added option ***--enable-mock-data*** for testing - Option ***--trcfrom***. Traces the call stack starting with the specified function. This option applies only to functions for which tracing has been enabled. - API performance profiling - Added options ***--ignore-hiddev*** and ***--ignore-usb-vid-pid*** - Added: Sample file nvidia-i2c.conf that can be installed in directory /etc/modprobe.d to set options sometimes needed by the proprieatry NVidia video driver. - Added option ***--discard-cache*** to discard cached data at the start of program execution. Valid arguments are ***capabilities***, ***dsa***, and ***all***. - Command **discard [capabilites|dsa|all] cache(s)** discards cached data. - Option ***--pid*** (alt ***--process-id***) prepends the process id to trace messages. - Command **traceable-functions*** lists functions that can be traced by name, i.e. ones that can be specified as a ***--trcfunc*** argument. - If using X11, terminate immediately if a DPMS sleep mode is active. #### Changed - The dynamic sleep algorithm has been completely rewritten to both dynamically increase the sleep-multiplier factor (as needed) and decrease the sleep multiplier factor (insofar as possible). Data is maintained across program executions in file $HOME/.cache/ddcutil/stats. Option ***-dsa***, or one of its variants such as ***--enable-dsa*** turn it on. - Option ***--sleep-multiplier***: 0 is now allowed as an argument. Some DisplayPort monitors have been observed to work with this value. - Writing to the system log has been generalized. Option ***--syslog *** controls what is written to the system log. Recognized levels are NEVER, ERROR, WARN, INFO, and DEBUG. This option replaces ***--enable-syslog***, ***--disable-syslog***, and ***--trace-to-syslog***. - **environment --verbose**: Option ***--quickenv*** skips some slow tests such as use of program i2cdetect. - **environment --verbose**: extended sysfs scan for ARM SOC devices to explore how those devices use /sys - Detailed statistics are now maintained on a per-display instead of per-thread basis. - Option ***--vstats*** includes per-display statistics in its reports. It takes the same arguments as ***--stats***. - Cached capabilities are not erased by ddcutil calls that are not executed with ***--enable-capabilities-cache***. This makes the behavior the same as cached displays and cached performance statistics. - **environment --verbose** disables caching, reports contents of cached files. - loosen criteria for when to try fallback methods to read EDID when using USB to communicate with Eizo monitors - udev rule changes: - install /usr/lib/udev/rules.d/60-ddcutil-usb.rules - rename /usr/lib/udev/rules.d/60-ddcutil.rules to 60-ddcutil-i2c.rules - update and rename sample rules files installed in /usr/share/data/ddcutil as 60-ddcutil-i2c.rules and 60-ddcutil-usb.rules. The user can modify these files and install them in /etc/udev/rules.d to override the files installed in /usr/lib/udev/rules.d. - ***--enable-dsa*** is a valid synonym for ***--enable-dynamic-sleep*** - Display detection improved - Rework the algorithm for detecting display communication and testing how invalid features are reported. - Handle the phantom monitor case where a MST capabile monitor is detected as a separeate i2c bus/drm connector along with that on the video card - Command **detect** improved: - verbose output: - Reports the sysfs DRM values for dpms, enabled, and status - Reports if I2C slave address x37 is responsive - reports an error summary if DDC communication fails - Issue warnings that output may be inaccurate if the monitor is sleeping or if it cannot be determined how unsupported features are indicated. - Messages regarding DDC data errors (controlled by option ***--ddc***) are written to the system log with level LOG_WARNING instead of LOG_NOTICE. #### Fixed - More robust checks during display detection to test for misuse of the DDC Null Message and all zero getvcp response to indicate unsupported features. - Option ***--help***: Document **ELAPSED** as a recognized statistics class - ddca_dfr_check_by_dref(): do not return an error if no user defined feature file exists for the monitor - Recognize (but always report failure for) CHKUSBMON command even when ddcutil not built with USB support. - Improve reporting of /dev/hiddev* open failures to reduce confusion caused by this typically benign error. - Check that no display identifier is included on commands that don't use one - Increase buffer size to allow for a Get Feature Reply packet that contains an incorrectly large length field. - Change the USB infomation shown for option ***--version*** to emphasize that ddcutil uses USB for communicating with the monitor's Virtual Control Pandl, not for video transmission. - Memory leaks ### Shared library changes The shared library **libddcutil** in is not backwardly compatible. The SONAME is now libddcutil.so.5. The released library file is libddcutil.so.5.0.0. Library initialization has been reworked extensively to move operations that can fail and other aspects that should be under control of the library user into a new function **ddca_init()**. This function: - controls the level of messages written to the system log - optionally processes options obtained from the **ddcutil** configuration file - processes additional options passed as a string - sets error information for ddca_get_error_detail() If this function is not called by the user program, any API function that relies on its processing invokes **ddca_init()** using arguments such that it never fails, e.g. the configuration file is not processed. Added typedef - struct DDCA_Display_Detection_Report Added functions: - ddca_init() See above. - ddca_register_display_detection_callback(): Registers a function of type DDCA_Display_Status_Func which will be called to inform the client of display hotplug events. - ddca_library_filename(): Returns the fully qualified name of the shared library. Changed functions: - ddca_report_display_info() returns DDCA_Status instead of void - ddca_get_feature_name() implementation restored Changed semantics: The semantics of some functions have changed, reflecting the fact that some statistics are now maintained on a per-display rather than per-thread basis. - ddca_set_sleep_multiplier(), ddca_get_sleep_multiplier(). Instead of operating on the current thread, these functions operate on the display, if any, open in the current thread. - ddca_set_default_sleep_multiplier(), ddca_get_default_sleep_multiplier() Operate on newly detected displays, not new threads. Removed functions: With the ability to configure libddcutil operation both by the ddcutil configuration file and by passing an option string in the ddca_init() arguments, several API functions are no longer needed and have been removed: Max-tries options: - ddca_max_max_tries() - ddca_get_max_tries() - ddca_set_max_tries() - ddca_set_default_sleep_multiplier(), ddca_set_global_sleep_multiplier() - ddca_get_default_sleep_multiplier(), ddca_set_global_sleep_multiplier() Trace options: - ddca_add_traced_function() - ddca_add_traced_file() - ddca_set_trace_groups() - ddca_add_trace_groups() - ddca_trace_group_name_to_value() - ddca_set_trace_options() USB enablement: - ddca_enable_usb_display_detection - ddca_disable_usb_display_detection Miscellaneous: - ddca_enable_force_slave_adress() - ddca_is_force_slave_address_enabled() - ddca_enable_error_info() Most per-thread statistics are now instead maintained on a per-display basis. The following functions are no longer useful and have been removed - ddca_set_thread_description() - ddca_append_thread_description() - ddca_get_thread_desription() Remove previously deprecated functions: - ddca_open_display(). Use ddca_open_display2(). - ddca_create_display_ref(). Use ddca_get_display_ref() - ddca_free_display_ref(). Had become a NO-OP. All display references are persistent Symbols for functions and enums that had previously been removed from ddcutil_c_api.h are no longer exported. Options that apply only to libddcutil (Specified in the ddcutil configuration file or passed to ddca_init()) - Option ***--profile-api***. Applies only to **libddcutil**. Statistics for API functions that perform display IO are collected and subsequently reported when the library is terminated. - Option ***--trcapi***. Trace the call stack for a specified API function. #### Building ddcutil - configure options --enable-syslog/--disable-syslog have been eliminated. Use runtime option ***--syslog NEVER*** to disable all writes to the system log. - Use of shared library **libkmod** eliminated. - Shared library **libjansson** is now required ## [1.4.5] 2023-09-18 #### Building ddcutil - The autotools **configure** command now recognizes ***--enable-install-lib-only***. If specified, command **make install** only installs the shared library. This is intended to facilitate installation of **libddcutil.so.4** along with the upcoming **libddcutil.so.5**. ## [1.4.2] 2023-02-17 ### Added - **ddcutil** installation installs files /usr/lib/modules-load.d/ddcutil.conf and /usr/lib/modules-load.d#libddcutil.conf to ensure that kernel module i2c-dev is loaded at boot time if it is not built into the kernel. There are two files so that when split up into distribution packages, each of the command line **ddcutil** package and the shared library **libddcutil** package installs a file. ## [1.4.1] 2023-01-16 ### Fixed - The default sleep-multipler value was 0, instead of 1. This resulted in failure of most DDC/CI operations, including display detection. ## [1.4.0] 2023-01-04 ### Added - **ddcutil** installation installs file /usr/lib/udev/rules.c/60-ddcutil.rules. This udev rule uses tag uaccess to give the logged on user read/write access to /dev/i2c devices associated with video adapters. Configuring use of group i2c is no longer necessary. - configure options ***--enable-syslog*** and ***--disable-syslog*** control whether messages are written to the system log. The default is enabled. ### Changed - The ability to use the write()/read() interface of i2c-dev has been restored. It is needed to work around a bug in the proprietary Nvidia driver. By default, ioctl() interface is used for all drivers. If the Nvidia bug is detected, the write()/read() interface is used instead. Command line options ***--use-file-io*** and ***--use-ioctl-io*** affect this default behavior. When i2c-dev's file io interface is used, option ***--force-slave-address*** is again meaningful. - Option ***--sleep-multiplier*** and API functions **ddca_set_sleep_multiplier_value()**, **ddca_set_default_sleep_multiplier_value()** now accept 0 as a valid argument. - The ddcutil command parser reports an error if a display selection option (e.g. ***--bus***) is given on a command to which it does not apply. - Write additional error and information messages to the system log. - Eliminate message "Is DDC/CI enabled in the monitor's on-screen display?" It's rarely the cause of communication failures. ### Fixed - Warn of a possibly invalid DRM connector name in **detect** output if monitors with identical EDIDs are used with the proprietary nvidia driver. - Handle /dev/i2c device names with a double hyphen, e.g. /dev/i2c--3. - Better libddcutil handling of configuration file errors. Do not abort initialization in case of errors. - Fix interpretation of digital display type bits for EDID version 1.4 - Miscellaneous segfaults. ## [1.3.2] 2022-09-04 ### Changed - Modify tarball creation to eliminate garbage and otherwise unneeded files. ## [1.3.0] 2022-07-19 ### Added - Command **detect**: - Issue warning for monitors for which **ddcutil** should not be used to change settings. - Currently only entry is Xaomi model "Mi Monitor" - Debug messages. Environment variables DDCUTIL_DEBUG_PARSE, DDCUTIL_DEBUG_MAIN, DDCUTIL_DEBUG_LIBINIT can be set to enable trace messages in command line **ddcutil** or shared library **libddcutil.so** during initialization and before command options. ### Changed - Option ***--force-slave-address*** no longer has any effect. The dev-i2c ioctl() interface is now used exclusively instead of write() and read() calls for writing to and reading from the I2C bus. As a result, ioctl(SLAVE_ADDRESS), which has been the source of EBUSY errors from driver i2-dev, is no longer used. In principle, EBUSY errors are still possible from within individual video drivers, but this has never been observed. - Sleeps immediately after opening a /dev/i2c device and after completion of a read operation are completely eliminated. The sleep-suppression related uptions, ***--sleep-less***, ***--less-sleep, ***--enable-sleep-suppression***, and ***--disable-sleep-suppression*** no longer have any effect. - Option ***--dca***: The Dynamic Sleep Adjustment algorithm was rewritten to more sensibly increment sleep times after before each retry. - Commands **getvcp** and **vcpinfo**: - Allow specification of multiple feature codes, for example ***ddcutil getvcp 10 12*** , ***ddcutil vcpinfo 14 16 18 1a*** - Command **detect**: - Option ***--verbose*** produces addtional information: - The product code is reported in hex as well as decimal - The EDID source field is set to **I2C** in the normal case where the EDID is read directly from slave address X50. Alternative values include **USB**, **X11**, and **SYSFS**. - Command **environment**: - Scanning of /sys by option ***--verbose*** has been improved. - Add msg re SYSENV_QUICK_TEST environment variable - Command **interrogate**: - Set --disable-capabilities-cache - More user friendly messages at startup regarding /dev/i2c buses that cannont be opened. If the problem is inadequate permissions (EACCES), the user is directed to www.ddcutil.com/permissions. - Better handle malformed EDIDs - Trailing blanks on model and serial number are stripped. This affects commands **detect --terse**, **loadvcp** and **dumpvcp**, and also the file names of user defined features. - Option ***--stats***: - I2C ioctl() calls for reading and writing are now reported as type IE_IOCTL_WRITE and IE_IOCTL_READ rather than IE_OTHER - IE_WRITE_READ stats are no longer reported, as they are redundant - Source code has been extensively cleaned up. In particular, directory **adl** containing code for the old proprietary AMD video driver, has been removed. - Building ddcutil: - Library **libi2c.so** is no longer linked. It was needed only for some experimental code. libddcutil: - ddca_get_display_refs(), ddca_get_display_info_list2(): - Open errors can be retrieved using ddca_get_error_info(). Note that the API calls still succeed. - Deprecated API functions have no effect: - ddca_enable_force_slave_address(), ddca_is_force_slave_address_enabled() ### Fixed - The sleep multiplier value was not respected for new API threads. - User Defined Features: Keyword **NC** set the incorrect flag in a feature descriptor. - Option **--dsa**: Fix adjustment factor calculation due to incorrect variable type. - Fixed a segfault that occurred at **ddcui** startup. The fault was in a trace message for function ddc_start_watch_displays() which watches for displays that are added or removed. - Fixed a segfault in **ddcutil** initialization because of unexpected contents in sysfs. - Do not use glib function g_byte_array_steal(), which requires glib 2.60. ddcutil requires only glib 2.40. - Miscellaneous memory leaks - Double count I2C writes in stats. ## [1.2.2] 2022-01-22 ### Added - API function ddca_enable_force_slave_address() - API function ddca_is_force_slave_address_enabled() ### Changed - Improve handling of and messages regarding DDC communication failures with errno EBUSY. In particular, this error occurs when driver ddcci is loaded. - Command **detect**: If DDC communication fails with error EBUSY, report the display as "Busy" instead of "Invalid" and suggest use of option ***--force-slave-address***. - Command **environment**: Suggest use of option ***--force-slave-address*** if driver ddcci is detected. - Messages re EBUSY errors are always written to the system log. - Command **detect**: - Do not report the EDID source unless there is a value to show. This value is set only for USB connected monitors. - Show extended output based on option ***--verbose***, not undocumented option ***--very-verbose***. - Report color bit depth if EDID version >= 1.4 - Command **environment**: Simplify the exploration of sysfs. - API changes: - Field latest_sl_values in struct DDCA_Feature_Metadata struct is no longer set, - API function ddca_report_display_info(): include binary serial number - Building and porting: - When building ddcutil, allow for building a static library if **configure** option ***--enable-static*** is set. Linux distributions frown on packaging static libraries, but if a user wants to build it who am I to judge. By default, static libraries are not built, - Replace use of Linux specific function **__assert_fail()** with **exit()** in traced assertions. **__assert_fail** is used in the Linux implementation of **assert()**, but is not in the C specification. This can present a problem in porting ddcutil. - Code cleanup: - Delete incomplete, experimental code for asynhronous feature access, including files src/ddc/ddc_async.c/h. - Remove unused files src/util/output_sink.c/h. ### Fixed - Only write Starting/Terminating messages to the system log if option ***--syslog*** is specified. - Avoid compilation warnings when assert() statments are disabled (NDEBUG is defined). - Fixed a segfault in the debug/trace code of ddca_get_display_refs() - Memory leaks. ## [1.2.1] 2021-11-15 ### Added - Option ***--syslog***: Send trace and debug messages to the system log in addition to the trace location. - Option ***--wall-timestamp***, ***--wts***: Prefix trace and debug messages with the current wall time. - Option ***--settings***: Report option settings in effect. ### Changed - Details of current settings are no longer reported by every command invocation when option ***--verbose*** is specified. Use option ***--settings*** to control option reporting. - Removed sample program demo_watch_displays. ### Fixed - Numerous memory leaks, in particular ones triggered by ddca_redetect_displays(). - Build failure if configure option ***--enable-x11=no*** was specified. - API functions ddc_open_display(),ddc_open_display2() now always return DDCRC_ALREADY_OPEN if the the display is already open in the current thread. Previously an assert() failure would occur under certain circumstances. - Options ***--disable-capabilities-cache***, ***--disable-udf*** not respected - Proof of concept code that watches for display hotplug events ## [1.2.0] 2021-09-28 ### Added - libddcutil log file - libddcuti and ddcutil write critical events to syslog - API function ddca_add_trace_group() - API function ddca_extended_version_string() - API function ddca_redetect_displays() - API function ddca_get_display_refs() - API function ddca_get_display_info() - API function ddca_free_display_info() - Macro DDCUTIL_VSUFFIX ### Changed - If possible, command **ddcutil environment --verbose** calls **get-edid|parse-edid** as an additional EDID check. - Additional validation of DDCA_Display_Ref and DDCA_Display_Handle arguments to API functions - Improved tracing of assert() failures - --enable-capabilities-cache is now the default - libddcutil name is now libddcutil.so.4.1.0 - Command **detect**: improved analysis of /sys - Command **detect**: ***--verbose*** option reports raw EDID - Option ***--help*** does not report undocumented option ***--very-verbose***. ### Fixed - Incorrect assembly of sysfs path definitions in **ddcutil environment --verbose** - ddcutil diagnostics were not finding module i2c-dev if the system (e.g. NixOS) used a non-standard location for the modules directory (Issue #178). The checks have been rewritten to use libkmod. - Eliminate repeated messages from the experimental display hotplug detection code if no /sys/class/drm/cardN devices exist. (libddcutil) ## [1.1.0] 2021-04-05 For details, see [ddcutil Release Notes](https://www.ddcutil.com/release_notes). ### Added - Configuration file **ddcutilrc**, located on the XDG config path. - Cache monitor capabilities strings to improve performance of the **capabilities** command. Controlled by options ***--enable-capabilities-cache***, ***--disable-capabilities-cache***. - Workarounds for problems in DRM video drivers (e.g. i915, AMDGPU) when displays are connected to a docking station. The same monitor can appear as two different /dev/i2c devices, but only one supports DDC/CI. If possible these are reported as a "Phantom Display" instead of as "Invalid Display". Also, try to work around problems reading the EDID on these monitors, which can cause the monitor to not be detected. - Option ***--edid-read-size 128*** or ***--edid-read-size 256*** forces **ddcutil** to request that number of bytes when reading the EDID, which can occasionally allow the EDID to be read successfully. - Issue warning at startup if driver i2c-dev is neither loaded nor built into the kernel. ### Changed - By default, files generated by **dumpvcp** are saved in the XDG_DATA_HOME directory. - **environment --verbose** has more detailed reporting of relevant sections of /sys. - Additional information on **detect --verbose**. - Additional functions are traceable using option ***--trcfunc*** - User defined features are enabled by default. ### Fixed - Regard IO operations setting errno EBUSY as recoverable, suggest use of option ***--force-slave-address***. (EBUSY can occur when ddcontrol's ddcci driver is loaded.) - Fix build failure when configure option ***--disable-usb*** is combined with ***--enable-envcmds***. - On AMD Navi2 variants, e.g. RX 6000 series, **ddcutil** display detection put the GPU into an inconsistent state when probing a SMU I2C bus exposed by the GPU. This change ensures that **ddcutil** does not attempt to probe such buses. ddcutil-2.2.0/man/0000775000175000001440000000000014754576333007476 5ddcutil-2.2.0/man/Makefile.am0000644000175000001440000000020514572333721011433 if !INSTALL_LIB_ONLY_COND man_MANS = ddcutil.1 else man_MANS = endif EXTRA_DIST = $(man_MANS) # dist_man1_MANS = \ # ddcutil.1 ddcutil-2.2.0/man/Makefile.in0000664000175000001440000004155614754576155011500 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = man ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man1dir = $(mandir)/man1 am__installdirs = "$(DESTDIR)$(man1dir)" NROFF = nroff MANS = $(man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) am__DIST_COMMON = $(srcdir)/Makefile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ @INSTALL_LIB_ONLY_COND_FALSE@man_MANS = ddcutil.1 @INSTALL_LIB_ONLY_COND_TRUE@man_MANS = EXTRA_DIST = $(man_MANS) all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign man/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man1: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) tags TAGS: ctags CTAGS: cscope cscopelist: distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(MANS) installdirs: for dir in "$(DESTDIR)$(man1dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-man uninstall-man: uninstall-man1 .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ cscopelist-am ctags-am distclean distclean-generic \ distclean-libtool distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-man1 install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags-am uninstall uninstall-am uninstall-man \ uninstall-man1 .PRECIOUS: Makefile # dist_man1_MANS = \ # ddcutil.1 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/man/ddcutil.10000644000175000001440000004161114754250415011117 .\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH ddcutil 1 "2024-01-11" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME ddcutil \- Query and change monitor settings .SH SYNOPSIS \fBddcutil\fP [\fIoptions\fP] command [\fIcommand-arguments\fP] [\fIoptions\fP] Options can be written either before or after the command and its arguments. .\" ALT USING .SY .OP .\" .SY .\" .OP \-abcde .\" .OP \-b busno .\" .OP \-d|--display dispno .\" command command-arguments .\" .YS .SH DESCRIPTION \fBddcutil\fP is used to query and change monitor settings. The settings that can be controlled by \fBddcutil\fP are, generally speaking, those that can be changed using the buttons on a monitor and its on screen display. The specific settings vary from monitor to monitor. \fBddcutil\fP communicates with monitors that implement the Monitor Control Command Set (MCCS) using the DDC/CI protocol on an I2C bus. Normally, the video driver for the monitor exposes the I2C bus as devices named /dev/i2c-n. Alternatively, \fBddcutil\fP can communicate with monitors that use USB to communicate MMCS, provided the monitors meet the USB Monitor Control Class Specification. The Monitor Control Command Set describes a collection of Virtual Control Panel (VCP) features that a monitor can implement. Each feature is identified using a single byte. For example, feature x10 is the brightness control. Common use cases include changing monitor brightness and color. Using scripts, the changes can be effected by keystrokes, or in response to the time of day. Another common use case is to switch the monitor input source. A more complex use case for \fBddcutil\fP is as part of color profile management. Monitor calibration is relative to the monitor color settings currently in effect, e.g. red gain. \fBddcutil\fP allows color related settings to be saved at the time a monitor is calibrated, and then restored when the calibration is applied. This man page describes \fBddcutil\fP commands and options most important to the typical user. For complete documentation, use the \fI--help\fP option or see the web site .UR http://www/ddcutil.com .UE . If option \fI--verbose\fP is specifeid in conjunction with \fI--help\fP, more extensive help on option arguments is shown. Option \fI--hh\fP shows all options recognized by \fBddcutil\fP. These include deprecated option names (which have been replaced by more descriptive names), experimental options, and options only of interest to developers. .SH RESTRICTIONS \fBddcutil\fP does not support laptop monitors, which do not implement DDC/CI. .PP .\" TeX users may be more comfortable with the \fB\fP and .\" \fI\fP escape sequences to invode bold face and italics, .\" respectively. .\" .B ddcutil .\" .I command .\" .R [ .\" .I command-arguments .\" .R ] [ .\" .I options .\" .R ] .SH COMMANDS .SS Primary Commands These are the most used \fBddcutil\fP commands. .TP .B "detect " Find monitors that have a Virtual Control Panel. .TP \fBvcpinfo\fP [ \fIfeature-code\fP | \fIfeature-group\fP ] Describe VCP feature codes. as defined in the MCCS specification. Use option \fI--verbose\fP to see values for Non-Continuous features. .TP .B "capabilities " Query the monitor's capabilities string .TP \fBgetvcp\fP [ \fIfeature-code\fP | \fIfeature-group\fP ] ... Report a VCP feature value, or a group of feature values. More than one feature code can be specified. However feature codes and groups cannot be combined. .TP \fBsetvcp\fP \fIfeature-code\fP [+|-] \fInew-value\fP ... Set a VCP feature value. If + or - is specified, it must be surrounded by blanks, and indicates a relative value change of a continuous VCP feature. Multiple feature/value pairs (with or without [+|1]) can be specified. .SS Secondary Commands These commands address special situations. .TP .BI "dumpvcp " filename Save color profile related VCP feature values in a file. If no file name is specified, one is generated and the file is saved in $HOME/.local/share/ddcutil, .TP .BI "loadvcp " filename Set VCP feature values from a file. The monitor to which the values will be applied is determined by the monitor identification stored in the file. If the monitor is not attached, nothing happens. .TP .B "scs " Issue DDC/CI Save Current Settings request. Most monitors do not implement this command. A few require it for values changed by \fBsetvcp\fP to take effect. .TP .B "chkusbmon " Tests if a hiddev device may be a USB connected monitor, for use in udev rules. .TP .BI "discard " "all|capabilities|dsa " cache[s] Discard cached files used for performance improvement. .TP .B "traceable-functions" Lists functions that can be specifically traced using an option like \fI--trcfunc\fP or \fI--trcfrom\fP .TP .B "noop " Do not execute a command. Just process options. .SS Diagnostic commands These commands diagnose issues in the system configuration that affect \fBddcutil\fP operation, and that gather information for remote problem diagnosis. .TP .B "environment " Probe the \fBddcutil\fP installation environment. .TP .B "usbenv " Probe USB aspects of the \fBddcutil\fP installation environment. .TP .B "probe " Explore the capabilities and features of a single monitor. .TP .B "interrogate " Collect maximum information for problem diagnosis. Includes the output of \fBddcutil environment --verbose\fP for each detected monitor, the output of \fBddcutil capabilities --verbose\fP and \fBddcutil probe --verbose\fP. .PP .SH COMMAND ARGUMENTS .I feature-code .sp A feature-code is specified by its 2 character hex feature number, with or without a leading "0x", e.g. 0x10, 10 .sp 2 .I feature-group .sp 2 The following are the most useful feature groups. For a complete list, use the \fB--help\fP option. .TP .BR ALL|KNOWN All feature codes understood by \fBddcutil\fP .TQ .B COLOR Scan color related feature codes .TQ .B PROFILE Subset of color related feature codes that are saved and restored by \fBdumpvcp\fP and \fBloadvcp\fP .TQ .B SCAN Scan all possible feature codes 0x00..0xff, except those known the be write-only .PP Feature group names can be abbreviated to the first 3 characters. Case is ignored. e.g. "COL", "pro". .I new-value .sp Normally, this is a decimal number in the range 0..255, or a hexadecimal number in the range x00..xff. More generally, this is actually a two byte value, i.e. x00..xffff, and a few features on some monitors use this extended range. .\" .TP inserts a line before its output, .TQ does not .SH OPTIONS .PP Options that control the amount and form of output. .TQ .B "-t, --terse, --brief" Show brief detail. For command \fBgetvcp\fP, the output is in machine readable form. .TQ .B -v, --verbose Show extended detail .PP Options for program information. .TQ .B "-V, --version" Show program version. .TQ .B "--settings" Report option settings in effect. .TQ .BR -h , --help Show program help. .TQ .B "--hh" Show program help including hidden options. Hidden options include alternative option names, experimental and deprecated options, and ones for debugging. .PP Options for monitor selection. If none are specified, the default is the first detected monitor. Options \fB--mfg\fP, \fB--model\fP and \fB--sn\fP can be specified together. .TQ .BR "-d , --dis , --display " , .I display-number logical display number (starting from 1) .TQ .BR "-b,--bus " .I bus-number I2C bus number .TQ .BR "--hiddev " .I device number hiddev device number .TQ .BI "-u,--usb " "busnum.devicenum" USB bus and device numbers .TQ .B -g,--mfg 3 letter manufacturer code .TQ .B -l,--model model name .TQ .B -n,--sn serial number. (This is the "serial ascii" field from the EDID, not the binary serial number.) .TQ \fB-e,--edid\fP 256 hex character representation of the 128 byte EDID. Needless to say, this is intended for program use. .PP Feature selection filters .TQ .B "-U, --show-unsupported" Normally, \fBgetvcp\fP does not report unsupported features when querying a feature-group. This option forces output. .TQ .B "--show-table | --no-table Normally, \fBgetvcp\fP does not report Table type features when querying a feature-group. \fB--show-table\fP forces output. \fB--no-table\fP is the default. .TQ .B "--rw, --ro, --wo" Limit \fBgetvcp\fP or \fBvcpinfo\fP output to read-write, read-only, or (for \fBvcpinfo\fP) write-only features. .PP Options for diagnostic output .TQ .B --ddcdata Reports DDC protocol errors. These may reflect I2C bus errors, or deviations by monitors from the MCCS specification. Formerly named \fB--ddc\fP, .TQ .BR --stats " [" all | errors | tries | calls | elapsed | time ] Report execution statistics. I2C bus communication is inherently unreliable. It is the responsibility of the program using the bus, i.e. \fBddcutil\fP, to manage retries in case of failure. This option reports retry counts and various performance statistics. If no argument is specified, or ALL is specified, then all statistics are output. ELAPSED is a synonym for TIME. CALLS implies TIME. .br Specify this option multiple times to report multiple statistics groups. .TQ .BR --vstats " [" all | errors | tries | calls | elapsed | time ] Like \fB--stats\fP, but includes per-display statistics. .TQ .BR --istats " [" all | errors | tries | calls | elapsed | time ] Like \fB--vstats\fP, but includes additional internal information. .TQ .BI --syslog " [" debug | verbose | info | notice | warn | error | never " ]" Write messages of the specified or more urgent severity level to the system log. The \fBddcutil\fP default is \fBWARN\fP. The \fBlibddcutil\P default is \fBNOTICE\fP. ./" .TQ ./" .BI "--libddcutil-trace-file" file name ./" Direct trace output to the specified file instead of the terminal. This is a \fBlibddcutil\fP only option. ./" .TQ ./" .BI "--trace" trace-class-name ./" Trace all functions in a trace class. For a list of trace classes, use \fI--help --verbose\fP. ./" .TQ ./" .BI "--trcfunc" function-name ./" Trace a specific function. .PP Options that tune execution .TQ .B "--enable-capabilities-cache, --disable-capabilities-cache" Enable or disable caching of capabilities strings, improving performance. The default is .B --enable-capabilities-cache .TQ .\" .B "--enable-displays-cache, --disable-displays-cache" .\" Enable or disable caching of information about detected displays, improving performance. .\" The default is .\".B "--enable-displays-cache" .TQ .B "--enable-dynamic-sleep, --disable-dynamic-sleep" Dynamically adjust the sleep-multiplier over multiple \fBddcutil\fP invocations, improving performance. The default is .B "--enable-dynamic-sleep" .TQ .BI "--min-dynamic-multiplier " "decimal number" Modify the dynamic sleep algorithm to never adjust the sleep multiplier below this value. This option can help dampen swings in sleep multiplier values. .TQ .BI "--sleep-multiplier " "decimal number" Adjust the length of waits listed in the DDC/CI specification by this number to determine the actual wait time. Well behaved monitors work with sleep-multiplier values less than 1.0, while monitors with poor DDC implementations may require sleep-multiplier values greater than 1.0. In general, newer option \fB--enable-dynamic-sleep\fP will provide better performance. .\" .TQ .\" .B "--lazy-sleep" .\" Peform mandated sleeps before the next DDC/CI operation instead of immediately after the .\" DDC/CI operation that specified a delay, marginally improving performance. .\" .TQ .\" .B "--i2c-bus-checks-async-min" .\" (experimental option) During display detection, examine I2C buses in parallel to see if a monitor is present. .\" These are low level checks that do not test DDC communication. The default is .\" .B "--i2c-bus-checks-async-min 99" .\" (i.e. never). .\" .TQ .\" .B "--ddc-checks-async-min" .\" If there are several monitors, initial DDC checks are performed in multiple threads, improving performance. .\" This option was formerly (and ambiguously) named \fB--async\fP. The default is .\" .B "--ddc-checks-async-min 3" .TQ .B "--skip-ddc-checks" Assume DDC communication works and monitors properly use the invalid feature flag in a DDC/CI Reply packet to indicate an unsupported feature, improving display detection performance. .TQ .B "--discard-cache [capabilities|dsa|all" Discard cached display information and/or dynamic sleep data. .PP Options that modify behavior .TQ .BI "--maxtries " "(max-read-tries, max-write-read-tries, max-multi-part-tries)" Adjust the number of retries. A value of "." or "0" leaves the setting for a retry type unchanged. .TQ .B "--verify | --noverify" Verify or do not verify values set by \fBsetvcp\fP or \fBloadvcp\fP. \fB--noverify\fP is the default. .TQ .BI "--mccs " "MCCS version" Tailor command input and output to a particular MCCS version, e.g. 2.1 .TQ .B "--enable-udf, --disable-udf" Enable or disable support for user supplied feature definitions. The default is .B "--enable-udf" .TQ .B "--enable-usb, --disable-usb" Enable or disable support for monitors that implement USB communication with the Virtual Control Panel. (These options are available only if \fBddcutil\fP was built with USB support.) The default is .B "--disable-usb" .TQ .BI "--ignore-usb-vid-pid " vid:pid Force \fBddcutil\fP to ignore a particular USB device, specified by its 4 hex digit vendor id and its 4 hex digit product id. .TQ .BI "--ignore-hiddev " hiddev-device-number Force \fBddcutil\fI to ignore a particular USB device, specified by /dev/usb/hiddev device number .TQ .BI "--use-file-io | --use-ioctl-io" Cause \fBddcutil\fP to use the write()/read() interface or the ioctl interface of driver dev-i2c to send and receive I2C packets. By default, \fBddcutil\fP uses the ioctl interface. Nvidia proprietary driver are built in a way such that the ioctl interface can fail, in which case \fBddcutil\fP switches to using the file io interface. .TQ .B "--force-slave-address" Take control of slave addresses on the I2C bus even they are in use. Has use only with file-io, not with ioctl-io. .TQ .BI "--enable-cross-instance-locks | --disable-cross-instance-locks" Coordinates /dev/i2c device access across multiple instance of \fBddcutil\fP and \fBlibddcutil\fP. The default is .B "--enable-cross-instance-locks" .TQ .BI "--edid-read-size " "128|256" Force \fBddcutil\fP to read the specified number of bytes when reading the EDID. This option is a work-around for certain driver bugs. The default is 256. .TQ .BI "--i2c-source-addr " hex-addr Use this as the source address in DDC packet, instead of the normal value. This option has been found to enable access some control functions when using some displays, particularly from LG. .TQ .B "--permit-unknown-feature" Allow \fBsetvcp\fP of unknown features. .PP Miscellaneous .TQ .BI "--ignore-mmid " monitor-model-id Ignore monitors with this monitor-model-id. The see the monitor-model-id for a display, use command \fBddcutil --verbose\fP. .TQ .BR "--noconfig " Do not process the configuration file .\" .SH EXECUTION ENVIRONMENT .\" Requires read/write access to /dev/i2c devices. See .\".UR http://www.ddcutil.com/i2c_permissions. .\".UE .SH NVIDIA PROPRIETARY DRIVER Some Nvidia cards using the proprietary Nvidia driver require special settings to properly enable I2C support. See .UR http://www.ddcutil.com/nvidia .UE . .SH VIRTUAL MACHINES Virtualized video drivers in VMWare and VirtualBox do not provide I2C emulation. Use of normal video drivers with PCI passthrough is possible. .SH EXAMPLES .\" What do .EX and .EE do? .B ddcutil detect .sp 0 Identify all attached monitors. .sp 4 .B ddcutil getvcp supported .sp 1 .br Show all settings that the default monitor supports and that \fBddcutil\fP understands. .PP .sp 0 .B ddcutil getvcp 10 --display 2 .br Query the luminosity value of the second monitor. .B ddcutil setvcp 10 30 --bus 4 .sp 0 Set the luminosity value for the monitor on bus /dev/i2c-4. .B ddcutil vcpinfo --verbose .sp 0 Show detailed information about VCP features that \fBddcutil\fP understands. .B ddcutil interrogate > ~/ddcutil.out .sp 0 Collect maximum information about monitor capabilities and the execution environment, and direct the output to a file. .SH DIAGNOSTICS Returns 0 on success, 1 on failure. Requesting help is regarded as success. .\" .SH FILES .SH SEE ALSO .\" README file /usr/local/share/doc/ddcutil/README.md .\" The program is documented fully in .\" .br .\" /usr/local/share/doc/ddcutil/html/index.html .\" .PP The project homepage: .UR http://www.ddcutil.com .UE .\" .SH NOTES .\" .SH BUGS .SH AUTHOR Sanford Rockowitz (rockowitz at minsoft dot com) .br Copyright 2015\-2023 Sanford Rockowitz ddcutil-2.2.0/data/0000775000175000001440000000000014754576333007634 5ddcutil-2.2.0/data/cmake/0000775000175000001440000000000014754576333010714 5ddcutil-2.2.0/data/cmake/ddcutil/0000775000175000001440000000000014754576333012344 5ddcutil-2.2.0/data/cmake/ddcutil/FindDDCUtil.cmake0000644000175000001440000000477614441414365015320 # - Try to find Libddcutil # Once done this will define # # DDCUTIL_FOUND - system has DDCUtil # DDCUTIL_INCLUDE_DIR - the libddcutil include directory # DDCUTIL_LIBS - The libddcutil libraries # Copyright (c) 2017, Dorian Vogel, # # 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. find_package(PkgConfig) pkg_check_modules(PC_LIBDDCUTIL QUIET ddcutil) set(LIBDDCUTIL_DEFINITIONS ${PC_LIBDDCUTIL_CFLAGS_OTHER}) find_path(LIBDDCUTIL_INCLUDE_DIR ddcutil_c_api.h HINTS ${PC_LIBDDCUTIL_INCLUDEDIR} ${PC_LIBDDCUTIL_INCLUDE_DIRS}) find_library(LIBDDCUTIL_LIBRARY NAMES libddcutil.so HINTS ${PC_LIBDDCUTIL_LIBDIR} ${PC_LIBDDCUTIL_LIBRARY_DIRS} ) include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set LIBDDCUTIL_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args(ddcutil DEFAULT_MSG LIBDDCUTIL_LIBRARY LIBDDCUTIL_INCLUDE_DIR) mark_as_advanced(LIBDDCUTIL_INCLUDE_DIR LIBDDCUTIL_LIBRARY ) set(LIBDDCUTIL_LIBRARIES ${LIBDDCUTIL_LIBRARY} ) set(LIBDDCUTIL_INCLUDE_DIRS ${LIBDDCUTIL_INCLUDE_DIR} ) ddcutil-2.2.0/data/etc/0000775000175000001440000000000014754576333010407 5ddcutil-2.2.0/data/etc/modprobe.d/0000775000175000001440000000000014754576333012440 5ddcutil-2.2.0/data/etc/modprobe.d/nvidia-i2c.conf0000644000175000001440000000022714572333721015141 # modprobe.d file to set proprietary Nvidia driver options often needed for DDC/CI options nvidia NVreg_RegistryDwords=RMUseSwI2c=0x01;RMI2cSpeed=100 ddcutil-2.2.0/data/etc/udev/0000775000175000001440000000000014754576333011352 5ddcutil-2.2.0/data/etc/udev/rules.d/0000775000175000001440000000000014754576333012726 5ddcutil-2.2.0/data/etc/udev/rules.d/60-ddcutil-i2c.rules0000644000175000001440000000176214572333721016242 # Sample rules to grant RW access to /dev/i2c devices. # This sample file can be modified and copied to /etc/udev/rules.d. If file # /etc/udev/rules.d/60-ddcutil-i2c.rules exists, it overrides a file with the # same name in /usr/lib/udev/rules.d, which is created by ddcutil installation. # This can be useful in cases where the usual rules do not work as needed, or # during development. # The usual case, using TAG+="uaccess": If a /dev/i2c device is associated # with a video adapter, grant the current user access to it. # SUBSYSTEM=="i2c-dev", KERNEL=="i2c-[0-9]*", ATTRS{class}=="0x030000", TAG+="uaccess" # Assigns i2c devices to group i2c, and gives that group RW access. # Individual users must then be assigned to group i2c. # On some distributions, installing package i2c-tools creates this rule. # (For example, on Ubuntu, see 40-i2c-tools.rules.) # KERNEL=="i2c-[0-9]*", GROUP="i2c", MODE="0660" # Gives everyone RW access to the /dev/i2c devices: # KERNEL=="i2c-[0-9]*", MODE="0666" ddcutil-2.2.0/data/etc/udev/rules.d/60-ddcutil-usb.rules0000644000175000001440000000250114754153540016347 # Rules for monitors implementing USB communication with their Virtual Control Panel. # This sample file can be modified and copied to /etc/udev/rules.d. # If file /etc/udev/rules.d/60-ddcutil-usb.rules exists, it overrides a file with # the same name in /usr/lib/udev/rules.d. (This file used to be created by ddcutil # installation.) # The simplest solution is to specify a particular monitor device by its vid/pid, # and then use TAG+="uaccess" to grant the current user read/write access to it. # The values in this example are for an Apple Cinema Display, model A1082: # SUBSYSTEM=="usbmisc", ATTRS{idVendor}=="05ac", ATTRS{idProduct}=="9223", TAG+="uaccess" # A more general solution is to use ddcutil chkusbmon to check if a USB Human # Interface device implements the USB Device Class Definition for Human Interface # Devices. Unfortunately, this has been seen to cause system instability in # certain ill-defined cases. # Note this rule may have to be adjusted to reflect the actual path where # ddcutil is installed. The -v option produces informational messages. # These are lost when the rule is normally executed by udev, but can be # helpful when rules are tested using the "udevadm test" command. # SUBSYSTEM=="usbmisc", KERNEL=="hiddev*", PROGRAM="/usr/bin/ddcutil chkusbmon $env{DEVNAME} -v", TAG+="uaccess" ddcutil-2.2.0/data/etc/X11/0000775000175000001440000000000014754576333010760 5ddcutil-2.2.0/data/etc/X11/xorg.conf.d/0000775000175000001440000000000014754576333013105 5ddcutil-2.2.0/data/etc/X11/xorg.conf.d/90-nvidia-i2c.conf0000644000175000001440000000064214572333721016035 # xorg.conf.d file specifying proprietary Nvidia driver options often needed for DDC/CI Section "Device" Driver "nvidia" Identifier "Dev0" Option "RegistryDwords" "RMUseSwI2c=0x01; RMI2cSpeed=100" # solves problem of i2c errors with nvidia driver # per https://devtalk.nvidia.com/default/topic/572292/-solved-does-gddccontrol-work-for-anyone-here-nvidia-i2c-monitor-display-ddc/#4309293 EndSection ddcutil-2.2.0/data/usr/0000775000175000001440000000000014754576333010445 5ddcutil-2.2.0/data/usr/lib/0000775000175000001440000000000014754576333011213 5ddcutil-2.2.0/data/usr/lib/modules-load.d/0000775000175000001440000000000014754576333014022 5ddcutil-2.2.0/data/usr/lib/modules-load.d/ddcutil.conf0000644000175000001440000000001014572333721016214 i2c-dev ddcutil-2.2.0/data/usr/lib/udev/0000775000175000001440000000000014754576333012156 5ddcutil-2.2.0/data/usr/lib/udev/rules.d/0000775000175000001440000000000014754576333013532 5ddcutil-2.2.0/data/usr/lib/udev/rules.d/60-ddcutil-i2c.rules0000644000175000001440000000021414754153540017036 SUBSYSTEM=="i2c-dev", KERNEL=="i2c-[0-9]*", ATTRS{class}=="0x030000", TAG+="uaccess" SUBSYSTEM=="dri", KERNEL=="card[0-9]*", TAG+="uaccess" ddcutil-2.2.0/data/Makefile.am0000644000175000001440000001052214754153540011575 # File data/Makefile.am # Copyright (C) 2016-2024 Sanford Rockowitz # SPDX-License-Identifier: GPL-2.0-or-later # The proper location for pkgconfig files is ambiguous, and the # subject of much discussion. . # However, it appears that: # - /usr/lib64/pkgconfig should hold x64 specific pkgconfig files # - /usr/lib/pkgconfig should hold i386 specific pkgconfig files # - /usr/share/pkgconfig should hold architecture agnostic pkgconfig files # # The tail wags the dog. libddcutil-dev can contain # usr/*/pkgconfig # or # usr/lib/x86_64-linux-gnu/pkgconfig # but there's no way to "or" these two statements. # # When building on OBS, the same libddcutil-dev.install is used for all (Debian based) builds, # and if using $(libdir) the location of ddcutil.pc will depend on platform, e.g. # some times it will be /usr/lib/x86_64-linux-gnu/pkgconfig, sometimes something else. # # Note the the entry for ddcutil.pc in the Debian .install file needs # to be kept in sync with where autotools puts the files. resfiles = \ etc/modprobe.d/nvidia-i2c.conf \ etc/udev/rules.d/60-ddcutil-i2c.rules \ etc/udev/rules.d/60-ddcutil-usb.rules \ etc/X11/xorg.conf.d/90-nvidia-i2c.conf rulesfiles = \ usr/lib/udev/rules.d/60-ddcutil-i2c.rules distributed_modulesfiles = \ usr/lib/modules-load.d/ddcutil.conf if !INSTALL_LIB_ONLY_COND installed_modulesfiles = \ usr/lib/modules-load.d/ddcutil.conf endif pkgconfigfiles = \ ddcutil.pc # Causes files (with directory structure) to be included in tarball: EXTRA_DIST = $(resfiles) $(rulesfiles) $(distributed_modulesfiles) ddcutil.pc.in # Target directory pkgconfigdir = ${libdir}/pkgconfig # Target directory (/usr/local/share/ddcutil/data or /usr/share/ddcutil/data): ddcutildir = $(datadir)/ddcutil/data resdir = $(datadir)/ddcutil/data # Causes files (w/o directory structure) to be installed in target directory: if !INSTALL_LIB_ONLY_COND ddcutil_DATA = $(resfiles) pkgconfig_DATA = ddcutil.pc endif # Use prefix instead of libdir here because it appears that # udev/rules.d is always a subdirectory of /usr/lib rulesdir = ${prefix}/lib/udev/rules.d if !INSTALL_LIB_ONLY_COND rules_DATA = $(rulesfiles) endif # Similar comment for modules-load.d installed_modulesdir = $(prefix)/lib/modules-load.d if !INSTALL_LIB_ONLY_COND installed_modules_DATA = $(installed_modulesfiles) endif # include FindDDCUtil.cmake in tarball: EXTRA_DIST += cmake/ddcutil/FindDDCUtil.cmake # where FindDDCUtil.cmake will installed: cmakedir = $(libdir)/cmake/ddcutil if ENABLE_SHARED_LIB_COND if !INSTALL_LIB_ONLY_COND # where make install finds FindDDCUtil.cmake: cmake_DATA = cmake/ddcutil/FindDDCUtil.cmake endif endif # n. -local executes before target, -hook executes after all-local: @echo "(data/Makefile) ==> Executing rule: all-local" install-data-local: @echo "(data/Makefile) ==> Executing rule: install-data-local" @echo "prefix: ${prefix}" @echo "includedir ${includedir}" @echo "docdir ${docdir}" @echo "libdir ${libdir}" @echo "rulesdir ${rulesdir}" @echo "packagedatadir: $(packagedatadir)" @echo "datadir: $(datadir)" @echo "ddcutildir: $(ddcutildir)" @echo "srcdir: $(srcdir)" @echo "bindir: ${bindir}" @echo "cmakedir: ${cmakedir}" @echo "DESTDIR: ${DESTDIR}" @echo "rulesfiles: ${rulesfiles}" @echo "resfiles: ${resfiles}" @echo "udevdir: ${udevdir}" # @xxx@ names are not defined, names with $() are # use "find ..." instead of "rm -f" as latter tries to delete directory as well # rm -f ${DESTDIR}${resdir}/45-ddcutil* # rm -f ${DESTDIR}${rulesdir}/60-ddcutil.rules # rm -f ${DESTDIR}${rulesdir}/60-ddcutil-usb.rules install-data-hook: @echo "(data/install-data-hook)===> Executing rule: install-data-hook" # if !INSTALL_LIB_ONLY_COND # sed -i "s|/usr|${prefix}|" ${DESTDIR}${rulesdir}/60-ddcutil-usb.rules # endif @echo "Clear out files possibly left over from earlier installation" find ${DESTDIR}${resdir} -name "45-ddcutil*" -delete find ${DESTDIR}${resdir} -name "60-ddcutil.rules" -delete uninstall-hook: @echo "(data/uninstall-hook)===> Executing rule: uninstall-hook" @echo "Clear out files possibly left over from earlier installation" find ${DESTDIR}${resdir} -name "45-ddcutil.rules" -delete find ${DESTDIR}${rulesdir} -name "60-ddcutil-usb.rules" -delete ddcutil-2.2.0/data/Makefile.in0000664000175000001440000006071514754576155011634 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # File data/Makefile.am # Copyright (C) 2016-2024 Sanford Rockowitz # SPDX-License-Identifier: GPL-2.0-or-later # The proper location for pkgconfig files is ambiguous, and the # subject of much discussion. . # However, it appears that: # - /usr/lib64/pkgconfig should hold x64 specific pkgconfig files # - /usr/lib/pkgconfig should hold i386 specific pkgconfig files # - /usr/share/pkgconfig should hold architecture agnostic pkgconfig files # # The tail wags the dog. libddcutil-dev can contain # usr/*/pkgconfig # or # usr/lib/x86_64-linux-gnu/pkgconfig # but there's no way to "or" these two statements. # # When building on OBS, the same libddcutil-dev.install is used for all (Debian based) builds, # and if using $(libdir) the location of ddcutil.pc will depend on platform, e.g. # some times it will be /usr/lib/x86_64-linux-gnu/pkgconfig, sometimes something else. # # Note the the entry for ddcutil.pc in the Debian .install file needs # to be kept in sync with where autotools puts the files. VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = data ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = ddcutil.pc CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(cmakedir)" "$(DESTDIR)$(ddcutildir)" \ "$(DESTDIR)$(installed_modulesdir)" \ "$(DESTDIR)$(pkgconfigdir)" "$(DESTDIR)$(rulesdir)" DATA = $(cmake_DATA) $(ddcutil_DATA) $(installed_modules_DATA) \ $(pkgconfig_DATA) $(rules_DATA) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/ddcutil.pc.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ resfiles = \ etc/modprobe.d/nvidia-i2c.conf \ etc/udev/rules.d/60-ddcutil-i2c.rules \ etc/udev/rules.d/60-ddcutil-usb.rules \ etc/X11/xorg.conf.d/90-nvidia-i2c.conf rulesfiles = \ usr/lib/udev/rules.d/60-ddcutil-i2c.rules distributed_modulesfiles = \ usr/lib/modules-load.d/ddcutil.conf @INSTALL_LIB_ONLY_COND_FALSE@installed_modulesfiles = \ @INSTALL_LIB_ONLY_COND_FALSE@ usr/lib/modules-load.d/ddcutil.conf pkgconfigfiles = \ ddcutil.pc # Causes files (with directory structure) to be included in tarball: # include FindDDCUtil.cmake in tarball: EXTRA_DIST = $(resfiles) $(rulesfiles) $(distributed_modulesfiles) \ ddcutil.pc.in cmake/ddcutil/FindDDCUtil.cmake # Target directory pkgconfigdir = ${libdir}/pkgconfig # Target directory (/usr/local/share/ddcutil/data or /usr/share/ddcutil/data): ddcutildir = $(datadir)/ddcutil/data resdir = $(datadir)/ddcutil/data # Causes files (w/o directory structure) to be installed in target directory: @INSTALL_LIB_ONLY_COND_FALSE@ddcutil_DATA = $(resfiles) @INSTALL_LIB_ONLY_COND_FALSE@pkgconfig_DATA = ddcutil.pc # Use prefix instead of libdir here because it appears that # udev/rules.d is always a subdirectory of /usr/lib rulesdir = ${prefix}/lib/udev/rules.d @INSTALL_LIB_ONLY_COND_FALSE@rules_DATA = $(rulesfiles) # Similar comment for modules-load.d installed_modulesdir = $(prefix)/lib/modules-load.d @INSTALL_LIB_ONLY_COND_FALSE@installed_modules_DATA = $(installed_modulesfiles) # where FindDDCUtil.cmake will installed: cmakedir = $(libdir)/cmake/ddcutil # where make install finds FindDDCUtil.cmake: @ENABLE_SHARED_LIB_COND_TRUE@@INSTALL_LIB_ONLY_COND_FALSE@cmake_DATA = cmake/ddcutil/FindDDCUtil.cmake all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign data/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign data/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): ddcutil.pc: $(top_builddir)/config.status $(srcdir)/ddcutil.pc.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-cmakeDATA: $(cmake_DATA) @$(NORMAL_INSTALL) @list='$(cmake_DATA)'; test -n "$(cmakedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(cmakedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(cmakedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(cmakedir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(cmakedir)" || exit $$?; \ done uninstall-cmakeDATA: @$(NORMAL_UNINSTALL) @list='$(cmake_DATA)'; test -n "$(cmakedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(cmakedir)'; $(am__uninstall_files_from_dir) install-ddcutilDATA: $(ddcutil_DATA) @$(NORMAL_INSTALL) @list='$(ddcutil_DATA)'; test -n "$(ddcutildir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(ddcutildir)'"; \ $(MKDIR_P) "$(DESTDIR)$(ddcutildir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(ddcutildir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(ddcutildir)" || exit $$?; \ done uninstall-ddcutilDATA: @$(NORMAL_UNINSTALL) @list='$(ddcutil_DATA)'; test -n "$(ddcutildir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(ddcutildir)'; $(am__uninstall_files_from_dir) install-installed_modulesDATA: $(installed_modules_DATA) @$(NORMAL_INSTALL) @list='$(installed_modules_DATA)'; test -n "$(installed_modulesdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(installed_modulesdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(installed_modulesdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(installed_modulesdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(installed_modulesdir)" || exit $$?; \ done uninstall-installed_modulesDATA: @$(NORMAL_UNINSTALL) @list='$(installed_modules_DATA)'; test -n "$(installed_modulesdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(installed_modulesdir)'; $(am__uninstall_files_from_dir) install-pkgconfigDATA: $(pkgconfig_DATA) @$(NORMAL_INSTALL) @list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgconfigdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pkgconfigdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(pkgconfigdir)" || exit $$?; \ done uninstall-pkgconfigDATA: @$(NORMAL_UNINSTALL) @list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(pkgconfigdir)'; $(am__uninstall_files_from_dir) install-rulesDATA: $(rules_DATA) @$(NORMAL_INSTALL) @list='$(rules_DATA)'; test -n "$(rulesdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(rulesdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(rulesdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(rulesdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(rulesdir)" || exit $$?; \ done uninstall-rulesDATA: @$(NORMAL_UNINSTALL) @list='$(rules_DATA)'; test -n "$(rulesdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(rulesdir)'; $(am__uninstall_files_from_dir) tags TAGS: ctags CTAGS: cscope cscopelist: distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(DATA) all-local installdirs: for dir in "$(DESTDIR)$(cmakedir)" "$(DESTDIR)$(ddcutildir)" "$(DESTDIR)$(installed_modulesdir)" "$(DESTDIR)$(pkgconfigdir)" "$(DESTDIR)$(rulesdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-cmakeDATA install-data-local \ install-ddcutilDATA install-installed_modulesDATA \ install-pkgconfigDATA install-rulesDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-cmakeDATA uninstall-ddcutilDATA \ uninstall-installed_modulesDATA uninstall-pkgconfigDATA \ uninstall-rulesDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: install-am install-data-am install-strip uninstall-am .PHONY: all all-am all-local check check-am clean clean-generic \ clean-libtool cscopelist-am ctags-am distclean \ distclean-generic distclean-libtool distdir dvi dvi-am html \ html-am info info-am install install-am install-cmakeDATA \ install-data install-data-am install-data-hook \ install-data-local install-ddcutilDATA install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am \ install-installed_modulesDATA install-man install-pdf \ install-pdf-am install-pkgconfigDATA install-ps install-ps-am \ install-rulesDATA install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags-am uninstall uninstall-am uninstall-cmakeDATA \ uninstall-ddcutilDATA uninstall-hook \ uninstall-installed_modulesDATA uninstall-pkgconfigDATA \ uninstall-rulesDATA .PRECIOUS: Makefile # n. -local executes before target, -hook executes after all-local: @echo "(data/Makefile) ==> Executing rule: all-local" install-data-local: @echo "(data/Makefile) ==> Executing rule: install-data-local" @echo "prefix: ${prefix}" @echo "includedir ${includedir}" @echo "docdir ${docdir}" @echo "libdir ${libdir}" @echo "rulesdir ${rulesdir}" @echo "packagedatadir: $(packagedatadir)" @echo "datadir: $(datadir)" @echo "ddcutildir: $(ddcutildir)" @echo "srcdir: $(srcdir)" @echo "bindir: ${bindir}" @echo "cmakedir: ${cmakedir}" @echo "DESTDIR: ${DESTDIR}" @echo "rulesfiles: ${rulesfiles}" @echo "resfiles: ${resfiles}" @echo "udevdir: ${udevdir}" # @xxx@ names are not defined, names with $() are # use "find ..." instead of "rm -f" as latter tries to delete directory as well # rm -f ${DESTDIR}${resdir}/45-ddcutil* # rm -f ${DESTDIR}${rulesdir}/60-ddcutil.rules # rm -f ${DESTDIR}${rulesdir}/60-ddcutil-usb.rules install-data-hook: @echo "(data/install-data-hook)===> Executing rule: install-data-hook" # if !INSTALL_LIB_ONLY_COND # sed -i "s|/usr|${prefix}|" ${DESTDIR}${rulesdir}/60-ddcutil-usb.rules # endif @echo "Clear out files possibly left over from earlier installation" find ${DESTDIR}${resdir} -name "45-ddcutil*" -delete find ${DESTDIR}${resdir} -name "60-ddcutil.rules" -delete uninstall-hook: @echo "(data/uninstall-hook)===> Executing rule: uninstall-hook" @echo "Clear out files possibly left over from earlier installation" find ${DESTDIR}${resdir} -name "45-ddcutil.rules" -delete find ${DESTDIR}${rulesdir} -name "60-ddcutil-usb.rules" -delete # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/data/ddcutil.pc.in0000644000175000001440000000061114572333721012117 prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: @PACKAGE@ Description: Control display settings URL: http://www.ddcutil.com Version: @VERSION@ # No. These are packages required by the library, not the caller # Requires: @REQUIRED_PACKAGES@ # Libs and Cflags not needed since using default locations Libs: -L${libdir} -lddcutil Cflags: -I${includedir} ddcutil-2.2.0/docs/0000775000175000001440000000000014754576333007653 5ddcutil-2.2.0/docs/Makefile.am0000677000175000001440000000120513134651763011621 SUBDIRS = # SUBDIRS += ddcutil if USE_DOXYGEN SUBDIRS += doxygen endif if USE_DOXYGEN if HAVE_DOCBASE docbasedir = $(datadir)/doc-base docbase_DATA = ddcutil-c-api EXTRA_DIST = ddcutil-c-api install-data-local: @echo "(docs/Makefile) Executing rule install-data-local" install-data-hook: @echo "(docs/Makefile) Executing rule install-data-hook" @echo "docbasedir $(docbasedir)" @echo "datadir $(datadir)" install-docs --install-changed # uninstall-data-hook doesn't exist, use uninstall-hook: uninstall-hook: @echo "(docs/Makefile) Executing rule uninstall-data-hook" install-docs --install-changed endif endif ddcutil-2.2.0/docs/Makefile.in0000664000175000001440000005740114754576155011651 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ # SUBDIRS += ddcutil @USE_DOXYGEN_TRUE@am__append_1 = doxygen subdir = docs ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = ddcutil-c-api CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(docbasedir)" DATA = $(docbase_DATA) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = doxygen am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/ddcutil-c-api.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUBDIRS = $(am__append_1) @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@docbasedir = $(datadir)/doc-base @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@docbase_DATA = ddcutil-c-api @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@EXTRA_DIST = ddcutil-c-api all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign docs/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign docs/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): ddcutil-c-api: $(top_builddir)/config.status $(srcdir)/ddcutil-c-api.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-docbaseDATA: $(docbase_DATA) @$(NORMAL_INSTALL) @list='$(docbase_DATA)'; test -n "$(docbasedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(docbasedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(docbasedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(docbasedir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(docbasedir)" || exit $$?; \ done uninstall-docbaseDATA: @$(NORMAL_UNINSTALL) @list='$(docbase_DATA)'; test -n "$(docbasedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(docbasedir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(DATA) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(docbasedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." @HAVE_DOCBASE_FALSE@install-data-local: @USE_DOXYGEN_FALSE@install-data-local: @HAVE_DOCBASE_FALSE@install-data-hook: @USE_DOXYGEN_FALSE@install-data-hook: @HAVE_DOCBASE_FALSE@uninstall-hook: @USE_DOXYGEN_FALSE@uninstall-hook: clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-data-local install-docbaseDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-docbaseDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: $(am__recursive_targets) install-am install-data-am \ install-strip uninstall-am .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am \ install-data-hook install-data-local install-docbaseDATA \ install-dvi install-dvi-am install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am uninstall-docbaseDATA uninstall-hook .PRECIOUS: Makefile @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@install-data-local: @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@ @echo "(docs/Makefile) Executing rule install-data-local" @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@install-data-hook: @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@ @echo "(docs/Makefile) Executing rule install-data-hook" @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@ @echo "docbasedir $(docbasedir)" @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@ @echo "datadir $(datadir)" @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@ install-docs --install-changed # uninstall-data-hook doesn't exist, use uninstall-hook: @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@uninstall-hook: @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@ @echo "(docs/Makefile) Executing rule uninstall-data-hook" @HAVE_DOCBASE_TRUE@@USE_DOXYGEN_TRUE@ install-docs --install-changed # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/docs/ddcutil-c-api.in0000677000175000001440000000055613276144706012545 Document: ddcutil-c-api Title: ddcutil C API Author: Sanford Rockowitz Abstract: This doxgygen generated manual documents the ddcutil C API. You're probably better off just looking at the header files and sample code. Section: System/Hardware Format: HTML Index: @prefix@/share/doc/ddcutil/html/index.html Files: @prefix@/share/doc/ddcutil/html/* ddcutil-2.2.0/docs/doxygen/0000775000175000001440000000000014754576333011330 5ddcutil-2.2.0/docs/doxygen/Makefile.am0000677000175000001440000000065213032550072013267 docpkg = $(PACKAGE_TARNAME)-doxy-$(PACKAGE_VERSION).tar.gz doc_DATA = $(docpkg) $(docpkg): doxygen.stamp tar chof - html | gzip -9 -c >$@ doxygen.stamp: doxyfile $(DOXYGEN) $(DOXYFLAGS) $< echo Timestamp > $@ install-data-hook: cd $(DESTDIR)$(docdir) && tar xf $(docpkg) uninstall-hook: cd $(DESTDIR)$(docdir) && rm -rf html CLEANFILES = doxywarn.txt doxygen.stamp $(docpkg) clean-local: rm -rf html ddcutil-2.2.0/docs/doxygen/Makefile.in0000664000175000001440000004116314754576155013324 # Makefile.in generated by automake 1.16.5 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2021 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = docs/doxygen ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ax_prog_doxygen.m4 \ $(top_srcdir)/m4/flm_prog_try_doxygen.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = doxyfile CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(docdir)" DATA = $(doc_DATA) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/doxyfile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DBG = @DBG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DOCBASE_INSTALL_DOCS = @DOCBASE_INSTALL_DOCS@ DOXYGEN = @DOXYGEN@ DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DX_CONFIG = @DX_CONFIG@ DX_DOCDIR = @DX_DOCDIR@ DX_DOT = @DX_DOT@ DX_DOXYGEN = @DX_DOXYGEN@ DX_DVIPS = @DX_DVIPS@ DX_EGREP = @DX_EGREP@ DX_ENV = @DX_ENV@ DX_FLAG_chi = @DX_FLAG_chi@ DX_FLAG_chm = @DX_FLAG_chm@ DX_FLAG_doc = @DX_FLAG_doc@ DX_FLAG_dot = @DX_FLAG_dot@ DX_FLAG_html = @DX_FLAG_html@ DX_FLAG_man = @DX_FLAG_man@ DX_FLAG_pdf = @DX_FLAG_pdf@ DX_FLAG_ps = @DX_FLAG_ps@ DX_FLAG_rtf = @DX_FLAG_rtf@ DX_FLAG_xml = @DX_FLAG_xml@ DX_HHC = @DX_HHC@ DX_LATEX = @DX_LATEX@ DX_MAKEINDEX = @DX_MAKEINDEX@ DX_PDFLATEX = @DX_PDFLATEX@ DX_PERL = @DX_PERL@ DX_PROJECT = @DX_PROJECT@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ ENABLE_BUILD_TIMESTAMP_FLAG = @ENABLE_BUILD_TIMESTAMP_FLAG@ ENABLE_ENVCMDS_FLAG = @ENABLE_ENVCMDS_FLAG@ ENABLE_SHARED_LIB_FLAG = @ENABLE_SHARED_LIB_FLAG@ ENABLE_TARGETBSD_FLAG = @ENABLE_TARGETBSD_FLAG@ ENABLE_UDEV_FLAG = @ENABLE_UDEV_FLAG@ ENABLE_USB_FLAG = @ENABLE_USB_FLAG@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ JANSSON_CFLAGS = @JANSSON_CFLAGS@ JANSSON_LIBS = @JANSSON_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBDRM_CFLAGS = @LIBDRM_CFLAGS@ LIBDRM_LIBS = @LIBDRM_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIBTOOL_DEPS = @LIBTOOL_DEPS@ LIBUSB_CFLAGS = @LIBUSB_CFLAGS@ LIBUSB_LIBS = @LIBUSB_LIBS@ LIBX11_CFLAGS = @LIBX11_CFLAGS@ LIBX11_LIBS = @LIBX11_LIBS@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_AGE = @LT_AGE@ LT_CURRENT = @LT_CURRENT@ LT_REVISION = @LT_REVISION@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ REQUIRED_PACKAGES = @REQUIRED_PACKAGES@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ UDEV_CFLAGS = @UDEV_CFLAGS@ UDEV_LIBS = @UDEV_LIBS@ VERSION = @VERSION@ VERSION_VMAJOR = @VERSION_VMAJOR@ VERSION_VMICRO = @VERSION_VMICRO@ VERSION_VMINOR = @VERSION_VMINOR@ VERSION_VSUFFIX = @VERSION_VSUFFIX@ XEXT_CFLAGS = @XEXT_CFLAGS@ XEXT_LIBS = @XEXT_LIBS@ XRANDR_CFLAGS = @XRANDR_CFLAGS@ XRANDR_LIBS = @XRANDR_LIBS@ ZLIB_CFLAGS = @ZLIB_CFLAGS@ ZLIB_LIBS = @ZLIB_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ docpkg = $(PACKAGE_TARNAME)-doxy-$(PACKAGE_VERSION).tar.gz doc_DATA = $(docpkg) CLEANFILES = doxywarn.txt doxygen.stamp $(docpkg) all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign docs/doxygen/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign docs/doxygen/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): doxyfile: $(top_builddir)/config.status $(srcdir)/doxyfile.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-docDATA: $(doc_DATA) @$(NORMAL_INSTALL) @list='$(doc_DATA)'; test -n "$(docdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(docdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(docdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(docdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(docdir)" || exit $$?; \ done uninstall-docDATA: @$(NORMAL_UNINSTALL) @list='$(doc_DATA)'; test -n "$(docdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(docdir)'; $(am__uninstall_files_from_dir) tags TAGS: ctags CTAGS: cscope cscopelist: distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(DATA) installdirs: for dir in "$(DESTDIR)$(docdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-local mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-docDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-docDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: install-am install-data-am install-strip uninstall-am .PHONY: all all-am check check-am clean clean-generic clean-libtool \ clean-local cscopelist-am ctags-am distclean distclean-generic \ distclean-libtool distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am \ install-data-hook install-docDATA install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags-am uninstall \ uninstall-am uninstall-docDATA uninstall-hook .PRECIOUS: Makefile $(docpkg): doxygen.stamp tar chof - html | gzip -9 -c >$@ doxygen.stamp: doxyfile $(DOXYGEN) $(DOXYFLAGS) $< echo Timestamp > $@ install-data-hook: cd $(DESTDIR)$(docdir) && tar xf $(docpkg) uninstall-hook: cd $(DESTDIR)$(docdir) && rm -rf html clean-local: rm -rf html # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: ddcutil-2.2.0/docs/doxygen/doxyfile.in0000677000175000001440000016714313032550072013417 # Doxyfile 1.5.6 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = @PACKAGE_NAME@ # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = @PACKAGE_VERSION@ # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = . # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Farsi, Finnish, French, German, Greek, # Hungarian, Italian, Japanese, Japanese-en (Japanese with English messages), # Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, Polish, # Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, # and Ukrainian. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = @top_srcdir@ # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = YES # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the DETAILS_AT_TOP tag is set to YES then Doxygen # will output the detailed description near the top, like JavaDoc. # If set to NO, the detailed description appears after the member # documentation. # DETAILS_AT_TOP = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 3 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. # OPTIMIZE_OUTPUT_FOR_C = NO OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen to replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES # EXTRACT_ALL = NO EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespace are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = YES # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = YES # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = NO # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. # SHOW_USED_FILES = NO SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. # *** OBSOLETE *** # SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be abled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. # WARN_NO_PARAMDOC = NO WARN_NO_PARAMDOC = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = doxywarn.txt #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @top_srcdir@/src/public/ddcutil_c_api.h @top_srcdir@/src/public/ddcutil_types.h # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx # *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 FILE_PATTERNS = *.c \ *.cc \ *.cxx \ *.cpp \ *.c++ \ *.d \ *.java \ *.ii \ *.ixx \ *.ipp \ *.i++ \ *.inl \ *.h \ *.hh \ *.hxx \ *.hpp \ *.h++ \ *.idl \ *.odl \ *.cs \ *.php \ *.php3 \ *.inc \ *.m \ *.mm \ *.dox \ *.py # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used select whether or not files or # directories that are symbolic links (a Unix filesystem feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER # is applied to all files. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. Otherwise they will link to the documentstion. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = NO #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. # *** OBSOLETE *** # HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to FRAME, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, # Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are # probably better off using the HTML help feature. Other possible values # for this tag are: HIERARCHIES, which will generate the Groups, Directories, # and Class Hiererachy pages using a tree view instead of an ordered list; # ALL, which combines the behavior of FRAME and HIERARCHIES; and NONE, which # disables this behavior completely. For backwards compatibility with previous # releases of Doxygen, the values YES and NO are equivalent to FRAME and NONE # respectively. GENERATE_TREEVIEW = YES # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. # GENERATE_LATEX = NO GENERATE_LATEX = YES # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. # PDF_HYPERLINKS = NO PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. # USE_PDFLATEX = NO USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. # *** OBSOLETE *** # XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. # *** OBSOLETE *** # XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. This is useful # if you want to understand what is going on. On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse # the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option is superseded by the HAVE_DOT option below. This is only a # fallback. It is recommended to install and use dot, since it yields more # powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # By default doxygen will write a font called FreeSans.ttf to the output # directory and reference it in all dot files that doxygen generates. This # font does not include all possible unicode characters however, so when you need # these (or just want a differently looking font) you can specify the font name # using DOT_FONTNAME. You need need to make sure dot is able to find the font, # which can be done by putting it in a standard location or by setting the # DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory # containing the font. DOT_FONTNAME = FreeSans # By default doxygen will tell dot to use the output directory to look for the # FreeSans.ttf font (which doxygen will put there itself). If you specify a # different font using DOT_FONTNAME you can set the path where dot # can find it using this tag. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 1000 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is enabled by default, which results in a transparent # background. Warning: Depending on the platform used, enabling this option # may lead to badly anti-aliased labels on the edges of a graph (i.e. they # become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::additions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO