# -*- mode: sh; tab-width: 4 -*- # vi: ts=4:sw=4:sts=4:et # vim: filetype=sh : # This file contains some useful common functions # Copyright 2007 Yann E. MORIN # Licensed under the GPL v2. See COPYING in the root of this package CT_LoadConfig() { local o oldvals vals # Parse the configuration file # It has some info about the logging facility, so include it early # It also sets KERNEL/ARCH/... for file inclusion below. Does not handle # recursive definitions yet. We don't need arrays at this point. CT_TestOrAbort "Configuration file not found. Please create one." -r .config . ./.config # Prefixing with ./ prevents Bash from searching $PATH # Include sub-scripts instead of calling them: that way, we do not have to # export any variable, nor re-parse the configuration and functions files. . "${CT_LIB_DIR}/scripts/build/internals.sh" . "${CT_LIB_DIR}/scripts/build/arch.sh" . "${CT_LIB_DIR}/scripts/build/companion_tools.sh" . "${CT_LIB_DIR}/scripts/build/kernel/${CT_KERNEL}.sh" . "${CT_LIB_DIR}/scripts/build/companion_libs.sh" . "${CT_LIB_DIR}/scripts/build/binutils/${CT_BINUTILS}.sh" . "${CT_LIB_DIR}/scripts/build/libc.sh" . "${CT_LIB_DIR}/scripts/build/cc/${CT_CC}.sh" . "${CT_LIB_DIR}/scripts/build/debug.sh" . "${CT_LIB_DIR}/scripts/build/test_suite.sh" # Target tuple: CT_TARGET needs a little love: CT_DoBuildTargetTuple # Kludge: If any of the configured options needs CT_TARGET, # then rescan the options file now. This also handles recursive variables; # but we don't want to loop forever if there's a circular reference. oldvals="" try=0 while [ "$try" -le 10 ]; do . ./.config # Prefixing with ./ prevents Bash from searching $PATH vals=`set | ${grep} -E '^CT_'` if [ "$oldvals" = "$vals" ]; then break fi oldvals="$vals" try=$[ try + 1 ] done if [ "$try" -gt 10 ]; then CT_Abort "Variables in .config recurse too deep." fi # Double eval: first eval substitutes option name, second eval unescapes quotes # and whitespace. for o in `set | ${sed} -rn 's/^(CT_[A-Za-z0-9_]*_ARRAY)=.*/\1/p'`; do eval "eval $o=(\"\$$o\")" done } # Prepare the fault handler CT_OnError() { local ret=$? local result local old_trap local intro local file line func local step step_depth # To avoid printing the backtace for each sub-shell # up to the top-level, just remember we've dumped it if [ ! -f "${CT_WORK_DIR}/backtrace" ]; then [ -d "${CT_WORK_DIR}" ] && touch "${CT_WORK_DIR}/backtrace" # Print steps backtrace step_depth=${CT_STEP_COUNT} CT_STEP_COUNT=1 # To have a zero-indentation CT_DoLog ERROR "" CT_DoLog ERROR ">>" intro="Build failed" for((step=step_depth; step>0; step--)); do CT_DoLog ERROR ">> ${intro} in step '${CT_STEP_MESSAGE[${step}]}'" intro=" called" done # Print functions backtrace intro="Error happened in" CT_DoLog ERROR ">>" for((depth=1; ${BASH_LINENO[$((${depth}-1))]}>0; depth++)); do file="${BASH_SOURCE[${depth}]#${CT_LIB_DIR}/}" func="${FUNCNAME[${depth}]}" line="@${BASH_LINENO[${depth}-1]:-?}" CT_DoLog ERROR ">> ${intro}: ${func}[${file}${line}]" intro=" called from" done # If the user asked for interactive debugging, dump him/her to a shell if [ "${CT_DEBUG_INTERACTIVE}" = "y" ]; then # We do not want this sub-shell exit status to be caught, because # it is absolutely legit that it exits with non-zero. # Save the trap handler to restore it after our debug-shell old_trap="$(trap -p ERR)" trap -- ERR ( CT_LogDisable # In this subshell printf "\r \n\nCurrent command" if [ -n "${cur_cmd}" ]; then printf ":\n %s\n" "${cur_cmd}" else printf " (unknown), " fi printf "exited with error code: %d\n" ${ret} printf "Please fix it up and finish by exiting the shell with one of these values:\n" printf " 1 fixed, continue with next build command\n" if [ -n "${cur_cmd}" ]; then printf " 2 repeat this build command\n" fi printf " 3 abort build\n\n" while true; do ${bash} --rcfile <(printf "PS1='ct-ng:\w> '\nPROMPT_COMMAND=''\n") -i result=$? case $result in 1) printf "\nContinuing past the failed command.\n\n" break ;; 2) if [ -n "${cur_cmd}" ]; then printf "\nRe-trying last command.\n\n" break fi ;; 3) break;; esac printf "\nPlease exit with one of these values:\n" printf " 1 fixed, continue with next build command\n" if [ -n "${cur_cmd}" ]; then printf " 2 repeat this build command\n" fi printf " 3 abort build\n" done exit $result ) result=$? # Restore the trap handler eval "${old_trap}" case "${result}" in 1) rm -f "${CT_WORK_DIR}/backtrace"; touch "${CT_BUILD_DIR}/skip"; return;; 2) rm -f "${CT_WORK_DIR}/backtrace"; touch "${CT_BUILD_DIR}/repeat"; return;; # 3 is an abort, continue... esac fi fi # And finally, in top-level shell, print some hints if [ ${BASH_SUBSHELL} -eq 0 ]; then # Help diagnose the error CT_STEP_COUNT=1 # To have a zero-indentation CT_DoLog ERROR ">>" if [ "${CT_LOG_TO_FILE}" = "y" ]; then CT_DoLog ERROR ">> For more info on this error, look at the file: '${CT_BUILD_LOG#${CT_TOP_DIR}/}'" fi CT_DoLog ERROR ">> There is a list of known issues, some with workarounds, in:" if [ -r "${CT_DOC_DIR}/manual/B_Known_issues.md" ]; then CT_DoLog ERROR ">> '${CT_DOC_DIR#${CT_TOP_DIR}/}/manual/B_Known_issues.md'" else CT_DoLog ERROR ">> https://crosstool-ng.github.io/docs/known-issues/" fi CT_DoLog ERROR ">>" if [ -n "${CT_EXPERIMENTAL}" ]; then CT_DoLog ERROR ">> NOTE: Your configuration includes features marked EXPERIMENTAL." CT_DoLog ERROR ">> Before submitting a bug report, try to reproduce it without enabling" CT_DoLog ERROR ">> any experimental features. Otherwise, you'll need to debug it" CT_DoLog ERROR ">> and present an explanation why it is a bug in crosstool-NG - or" CT_DoLog ERROR ">> preferably, a fix." CT_DoLog ERROR ">>" fi if [ "${CT_PATCH_ORDER}" != "bundled" ]; then CT_DoLog ERROR ">> NOTE: You configuration uses non-default patch sets. Please" CT_DoLog ERROR ">> select 'bundled' as the set of patches applied and attempt" CT_DoLog ERROR ">> to reproduce this issue. Issues reported with other patch" CT_DoLog ERROR ">> set selections (none, local, bundled+local) are going to be" CT_DoLog ERROR ">> closed without explanation." CT_DoLog ERROR ">>" fi CT_DoLog ERROR ">> If you feel this is a bug in crosstool-NG, report it at:" CT_DoLog ERROR ">> https://github.com/crosstool-ng/crosstool-ng/issues/" CT_DoLog ERROR ">>" CT_DoLog ERROR ">> Make sure your report includes all the information pertinent to this issue." CT_DoLog ERROR ">> Read the bug reporting guidelines here:" CT_DoLog ERROR ">> http://crosstool-ng.github.io/support/" CT_DoLog ERROR "" CT_DoEnd ERROR rm -f "${CT_WORK_DIR}/backtrace" fi exit $ret } # Install the fault handler trap CT_OnError ERR # Inherit the fault handler in subshells and functions set -E # Make pipes fail on the _first_ failed command # Not supported on bash < 3.x, but we need it, so drop the obsolete bash-2.x set -o pipefail # Don't hash commands' locations, and search every time it is requested. # This is slow, but needed because of the static/shared core gcc which shall # always match to shared if it exists, and only fallback to static if the # shared is not found set +o hashall # Log policy: # - first of all, save stdout so we can see the live logs: fd #6 # (also save stdin and stderr for use by CT_DEBUG_INTERACTIVE) # FIXME: it doesn't look like anyone is overriding stdin/stderr. Do we need # to save/restore them? CT_LogEnable() { local clean=no local arg for arg in "$@"; do eval "$arg"; done exec 6>&1 7>&2 8<&0 CT_BUILD_LOG="${CT_TOP_DIR}/build.log" CT_LOG_ENABLED=y if [ "$clean" = "yes" ]; then rm -f "${CT_BUILD_LOG}" fi exec >>"${CT_BUILD_LOG}" } # Restore original stdout, stderr and stdin CT_LogDisable() { exec >&6 2>&7 <&8 CT_LOG_ENABLED= } # The different log levels: CT_LOG_LEVEL_ERROR=0 CT_LOG_LEVEL_WARN=1 CT_LOG_LEVEL_INFO=2 CT_LOG_LEVEL_EXTRA=3 CT_LOG_LEVEL_CFG=4 CT_LOG_LEVEL_FILE=5 CT_LOG_LEVEL_STATE=6 CT_LOG_LEVEL_ALL=7 CT_LOG_LEVEL_DEBUG=8 # Make it easy to use \n and ! CR=$(printf "\n") BANG='!' # A function to log what is happening # Different log level are available: # - ERROR: A serious, fatal error occurred # - WARN: A non fatal, non serious error occurred, take your responsbility with the generated build # - INFO: Informational messages # - EXTRA: Extra informational messages # - CFG: Output of various "./configure"-type scripts # - FILE: File / archive unpacking. # - STATE: State save & restore # - ALL: Component's build messages # - DEBUG: Internal debug messages # Usage: CT_DoLog [message] # If message is empty, then stdin will be logged. CT_DoLog() { local max_level LEVEL level cur_l cur_L local l eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}" # Set the maximum log level to DEBUG if we have none [ -z "${max_level}" ] && max_level=${CT_LOG_LEVEL_DEBUG} LEVEL="$1"; shift eval level="\${CT_LOG_LEVEL_${LEVEL}}" if [ $# -eq 0 ]; then cat - else echo -e "${*}" fi |( IFS="${CR}" # We want the full lines, even leading spaces _prog_bar_cpt=0 _prog_bar[0]='/' _prog_bar[1]='-' _prog_bar[2]='\' _prog_bar[3]='|' indent=$((2*CT_STEP_COUNT)) while read line; do case "${CT_LOG_SEE_TOOLS_WARN:-n},${line}" in y,*[[:space:]][Ww]arning:*|y,[Ww]arning:*|y,*[[:space:]]WARNING:*|y,WARNING:*) cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};; *[[:space:]][Ee]rror:*|[yn],[Ee]rror:*) cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};; *"make["*"]: ***"*) cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};; *) cur_L="${LEVEL}"; cur_l="${level}";; esac # There will always be a log file (stdout, fd #1), be it /dev/null if [ -n "${CT_LOG_ENABLED}" ]; then printf "[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" # If log file has been set up, fd#6 is console and it only # gets the most important messages. if [ ${cur_l} -le ${max_level} ]; then # Only print to console (fd #6) if log level is high enough. printf "${CT_LOG_PROGRESS_BAR:+\r}[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" >&6 fi if [ "${CT_LOG_PROGRESS_BAR}" = "y" ]; then printf "\r[%02d:%02d] %s " $((SECONDS/60)) $((SECONDS%60)) "${_prog_bar[$((_prog_bar_cpt/10))]}" >&6 _prog_bar_cpt=$(((_prog_bar_cpt+1)%40)) fi elif [ ${cur_l} -le ${CT_LOG_LEVEL_WARN} ]; then printf "[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" >&2 fi done ) return 0 } # Execute an action, and log its messages # It is possible to even log local variable assignments (a-la: var=val ./cmd opts) # Usage: CT_DoExecLog [VAR=val...] [parameters...] CT_DoExecLog() { local level="$1" local cur_cmd local ret local cmd_seen shift ( for i in "$@"; do case "${i}" in *=*) if [ -z "${cmd_seen}" ]; then cur_cmd+=" ${i%%=*}='${i#*=}'" else cur_cmd+=" '${i}'" fi ;; *) cur_cmd+=" '${i}'" cmd_seen=y ;; esac done while true; do case "${1}" in *=*) eval export "'${1}'"; shift;; *) break;; esac done # This while-loop goes hand-in-hand with the ERR trap handler: # - if the command terminates successfully, then we hit the break # statement, and we exit the loop # - if the command terminates in error, then the ERR handler kicks # in, then: # - if the user did *not* ask for interactive debugging, the ERR # handler exits, and we hit the end of the sub-shell # - if the user did ask for interactive debugging, the ERR handler # spawns a shell. Upon termination of this shell, the ERR handler # examines the exit status of the shell: # - if 1, the ERR handler returns; then we hit the else statement, # then the break, and we exit the 'while' loop, to continue the # build; # - if 2, the ERR handler touches the repeat file, and returns; # then we hit the if statement, and we loop for one more # iteration; # - if 3, the ERR handler exits with the command's exit status, # and we're dead; # - for any other exit status of the shell, the ERR handler # prints an informational message, and respawns the shell # # This allows a user to get an interactive shell that has the same # environment (PATH and so on) that the failed command was ran with. while true; do rm -f "${CT_BUILD_DIR}/repeat" CT_DoLog DEBUG "==> Executing: ${cur_cmd}" "${@}" 2>&1 |CT_DoLog "${level}" ret="${?}" if [ -f "${CT_BUILD_DIR}/repeat" ]; then rm -f "${CT_BUILD_DIR}/repeat" continue elif [ -f "${CT_BUILD_DIR}/skip" ]; then rm -f "${CT_BUILD_DIR}/skip" ret=0 break else break fi done CT_DoLog DEBUG "==> Return status ${ret}" exit ${ret} ) # Catch failure of the sub-shell [ $? -eq 0 ] } # Tail message to be logged whatever happens # Usage: CT_DoEnd CT_DoEnd() { local level="$1" CT_STOP_DATE=$(CT_DoDate +%s%N) CT_STOP_DATE_HUMAN=$(CT_DoDate +%Y%m%d.%H%M%S) if [ "${level}" != "ERROR" ]; then CT_DoLog "${level:-INFO}" "Build completed at ${CT_STOP_DATE_HUMAN}" fi elapsed=$((CT_STOP_DATE-CT_STAR_DATE)) elapsed_min=$((elapsed/(60*1000*1000*1000))) elapsed_sec=$(printf "%02d" $(((elapsed%(60*1000*1000*1000))/(1000*1000*1000)))) elapsed_csec=$(printf "%02d" $(((elapsed%(1000*1000*1000))/(10*1000*1000)))) CT_DoLog ${level:-INFO} "(elapsed: ${elapsed_min}:${elapsed_sec}.${elapsed_csec})" } # Remove entries referring to . and other relative paths # Usage: CT_SanitizePath CT_SanitizePath() { local new local p local IFS=: for p in $PATH; do # Only accept absolute paths; # Note: as a special case the empty string in PATH is equivalent to . if [ -n "${p}" -a -z "${p%%/*}" ]; then new="${new}${new:+:}${p}" fi done PATH="${new}" } # Sanitize the directory name contained in the variable passed as argument: # - remove duplicate / # - remove . (current dir) at the beginning, in the middle or at the end # - resolve .. (parent dir) if there is a previous component # - remove .. (parent dir) if at the root # # Usage: CT_SanitizeVarDir CT_PREFIX_DIR CT_SanitizeVarDir() { local var local old_dir local new_dir tmp for var in "$@"; do eval "old_dir=\"\${${var}}\"" new_dir=$( echo "${old_dir}" | ${awk} ' { isabs = $1 == "" # Started with a slash trail = $NF == "" # Ending with a slash ncomp = 0 # Components in a path so far for (i = 1; i <= NF; i++) { # Double-slash or current dir? Ignore if ($i == "" || $i == ".") { continue; } # .. pops the last component unless it is at the beginning if ($i == ".." && ncomp != 0 && comps[ncomp] != "..") { ncomp--; continue; } comps[++ncomp] = $i; } seencomp = 0 for (i = 1; i <= ncomp; i++) { if (comps[i] == ".." && isabs) { # /../ at the beginning is equivalent to / continue; } printf "%s%s", isabs || i != 1 ? "/" : "", comps[i]; seencomp = 1; } if (!seencomp && !isabs && !trail) { # Eliminated all components, but no trailing slash - # if the result is appended with /foo, must not become absolute printf "."; } if ((!seencomp && isabs) || (seencomp && trail)) { printf "/"; } }' FS=/ ) eval "${var}=\"${new_dir}\"" CT_DoLog DEBUG "Sanitized '${var}': '${old_dir}' -> '${new_dir}'" done } # Abort the execution with an error message # Usage: CT_Abort CT_Abort() { CT_DoLog ERROR "$1" false } # Test a condition, and print a message if satisfied # Usage: CT_Test CT_Test() { local ret local m="$1" shift CT_DoLog DEBUG "Testing '! ( $* )'" test "$@" && CT_DoLog WARN "$m" return 0 } # Test a condition, and abort with an error message if satisfied # Usage: CT_TestAndAbort CT_TestAndAbort() { local m="$1" shift CT_DoLog DEBUG "Testing '! ( $* )'" test "$@" && CT_Abort "$m" return 0 } # Test a condition, and abort with an error message if not satisfied # Usage: CT_TestAndAbort CT_TestOrAbort() { local m="$1" shift CT_DoLog DEBUG "Testing '$*'" test "$@" || CT_Abort "$m" return 0 } # Test the presence of a tool, or abort if not found # Usage: CT_HasOrAbort CT_HasOrAbort() { CT_TestAndAbort "'${1}' not found and needed for successful toolchain build." -z "$(CT_Which "${1}")" return 0 } # Search a program: wrap "which" for those system where "which" # verbosely says there is no match (such as on Mandriva). # Usage: CT_Which CT_Which() { which "$1" 2>/dev/null || true } # Get current date with nanosecond precision # On those system not supporting nanosecond precision, faked with rounding down # to the highest entire second # Usage: CT_DoDate CT_DoDate() { date "$1" |${sed} -r -e 's/%?N$/000000000/;' } CT_STEP_COUNT=1 CT_STEP_MESSAGE[${CT_STEP_COUNT}]="(top-level)" # Memorise a step being done so that any error is caught # Usage: CT_DoStep CT_DoStep() { local start=$(CT_DoDate +%s%N) CT_DoLog "$1" "=================================================================" CT_DoLog "$1" "$2" CT_STEP_COUNT=$((CT_STEP_COUNT+1)) CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift CT_STEP_START[${CT_STEP_COUNT}]="${start}" CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1" return 0 } # End the step just being done # Usage: CT_EndStep CT_EndStep() { local stop=$(CT_DoDate +%s%N) local duration=$(printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) \ |${sed} -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;' ) local elapsed=$(printf "%02d:%02d" $((SECONDS/60)) $((SECONDS%60))) local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}" local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}" CT_STEP_COUNT=$((CT_STEP_COUNT-1)) CT_DoLog "${level}" "${message}: done in ${duration}s (at ${elapsed})" return 0 } # Pushes into a directory, and pops back CT_Pushd() { CT_DoLog DEBUG "Entering '$1'" pushd "$1" >/dev/null 2>&1 } CT_Popd() { local dir=`dirs +0` CT_DoLog DEBUG "Leaving '${dir}'" popd >/dev/null 2>&1 } # Create a dir and pushd into it # Usage: CT_mkdir_pushd CT_mkdir_pushd() { local dir="${1}" mkdir -p "${dir}" CT_Pushd "${dir}" } # Creates a temporary directory # $1: variable to assign to # Usage: CT_MktempDir foo CT_MktempDir() { # Some mktemp do not allow more than 6 Xs eval "$1"=$(mktemp -q -d "${CT_BUILD_DIR}/tmp.XXXXXX") CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}" CT_DoLog DEBUG "Made temporary directory '${!1}'" return 0 } # Removes one or more directories, even if it is read-only, or its parent is # Usage: CT_DoForceRmdir dir [...] CT_DoForceRmdir() { local dir local cnt for dir in "${@}"; do [ -e "${dir}" ] || continue CT_TestOrAbort "Cannot remove '${dir}': not a directory" -d "${dir}" CT_DoExecLog ALL chmod -R u+w "${dir}" || :; if CT_DoExecLog ALL rm -rf "${dir}"; then continue fi # If we succeeded in removing the whole directory, good. If not, # but only the top level directory remains - it is fine, too, because # this function is used to remove the directories that are going to be # re-created. Hence, verify we at least succeeded in verifying the # contents of this directory. if [ -d "${dir}" ]; then cnt=$(ls -a "${dir}" | { grep -v '^\.\{1,2\}$' || :; } | wc -l) if [ "${cnt}" != "0" ]; then CT_Abort "Failed to remove '${dir}'" fi fi done } # Add the specified directory to LD_LIBRARY_PATH, and export it # If the specified patch is already present, just export # $1: path to add # $2: add as 'first' or 'last' path, 'first' is assumed if $2 is empty # Usage CT_SetLibPath /some/where/lib [first|last] CT_SetLibPath() { local path="$1" local pos="$2" case ":${LD_LIBRARY_PATH}:" in *:"${path}":*) ;; *) case "${pos}" in last) CT_DoLog DEBUG "Adding '${path}' at end of LD_LIBRARY_PATH" LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}${path}" ;; first|"") CT_DoLog DEBUG "Adding '${path}' at start of LD_LIBRARY_PATH" LD_LIBRARY_PATH="${path}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}" ;; *) CT_Abort "Incorrect position '${pos}' to add '${path}' to LD_LIBRARY_PATH" ;; esac ;; esac CT_DoLog DEBUG "==> LD_LIBRARY_PATH='${LD_LIBRARY_PATH}'" export LD_LIBRARY_PATH } # Build up the list of allowed tarball extensions # Add them in the prefered order; most preferred comes first CT_DoListTarballExt() { printf ".tar.xz\n" printf ".tar.lzma\n" if [ "${CT_CONFIGURE_has_lzip}" = "y" ]; then printf ".tar.lz\n" fi printf ".tar.bz2\n" printf ".tar.gz\n.tgz\n" printf ".tar\n" printf ".zip\n" } # Get the file name extension of a component # Usage: CT_GetFileExtension [extension] # If found, echoes the extension to stdout, and return 0 # If not found, echoes nothing on stdout, and return !0. CT_GetFileExtension() { local ext local file="$1" for ext in $(CT_DoListTarballExt); do if [ -e "${file}${ext}" -o -L "${file}${ext}" ]; then echo "${ext}" exit 0 fi done exit 1 } # Get file's basename by stripping supported archive extensions CT_GetFileBasename() { local bn="${1}" local ext for ext in $(CT_DoListTarballExt); do if [ "${bn%${ext}}" != "${bn}" ]; then echo "${bn%${ext}}" exit 0 fi done } # Try to retrieve the specified URL (HTTP or FTP) # Usage: CT_DoGetFile # This functions always returns true (0), as it can be legitimate not # to find the requested URL (think about snapshots, different layouts # for different gcc versions, etc...). CT_DoGetFile() { local url="${1}" local dest="${CT_TARBALLS_DIR}/${url##*/}" local tmp="${dest}.tmp-dl" local ok local T # Remove potential left-over from a previous run rm -f "${tmp}" # Replace a special value of '-1' with empty string if [ ${CT_CONNECT_TIMEOUT} != -1 ]; then T="${CT_CONNECT_TIMEOUT}" fi CT_DoLog DEBUG "Trying '${url}'" if [ "${CT_DOWNLOAD_AGENT_WGET}" = "y" ]; then if CT_DoExecLog ALL wget ${CT_DOWNLOAD_WGET_OPTIONS} \ ${T:+-T ${T}} \ -O "${tmp}" \ "${url}"; then ok=y fi elif [ "${CT_DOWNLOAD_AGENT_CURL}" = "y" ]; then if CT_DoExecLog ALL curl ${CT_DOWNLOAD_CURL_OPTIONS} \ ${T:+--connect-timeout ${T}} \ -o "${tmp}" \ "${url}"; then ok=y fi fi if [ "${ok}" = "y" ]; then # Success, we got it, good! mv "${tmp}" "${dest}" CT_DoLog DEBUG "Got it from: \"${url}\"" return 0 else # Whoops... rm -f "${tmp}" CT_DoLog DEBUG "Not at this location: \"${url}\"" return 1 fi } # This function saves the specified to local storage if possible, # and if so, symlinks it for later usage. This function is called from # the `if' condition (via the CT_GetFile) and therefore must return # on error rather than relying on the shell's ERR trap to catch it. # Usage: CT_SaveLocal CT_SaveLocal() { local file="$1" local savedir="${CT_LOCAL_TARBALLS_DIR}${CT_TARBALLS_BUILDROOT_LAYOUT:+/$2}" local basename="${file##*/}" if [ "${CT_SAVE_TARBALLS}" = "y" ]; then CT_DoLog EXTRA "Saving '${basename}' to local storage" # The subdirectory for this package may not exist yet; create it if [ ! -d "${savedir}" ]; then CT_DoExecLog ALL mkdir -p "${savedir}" fi # The file may already exist if downloads are forced: remove it first if ! CT_DoExecLog ALL rm -f "${savedir}/${basename}"; then return 1 fi if ! CT_DoExecLog ALL mv -f "${file}" "${savedir}"; then # Move may have failed if the local tarball storage is on a different # filesystem. Fallback to copy+delete. if ! CT_DoExecLog ALL cp -f "${file}" "${savedir}"; then return 1 fi if ! CT_DoExecLog ALL rm -f "${file}"; then return 1 fi fi if ! CT_DoExecLog ALL ln -s "${savedir}/${basename}" "${file}"; then return 1 fi fi } # Verify the file against a known digest. # Usage: CT_DoVerifyDigest CT_DoVerifyDigest() { local path="$1" local file="${path##*/}" local dir="${path%/*}" local pkgdir="$2" local alg="${CT_VERIFY_DOWNLOAD_DIGEST_ALG}" local chksum a f c if [ ! -r "${pkgdir}/chksum" ]; then CT_DoLog WARN "Not verifying '${file}': digest missing" return 0 fi CT_DoLog EXTRA "Verifying ${alg^^} checksum for '${file}'" chksum=`"${alg}sum" "${path}"` chksum="${chksum%%[[:space:]]*}" while read a f c; do if [ "${a}" != "${alg}" -o "${f}" != "${file}" ]; then continue fi if [ "${c}" = "${chksum}" ]; then CT_DoLog DEBUG "Correct ${alg} digest for ${file}: ${chksum}" return 0 else CT_DoLog ERROR "Bad ${alg} digest for ${file}: ${chksum}, expect ${c}" return 1 fi done < "${pkgdir}/chksum" CT_DoLog WARN "Downloaded file ${file} reference digest not available" return 0 } # Decompress a file to stdout CT_ZCat() { local file="$1" case "${file}" in *.tar.xz) xz -fdc "${file}" ;; *.tar.lzma) xz -fdc --format=lzma "${file}" ;; *.tar.lz) lzip -fdc "${file}" ;; *.tar.bz2) bzip2 -dc "${file}" ;; *.tar.gz|*.tgz) gzip -dc "${file}" ;; *.tar) cat "${file}" ;; *) CT_Abort "Unsupported archive file name '${file}'" esac } # Verify the file against a detached signature. # Fetched from the URL, or obtained from the package directory. # Usage: CT_DoVerifySignature CT_DoVerifySignature() { local path="$1" local file="${path##*/}" local dir="${path%/*}" local url="$2" local urldir="${url%/*}" local format="$3" local method="${format%/*}" local ext="${format#*/}" local save_subdir="$4" local sigfile local cat CT_DoLog EXTRA "Verifying detached signature for '${file}'" case "${method}" in packed) # Typical case: release is packed, then signed sigfile="${file}" cat=cat ;; unpacked) # Linux kernel: uncompressed tarball is signed, them compressed by various methods case "${file}" in *.tar.*) sigfile="${file%.tar.*}.tar" cat=CT_ZCat ;; *) CT_Abort "'unpacked' signature method only supported for tar archives" ;; esac ;; *) CT_Abort "Unsupported signature method ${method}" ;; esac # No recursion, as we don't pass signature_format argument if ! CT_DoGetFile "${urldir}/${sigfile}${ext}"; then CT_DoLog WARN "Failed to download the signature '${sigfile}${ext}'" return 1 fi CT_Pushd "${dir}" if ! ${cat} "${file}" | CT_DoExecLog ALL gpg --verify "${sigfile}${ext}" -; then # Remove the signature so it's re-downloaded next time CT_DoExecLog ALL rm "${sigfile}${ext}" CT_Popd return 1 fi CT_Popd # If we get here, verification succeeded. if ! CT_SaveLocal "${CT_TARBALLS_DIR}/${sigfile}${ext}" "${save_subdir}"; then CT_Popd return 1 fi return 0 } # Download the file from one of the URLs passed as argument CT_GetFile() { local -a argnames=( package # Name of the package pkg_dir # Directory with package's auxiliary files dir_name # Package's directory name in downloads dir basename # Base name of file/archive extensions # Extension(s) for the file/archive digest # If 'y', verify the digest signature_format # Format of the signature mirrors # Mirrors to download from ) local dl_dir local -a URLS local ext url for arg in "${argnames[@]/%/=}" "$@"; do eval "local ${arg//[[:space:]]/\\ }" done CT_TestOrAbort "Internal error: dir_name not set" -n "${dir_name}" dl_dir="${CT_LOCAL_TARBALLS_DIR:+${CT_LOCAL_TARBALLS_DIR}${CT_TARBALLS_BUILDROOT_LAYOUT:+/${dir_name}}}" # Does any of the requested files exist localy? for ext in ${extensions}; do # Do we already have it in *our* tarballs dir? if [ -r "${CT_TARBALLS_DIR}/${basename}${ext}" ]; then CT_DoLog DEBUG "Already have '${CT_TARBALLS_DIR}/${basename}${ext}'" return 0 fi if [ "${CT_FORCE_DOWNLOAD}" != "y" ]; then if [ -n "${dl_dir}" -a -r "${dl_dir}/${basename}${ext}" ]; then CT_DoLog DEBUG "Got '${basename}' from local storage" CT_DoExecLog ALL ln -s "${dl_dir}/${basename}${ext}" \ "${CT_TARBALLS_DIR}/${basename}${ext}" return 0 elif [ -n "${CT_LOCAL_TARBALLS_DIR}" -a -r "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" ]; then # Only different if we're using new buildroot layout CT_DoLog DEBUG "Got '${basename}' from local storage" CT_DoLog INFO "Moving the ${basename}${ext} into ${dir_name}/${basename}${ext}" if [ ! -d "${dl_dir}" ]; then CT_DoExecLog ALL mkdir -p "${dl_dir}" fi CT_DoExecLog ALL mv "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" "${dl_dir}/${basename}${ext}" CT_DoExecLog ALL ln -s "${dl_dir}/${basename}${ext}" \ "${CT_TARBALLS_DIR}/${basename}${ext}" return 0 fi fi done # No, it does not... If not allowed to download from the Internet, don't. if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then CT_DoLog DEBUG "Not allowed to download from the Internet, aborting ${basename} download" return 1 fi # Try to retrieve the file CT_DoLog EXTRA "Retrieving '${basename}'" # Add URLs on the LAN mirror if [ "${CT_USE_MIRROR}" = "y" ]; then CT_TestOrAbort "Please set the mirror base URL" -n "${CT_MIRROR_BASE_URL}" if [ -n "${package}" ]; then URLS+=( "${CT_MIRROR_BASE_URL}/${package}" ) fi URLS+=( "${CT_MIRROR_BASE_URL}" ) fi if [ "${CT_FORCE_MIRROR}" != "y" ]; then URLS+=( ${mirrors} ) fi # Scan all URLs in turn, and try to grab a tarball from there for ext in ${extensions}; do # Try all urls in turn for url in "${URLS[@]}"; do [ -n "${url}" ] || continue if [ "${url}" = "-unknown-" ]; then CT_Abort "Don't know how to download ${basename}" fi if CT_DoGetFile "${url}/${basename}${ext}"; then if [ -n "${digest}" -a -n "${pkg_dir}" ] && ! CT_DoVerifyDigest \ "${CT_TARBALLS_DIR}/${basename}${ext}" \ "${CT_LIB_DIR}/packages/${pkg_dir}"; then CT_DoLog ERROR "Digest verification failed; removing the download" CT_DoExecLog ALL rm "${CT_TARBALLS_DIR}/${basename}${ext}" return 1 fi if [ -n "${signature_format}" ] && ! CT_DoVerifySignature \ "${CT_TARBALLS_DIR}/${basename}${ext}" \ "${url}/${basename}${ext}" \ "${signature_format}"; then CT_DoLog ERROR "Signature verification failed; removing the download" CT_DoExecLog ALL rm "${CT_TARBALLS_DIR}/${basename}${ext}" return 1 fi if ! CT_SaveLocal "${CT_TARBALLS_DIR}/${basename}${ext}" "${dir_name}"; then return 1 fi return 0 fi done done # Just return error: CT_DoFetch will check it and will handle it appropriately. return 1 } # TBD these should not be needed if config.sub/guess is a package # Two wrappers to call config.(guess|sub) either from CT_TOP_DIR or CT_LIB_DIR. # Those from CT_TOP_DIR, if they exist, will be be more recent than those from CT_LIB_DIR. CT_DoConfigGuess() { if [ -r "${CT_TOP_DIR}/scripts/config.guess" ]; then "${CT_CONFIG_SHELL}" "${CT_TOP_DIR}/scripts/config.guess" else "${CT_CONFIG_SHELL}" "${CT_LIB_DIR}/scripts/config.guess" fi } CT_DoConfigSub() { if [ -r "${CT_TOP_DIR}/scripts/config.sub" ]; then "${CT_CONFIG_SHELL}" "${CT_TOP_DIR}/scripts/config.sub" "$@" else "${CT_CONFIG_SHELL}" "${CT_LIB_DIR}/scripts/config.sub" "$@" fi } # Normally, each step is executed in a sub-shell and thus cannot modify the # environment for the next step(s). When this is needed, it can do so by # invoking this function. # Usage: CT_EnvModify [export] VAR VALUE CT_EnvModify() { local e if [ "$1" = "export" ]; then shift e="export " fi eval "${e}${1}=\"${2}\"" echo "${e}${1}=\"${2}\"" >> "${CT_BUILD_DIR}/env.modify.sh" } # Compute the target tuple from what is provided by the user # Usage: CT_DoBuildTargetTuple # In fact this function takes the environment variables to build the target # tuple. It is needed both by the normal build sequence, as well as the # sample saving sequence. CT_DoBuildTargetTuple() { local tmp # Set the endianness suffix, and the default endianness gcc option target_endian_eb= target_endian_be= target_endian_el= target_endian_le= case "${CT_ARCH_ENDIAN}" in big) target_endian_eb=eb target_endian_be=be CT_ARCH_ENDIAN_CFLAG="-mbig-endian" CT_ARCH_ENDIAN_LDFLAG="-Wl,-EB" ;; little) target_endian_el=el target_endian_le=le CT_ARCH_ENDIAN_CFLAG="-mlittle-endian" CT_ARCH_ENDIAN_LDFLAG="-Wl,-EL" ;; # big,little and little,big do not need to pass the flags; # gcc is expected to be configured for that as default. big,little) target_endian_eb=eb target_endian_be=be ;; little,big) target_endian_el=el target_endian_le=le ;; esac # Set the bitness suffix case "${CT_ARCH_BITNESS}" in 32) target_bits_32=32 target_bits_64= ;; 64) target_bits_32= target_bits_64=64 ;; esac # Build the default architecture tuple part CT_TARGET_ARCH="${CT_ARCH}${CT_ARCH_SUFFIX}" # Set defaults for the system part of the tuple; only C libraries that # support multiple architectures. Can be overriden by architecture-specific # values. case "${CT_LIBC}" in glibc) CT_TARGET_SYS=gnu;; uClibc-ng) CT_TARGET_SYS=uclibc;; musl) CT_TARGET_SYS=musl;; bionic) CT_TARGET_SYS=android;; none|newlib|picolibc) CT_TARGET_SYS=elf;; *) # Keep empty for the libraries like mingw or avr-libc CT_TARGET_SYS= ;; esac # Set the default values for ARCH, ABI, CPU, TUNE, FPU and FLOAT for tmp in ARCH ABI CPU TUNE FPU FLOAT ENDIAN; do eval "unset CT_ARCH_${tmp}_CFLAG CT_ARCH_WITH_${tmp} CT_ARCH_WITH_${tmp}_32 CT_ARCH_WITH_${tmp}_64" done [ -n "${CT_ARCH_ABI}" ] && { CT_ARCH_ABI_CFLAG="-mabi=${CT_ARCH_ABI}"; CT_ARCH_WITH_ABI="--with-abi=${CT_ARCH_ABI}"; } [ -n "${CT_ARCH_FPU}" ] && { CT_ARCH_FPU_CFLAG="-mfpu=${CT_ARCH_FPU}"; CT_ARCH_WITH_FPU="--with-fpu=${CT_ARCH_FPU}"; } # The options below have distinct variants for multilib-enabled toolchain. # At this time, we just always have them equal to the "main" setting; it # seems that most example configurations are built for a specific CPU. # If there's demand for it, we can turn them into separate knobs in # Kconfig later. for tmp in ARCH CPU TUNE; do eval "val=\${CT_ARCH_${tmp}}" if [ -n "${val}" ]; then eval "CT_ARCH_${tmp}_CFLAG=-m${tmp,,}=${val}" eval "CT_ARCH_WITH_${tmp}=--with-${tmp,,}=${val}" if [ -n "${CT_ARCH_SUPPORTS_WITH_32_64}" -a -n "${CT_MULTILIB}" ]; then eval "CT_ARCH_WITH_${tmp}_32=--with-${tmp,,}-32=${val}" eval "CT_ARCH_WITH_${tmp}_64=--with-${tmp,,}-64=${val}" fi fi done case "${CT_ARCH_FLOAT}" in hard) CT_ARCH_FLOAT_CFLAG="-mhard-float" CT_ARCH_WITH_FLOAT="--with-float=hard" ;; soft) CT_ARCH_FLOAT_CFLAG="-msoft-float" CT_ARCH_WITH_FLOAT="--with-float=soft" ;; softfp) CT_ARCH_FLOAT_CFLAG="-mfloat-abi=softfp" CT_ARCH_WITH_FLOAT="--with-float=softfp" ;; esac if [ "${CT_ARCH_SUPPORTS_WITH_ENDIAN}" = "y" ]; then CT_ARCH_WITH_ENDIAN="--with-endian=${CT_ARCH_ENDIAN}" fi # Build the default kernel tuple part CT_TARGET_KERNEL="${CT_KERNEL}" # Overide the default values with the components specific settings CT_DoArchTupleValues CT_DoKernelTupleValues # Finish the target tuple construction if [ -z "${CT_OMIT_TARGET_ARCH}" ]; then CT_TARGET="${CT_TARGET_ARCH}" fi if [ -z "${CT_OMIT_TARGET_VENDOR}" -a -n "${CT_TARGET_VENDOR}" ]; then CT_TARGET="${CT_TARGET:+${CT_TARGET}-}${CT_TARGET_VENDOR}" fi if [ -n "${CT_TARGET_KERNEL}" ]; then CT_TARGET="${CT_TARGET:+${CT_TARGET}-}${CT_TARGET_KERNEL}" fi if [ -n "${CT_TARGET_SYS}" ]; then CT_TARGET="${CT_TARGET:+${CT_TARGET}-}${CT_TARGET_SYS}" fi # Sanity checks __sed_alias="" if [ -n "${CT_TARGET_ALIAS_SED_EXPR}" ]; then __sed_alias=$(echo "${CT_TARGET}" |${sed} -r -e "${CT_TARGET_ALIAS_SED_EXPR}") fi case ":${CT_TARGET_VENDOR}:${CT_TARGET_ALIAS}:${__sed_alias}:" in :*" "*:*:*:) CT_Abort "Don't use spaces in the vendor string, it breaks things.";; :*"-"*:*:*:) CT_Abort "Don't use dashes in the vendor string, it breaks things.";; :*:*" "*:*:) CT_Abort "Don't use spaces in the target alias, it breaks things.";; :*:*:*" "*:) CT_Abort "Don't use spaces in the target sed transform, it breaks things.";; esac # Canonicalise it if [ "${CT_TARGET_SKIP_CONFIG_SUB}" != "y" ]; then CT_TARGET=$(CT_DoConfigSub "${CT_TARGET}") if [ -n "${CT_OMIT_TARGET_VENDOR}" ]; then # config.sub always returns a 3- or 4-part tuple, with vendor # always being the 2nd part. CT_TARGET="${CT_TARGET%%-*}-${CT_TARGET#*-*-}" fi fi # Prepare the target CFLAGS CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ENDIAN_CFLAG}" CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ARCH_CFLAG}" CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ABI_CFLAG}" CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_CPU_CFLAG}" CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_TUNE_CFLAG}" CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FPU_CFLAG}" CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FLOAT_CFLAG}" # Now on for the target LDFLAGS CT_ARCH_TARGET_LDFLAGS="${CT_ARCH_TARGET_LDFLAGS} ${CT_ARCH_ENDIAN_LDFLAG}" # Now, a multilib quirk. We may not be able to pass CT_ARCH_TARGET_CFLAGS # and CT_ARCH_TARGET_LDFLAGS to gcc: even though GCC build appends the multilib # flags afterwards, on some architectures the build breaks because some # flags do not completely override each other. For example, on mips target, # 'gcc -mabi=32' and 'gcc -mabi=n32' both work, but 'gcc -mabi=32 -mabi=n32' # triggers an internal linker error. Likely a bug in GNU binutils, but we # have to work it around for now: *do not pass the CT_ARCH_TARGET_ flags*. # Instead, save them into a different variable here. Then, after the first # core pass, we'll know which of them vary with multilibs (i.e. must be # filtered out). if [ -n "${CT_MULTILIB}" ]; then CT_ARCH_TARGET_CFLAGS_MULTILIB="${CT_ARCH_TARGET_CFLAGS}" CT_ARCH_TARGET_CFLAGS= CT_ARCH_TARGET_LDFLAGS_MULTILIB="${CT_ARCH_TARGET_LDFLAGS}" CT_ARCH_TARGET_LDFLAGS= else CT_ALL_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_TARGET_CFLAGS}" CT_ALL_TARGET_LDFLAGS="${CT_ARCH_TARGET_LDFLAGS} ${CT_TARGET_LDFLAGS}" fi } # This function does pause the build until the user strikes "Return" # Usage: CT_DoPause [optional_message] CT_DoPause() { local foo local message="${1:-Pausing for your pleasure}" CT_DoLog INFO "${message}" read -p "Press 'Enter' to continue, or Ctrl-C to stop..." foo >&6 return 0 } # This function sets up trapping export/unset operations so that saving/restoring # the state can restore status of environment exactly. CT_TrapEnvExport() { unset() { eval "builtin unset $*" CT_ENVVAR_UNSET="${CT_ENVVAR_UNSET} $*" } export() { local v for v in "$@"; do eval "builtin export \"${v}\"" case "${CT_ENVVAR_EXPORTED} " in *" ${v%%=*} "*) continue;; esac CT_ENVVAR_EXPORTED="${CT_ENVVAR_EXPORTED} ${v%%=*}" done } } # This function creates a tarball of the specified directory, but # only if it exists # Usage: CT_DoTarballIfExists [extra_tar_options [...]] CT_DoTarballIfExists() { local dir="$1" local tarball="$2" shift 2 local -a extra_tar_opts=( "$@" ) local -a compress case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in y) compress=( gzip -c -3 - ); tar_ext=.gz;; *) compress=( cat - ); tar_ext=;; esac if [ -d "${dir}" ]; then CT_DoLog DEBUG " Saving '${dir}'" { tar c -C "${dir}" -v -f - "${extra_tar_opts[@]}" . \ |"${compress[@]}" >"${tarball}.tar${tar_ext}" ; } 2>&1 |${sed} -r -e 's/^/ /;' |CT_DoLog STATE else CT_DoLog STATE " Not saving '${dir}': does not exist" fi } # This function extracts a tarball to the specified directory, but # only if the tarball exists # Usage: CT_DoExtractTarballIfExists [extra_tar_options [...]] CT_DoExtractTarballIfExists() { local tarball="$1" local dir="$2" shift 2 local -a extra_tar_opts=( "$@" ) local -a uncompress case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in y) uncompress=( gzip -c -d ); tar_ext=.gz;; *) uncompress=( cat ); tar_ext=;; esac if [ -f "${tarball}.tar${tar_ext}" ]; then CT_DoLog DEBUG " Restoring '${dir}'" CT_DoForceRmdir "${dir}" CT_DoExecLog DEBUG mkdir -p "${dir}" { "${uncompress[@]}" "${tarball}.tar${tar_ext}" \ |tar x -C "${dir}" -v -f - "${extra_tar_opts[@]}" ; } 2>&1 |${sed} -r -e 's/^/ /;' |CT_DoLog STATE else CT_DoLog STATE " Not restoring '${dir}': does not exist" fi } # This function saves the state of the toolchain to be able to restart # at any one point # Usage: CT_DoSaveState CT_DoSaveState() { [ "${CT_DEBUG_CT_SAVE_STEPS}" = "y" ] || return 0 local state_name="$1" local state_dir="${CT_STATE_DIR}/${state_name}" local v CT_DoLog INFO "Saving state to restart at step '${state_name}'..." rm -rf "${state_dir}" mkdir -p "${state_dir}" # Save only environment variables, not functions. # Limit saving to our variables (CT_*) and exported variables. # Also unset variables that have been removed from the environment. # This generated script will be sourced from a function, so make # all the definitions global by adding -g. Hope we don't have # a multi-line variable that has a line starting with "declare" # (or we'll need to run sed on each variable separately, only on # the first line of it). CT_DoLog STATE " Saving environment and aliases" { for v in "${!CT_@}" ${CT_ENVVAR_EXPORTED}; do # Check if it is still set [ -n "${!v+set}" ] && declare -p "${v}" done | ${sed} 's/^declare /declare -g /' echo "builtin unset ${CT_ENVVAR_UNSET}" } >"${state_dir}/env.sh" # Save .config to check it hasn't changed when resuming. CT_DoExecLog STATE cp ".config" "${state_dir}/config" CT_DoTarballIfExists "${CT_BUILDTOOLS_PREFIX_DIR}" "${state_dir}/buildtools_dir" CT_DoTarballIfExists "${CT_SRC_DIR}" "${state_dir}/src_dir" CT_DoTarballIfExists "${CT_PREFIX_DIR}" "${state_dir}/prefix_dir" --exclude '*.log' CT_DoLog STATE " Saving log file" CT_LogDisable case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in y) gzip -3 -c "${CT_BUILD_LOG}" >"${state_dir}/log.gz";; *) cat "${CT_BUILD_LOG}" >"${state_dir}/log";; esac CT_LogEnable } # This function restores a previously saved state # Usage: CT_DoLoadState CT_DoLoadState(){ local state_name="$1" local state_dir="${CT_STATE_DIR}/${state_name}" local old_RESTART="${CT_RESTART}" local old_STOP="${CT_STOP}" CT_TestOrAbort "The previous build did not reach the point where it could be restarted at '${CT_RESTART}'" -d "${state_dir}" if ! cmp ".config" "${state_dir}/config" >/dev/null 2>&1; then CT_Abort "The configuration file has changed between two runs" fi CT_DoLog INFO "Restoring state at step '${state_name}', as requested." CT_DoExtractTarballIfExists "${state_dir}/prefix_dir" "${CT_PREFIX_DIR}" CT_DoExtractTarballIfExists "${state_dir}/src_dir" "${CT_SRC_DIR}" CT_DoExtractTarballIfExists "${state_dir}/buildtools_dir" "${CT_BUILDTOOLS_PREFIX_DIR}" # Restore the environment, discarding any error message # (for example, read-only bash internals) CT_DoLog STATE " Restoring environment" . "${state_dir}/env.sh" >/dev/null 2>&1 || true # Restore the new RESTART and STOP steps CT_RESTART="${old_RESTART}" CT_STOP="${old_STOP}" CT_DoLog STATE " Restoring log file" CT_LogDisable mv "${CT_BUILD_LOG}" "${CT_BUILD_LOG}.tail" case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in y) gzip -dc "${state_dir}/log.gz" >"${CT_BUILD_LOG}";; *) cat "${state_dir}/log" >"${CT_BUILD_LOG}";; esac cat "${CT_BUILD_LOG}.tail" >>"${CT_BUILD_LOG}" CT_LogEnable rm -f "${CT_BUILD_LOG}.tail" } # This function sets a kconfig option to a specific value in a .config file # Usage: CT_KconfigSetOption