scripts/functions
author Johannes Stezenbach <js@sig21.net>
Thu Jul 29 19:30:37 2010 +0200 (2010-07-29)
branch1.7
changeset 2047 ace1d90c9b15
parent 1909 5921089b34bd
permissions -rw-r--r--
scripts: remove . from $PATH

Add CT_SanitizePath function which removes entries referring to ., /tmp
and non-existing directories from $PATH, and call it early in the
build script.

If . is in PATH, gcc-4.4.4 build breaks:

[ALL ] checking what assembler to use...
/tmp/build/targets/arm-unknown-linux-uclibcgnueabi/build/gcc-core-static/arm-unknown-linux-uclibcgnueabi/bin/as
...
[ALL ] config.status: creating as

i.e. "as" is supposed to be the arm-unknown-linux-uclibcgnueabi cross assembler,
but config.status creates a local "as" script which is calling the
host assembler.

Signed-off-by: Johannes Stezenbach <js@sig21.net>
[Yann E. MORIN: style fixes + explanations]
Signed-off-by: "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
(transplanted from 20dd8cef1c8adff0aa3e78ae6d7acfbc45ed5a83)
yann@1
     1
# This file contains some usefull common functions
yann@1
     2
# Copyright 2007 Yann E. MORIN
yann@1
     3
# Licensed under the GPL v2. See COPYING in the root of this package
yann@1
     4
yann@136
     5
# Prepare the fault handler
yann@1
     6
CT_OnError() {
yann@1
     7
    ret=$?
yann@726
     8
    # Bail out early in subshell, the upper level shell will act accordingly.
yann@726
     9
    [ ${BASH_SUBSHELL} -eq 0 ] || exit $ret
yann@523
    10
    CT_DoLog ERROR "Build failed in step '${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}'"
yann@1
    11
    for((step=(CT_STEP_COUNT-1); step>1; step--)); do
yann@523
    12
        CT_DoLog ERROR "      called in step '${CT_STEP_MESSAGE[${step}]}'"
yann@1
    13
    done
yann@523
    14
    CT_DoLog ERROR "Error happened in '${BASH_SOURCE[1]}' in function '${FUNCNAME[1]}' (line unknown, sorry)"
yann@1
    15
    for((depth=2; ${BASH_LINENO[$((${depth}-1))]}>0; depth++)); do
yann@523
    16
        CT_DoLog ERROR "      called from '${BASH_SOURCE[${depth}]}' at line # ${BASH_LINENO[${depth}-1]} in function '${FUNCNAME[${depth}]}'"
yann@1
    17
    done
yann@523
    18
    [ "${CT_LOG_TO_FILE}" = "y" ] && CT_DoLog ERROR "Look at '${CT_LOG_FILE}' for more info on this error."
yann@96
    19
    CT_STEP_COUNT=1
yann@96
    20
    CT_DoEnd ERROR
yann@1
    21
    exit $ret
yann@1
    22
}
yann@136
    23
yann@136
    24
# Install the fault handler
yann@1
    25
trap CT_OnError ERR
yann@1
    26
yann@136
    27
# Inherit the fault handler in subshells and functions
yann@1
    28
set -E
yann@136
    29
yann@136
    30
# Make pipes fail on the _first_ failed command
yann@136
    31
# Not supported on bash < 3.x, but we need it, so drop the obsoleting bash-2.x
yann@1
    32
set -o pipefail
yann@1
    33
yann@136
    34
# Don't hash commands' locations, and search every time it is requested.
yann@136
    35
# This is slow, but needed because of the static/shared core gcc which shall
yann@136
    36
# always match to shared if it exists, and only fallback to static if the
yann@136
    37
# shared is not found
yann@136
    38
set +o hashall
yann@136
    39
yann@165
    40
# Log policy:
yann@165
    41
#  - first of all, save stdout so we can see the live logs: fd #6
yann@165
    42
exec 6>&1
yann@165
    43
#  - then point stdout to the log file (temporary for now)
yann@165
    44
tmp_log_file="${CT_TOP_DIR}/log.$$"
yann@165
    45
exec >>"${tmp_log_file}"
yann@165
    46
yann@1
    47
# The different log levels:
yann@1
    48
CT_LOG_LEVEL_ERROR=0
yann@1
    49
CT_LOG_LEVEL_WARN=1
yann@1
    50
CT_LOG_LEVEL_INFO=2
yann@1
    51
CT_LOG_LEVEL_EXTRA=3
yann@1741
    52
CT_LOG_LEVEL_ALL=4
yann@1741
    53
CT_LOG_LEVEL_DEBUG=5
yann@1
    54
yann@1083
    55
# Make it easy to use \n and !
yann@1081
    56
CR=$(printf "\n")
yann@1083
    57
BANG='!'
yann@1081
    58
yann@1
    59
# A function to log what is happening
yann@1
    60
# Different log level are available:
yann@1
    61
#   - ERROR:   A serious, fatal error occurred
yann@1
    62
#   - WARN:    A non fatal, non serious error occurred, take your responsbility with the generated build
yann@1
    63
#   - INFO:    Informational messages
yann@1
    64
#   - EXTRA:   Extra informational messages
yann@1
    65
#   - DEBUG:   Debug messages
yann@78
    66
#   - ALL:     Component's build messages
yann@1
    67
# Usage: CT_DoLog <level> [message]
yann@1
    68
# If message is empty, then stdin will be logged.
yann@1
    69
CT_DoLog() {
yann@47
    70
    local max_level LEVEL level cur_l cur_L
yann@47
    71
    local l
yann@1
    72
    eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}"
yann@1
    73
    # Set the maximum log level to DEBUG if we have none
yann@78
    74
    [ -z "${max_level}" ] && max_level=${CT_LOG_LEVEL_DEBUG}
yann@1
    75
yann@47
    76
    LEVEL="$1"; shift
yann@1
    77
    eval level="\${CT_LOG_LEVEL_${LEVEL}}"
yann@1
    78
yann@1
    79
    if [ $# -eq 0 ]; then
yann@1
    80
        cat -
yann@1
    81
    else
yann@1516
    82
        printf "${*}\n"
yann@1081
    83
    fi |( IFS="${CR}" # We want the full lines, even leading spaces
yann@523
    84
          _prog_bar_cpt=0
yann@523
    85
          _prog_bar[0]='/'
yann@523
    86
          _prog_bar[1]='-'
yann@523
    87
          _prog_bar[2]='\'
yann@523
    88
          _prog_bar[3]='|'
yann@1
    89
          indent=$((2*CT_STEP_COUNT))
yann@1
    90
          while read line; do
yann@47
    91
              case "${CT_LOG_SEE_TOOLS_WARN},${line}" in
yann@47
    92
                y,*"warning:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
yann@112
    93
                y,*"WARNING:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
yann@47
    94
                *"error:"*)             cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
yann@919
    95
                *"make["*"]: *** ["*)   cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
yann@47
    96
                *)                      cur_L="${LEVEL}"; cur_l="${level}";;
yann@47
    97
              esac
yann@523
    98
              # There will always be a log file (stdout, fd #1), be it /dev/null
yann@523
    99
              printf "[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}"
yann@47
   100
              if [ ${cur_l} -le ${max_level} ]; then
yann@523
   101
                  # Only print to console (fd #6) if log level is high enough.
yann@523
   102
                  printf "\r[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" >&6
yann@82
   103
              fi
yann@82
   104
              if [ "${CT_LOG_PROGRESS_BAR}" = "y" ]; then
yann@523
   105
                  printf "\r[%02d:%02d] %s " $((SECONDS/60)) $((SECONDS%60)) "${_prog_bar[$((_prog_bar_cpt/10))]}" >&6
yann@523
   106
                  _prog_bar_cpt=$(((_prog_bar_cpt+1)%40))
yann@1
   107
              fi
yann@1
   108
          done
yann@1
   109
        )
yann@1
   110
yann@1
   111
    return 0
yann@1
   112
}
yann@1
   113
yann@535
   114
# Execute an action, and log its messages
yann@1257
   115
# Usage: [VAR=val...] CT_DoExecLog <level> <command [parameters...]>
yann@535
   116
CT_DoExecLog() {
yann@535
   117
    local level="$1"
yann@535
   118
    shift
yann@1516
   119
    CT_DoLog DEBUG "==> Executing: '${*}'"
yann@668
   120
    "${@}" 2>&1 |CT_DoLog "${level}"
yann@535
   121
}
yann@535
   122
yann@96
   123
# Tail message to be logged whatever happens
yann@96
   124
# Usage: CT_DoEnd <level>
yann@96
   125
CT_DoEnd()
yann@96
   126
{
yann@145
   127
    local level="$1"
yann@523
   128
    CT_STOP_DATE=$(CT_DoDate +%s%N)
yann@523
   129
    CT_STOP_DATE_HUMAN=$(CT_DoDate +%Y%m%d.%H%M%S)
yann@599
   130
    if [ "${level}" != "ERROR" ]; then
yann@582
   131
        CT_DoLog "${level:-INFO}" "Build completed at ${CT_STOP_DATE_HUMAN}"
yann@582
   132
    fi
yann@96
   133
    elapsed=$((CT_STOP_DATE-CT_STAR_DATE))
yann@96
   134
    elapsed_min=$((elapsed/(60*1000*1000*1000)))
yann@523
   135
    elapsed_sec=$(printf "%02d" $(((elapsed%(60*1000*1000*1000))/(1000*1000*1000))))
yann@523
   136
    elapsed_csec=$(printf "%02d" $(((elapsed%(1000*1000*1000))/(10*1000*1000))))
yann@145
   137
    CT_DoLog ${level:-INFO} "(elapsed: ${elapsed_min}:${elapsed_sec}.${elapsed_csec})"
yann@96
   138
}
yann@96
   139
js@2047
   140
# Remove entries referring to ., /tmp and non-existing directories from $PATH
js@2047
   141
# Usage: CT_SanitizePath
js@2047
   142
CT_SanitizePath() {
js@2047
   143
    local new
js@2047
   144
    local tmp
js@2047
   145
    local IFS=:
js@2047
   146
    for p in $PATH; do
js@2047
   147
        # Replace any occurence of . with $(pwd -P)
js@2047
   148
        # Use /tmp as a default if the directory is non-existent
js@2047
   149
        # Do not add /tmp in the PATH
js@2047
   150
        tmp="$( cd /tmp; cd "${p}" 2>/dev/null || true; pwd -P )"
js@2047
   151
        if [ "${tmp}" != "/tmp" ]; then
js@2047
   152
            new="${new}${new:+:}${p}"
js@2047
   153
        fi
js@2047
   154
    done
js@2047
   155
    PATH="${new}"
js@2047
   156
}
js@2047
   157
yann@96
   158
# Abort the execution with an error message
yann@1
   159
# Usage: CT_Abort <message>
yann@1
   160
CT_Abort() {
yann@128
   161
    CT_DoLog ERROR "$1"
yann@1
   162
    exit 1
yann@1
   163
}
yann@1
   164
yann@1
   165
# Test a condition, and print a message if satisfied
yann@1
   166
# Usage: CT_Test <message> <tests>
yann@1
   167
CT_Test() {
yann@1
   168
    local ret
yann@1
   169
    local m="$1"
yann@1
   170
    shift
yann@1909
   171
    CT_DoLog DEBUG "Testing '! ( $* )'"
yann@1
   172
    test "$@" && CT_DoLog WARN "$m"
yann@1
   173
    return 0
yann@1
   174
}
yann@1
   175
yann@1
   176
# Test a condition, and abort with an error message if satisfied
yann@1
   177
# Usage: CT_TestAndAbort <message> <tests>
yann@1
   178
CT_TestAndAbort() {
yann@1
   179
    local m="$1"
yann@1
   180
    shift
yann@1909
   181
    CT_DoLog DEBUG "Testing '! ( $* )'"
yann@1
   182
    test "$@" && CT_Abort "$m"
yann@1
   183
    return 0
yann@1
   184
}
yann@1
   185
yann@1
   186
# Test a condition, and abort with an error message if not satisfied
yann@1
   187
# Usage: CT_TestAndAbort <message> <tests>
yann@1
   188
CT_TestOrAbort() {
yann@1
   189
    local m="$1"
yann@1
   190
    shift
yann@1909
   191
    CT_DoLog DEBUG "Testing '$*'"
yann@1
   192
    test "$@" || CT_Abort "$m"
yann@1
   193
    return 0
yann@1
   194
}
yann@1
   195
yann@1
   196
# Test the presence of a tool, or abort if not found
yann@1
   197
# Usage: CT_HasOrAbort <tool>
yann@1
   198
CT_HasOrAbort() {
yann@773
   199
    CT_TestAndAbort "'${1}' not found and needed for successful toolchain build." -z "$(CT_Which "${1}")"
yann@1
   200
    return 0
yann@1
   201
}
yann@1
   202
yann@210
   203
# Search a program: wrap "which" for those system where
yann@1226
   204
# "which" verbosely says there is no match (Mandriva is
yann@1226
   205
# such a sucker...)
yann@210
   206
# Usage: CT_Which <filename>
yann@210
   207
CT_Which() {
yann@210
   208
  which "$1" 2>/dev/null || true
yann@210
   209
}
yann@210
   210
yann@1
   211
# Get current date with nanosecond precision
yann@1
   212
# On those system not supporting nanosecond precision, faked with rounding down
yann@1
   213
# to the highest entire second
yann@1
   214
# Usage: CT_DoDate <fmt>
yann@1
   215
CT_DoDate() {
tvb377@1798
   216
    date "$1" |sed -r -e 's/N$/000000000/;'
yann@1
   217
}
yann@1
   218
yann@1
   219
CT_STEP_COUNT=1
yann@1
   220
CT_STEP_MESSAGE[${CT_STEP_COUNT}]="<none>"
yann@1
   221
# Memorise a step being done so that any error is caught
yann@1
   222
# Usage: CT_DoStep <loglevel> <message>
yann@1
   223
CT_DoStep() {
yann@523
   224
    local start=$(CT_DoDate +%s%N)
yann@1
   225
    CT_DoLog "$1" "================================================================="
yann@1
   226
    CT_DoLog "$1" "$2"
yann@1
   227
    CT_STEP_COUNT=$((CT_STEP_COUNT+1))
yann@1
   228
    CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift
yann@1
   229
    CT_STEP_START[${CT_STEP_COUNT}]="${start}"
yann@1
   230
    CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1"
yann@1
   231
    return 0
yann@1
   232
}
yann@1
   233
yann@1
   234
# End the step just being done
yann@1
   235
# Usage: CT_EndStep
yann@1
   236
CT_EndStep() {
yann@523
   237
    local stop=$(CT_DoDate +%s%N)
yann@523
   238
    local duration=$(printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) |sed -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;')
yann@582
   239
    local elapsed=$(printf "%02d:%02d" $((SECONDS/60)) $((SECONDS%60)))
yann@1
   240
    local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}"
yann@1
   241
    local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}"
yann@1
   242
    CT_STEP_COUNT=$((CT_STEP_COUNT-1))
yann@582
   243
    CT_DoLog "${level}" "${message}: done in ${duration}s (at ${elapsed})"
yann@1
   244
    return 0
yann@1
   245
}
yann@1
   246
yann@1
   247
# Pushes into a directory, and pops back
yann@1
   248
CT_Pushd() {
yann@1
   249
    pushd "$1" >/dev/null 2>&1
yann@1
   250
}
yann@1
   251
CT_Popd() {
yann@1
   252
    popd >/dev/null 2>&1
yann@1
   253
}
yann@1
   254
yann@1
   255
# Creates a temporary directory
yann@1
   256
# $1: variable to assign to
yann@1
   257
# Usage: CT_MktempDir foo
yann@1
   258
CT_MktempDir() {
yann@1
   259
    # Some mktemp do not allow more than 6 Xs
yann@1113
   260
    eval "$1"=$(mktemp -q -d "${CT_BUILD_DIR}/tmp.XXXXXX")
yann@1
   261
    CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}"
yann@787
   262
    CT_DoLog DEBUG "Made temporary directory '${!1}'"
yann@787
   263
    return 0
yann@1
   264
}
yann@1
   265
yann@1148
   266
# Removes one or more directories, even if it is read-only, or its parent is
yann@1138
   267
# Usage: CT_DoForceRmdir dir [...]
yann@1138
   268
CT_DoForceRmdir() {
yann@1148
   269
    local dir
yann@1148
   270
    local mode
yann@1148
   271
    for dir in "${@}"; do
yann@1148
   272
        [ -d "${dir}" ] || continue
yann@1185
   273
        mode="$(stat -c '%a' "$(dirname "${dir}")")"
yann@1185
   274
        CT_DoExecLog ALL chmod u+w "$(dirname "${dir}")"
yann@1185
   275
        CT_DoExecLog ALL chmod -R u+w "${dir}"
yann@1148
   276
        CT_DoExecLog ALL rm -rf "${dir}"
yann@1185
   277
        CT_DoExecLog ALL chmod ${mode} "$(dirname "${dir}")"
yann@1148
   278
    done
yann@1138
   279
}
yann@1138
   280
yann@1
   281
# Echoes the specified string on stdout until the pipe breaks.
yann@1
   282
# Doesn't fail
yann@1
   283
# $1: string to echo
yann@1
   284
# Usage: CT_DoYes "" |make oldconfig
yann@1
   285
CT_DoYes() {
yann@1
   286
    yes "$1" || true
yann@1
   287
}
yann@63
   288
yann@1391
   289
# Add the specified directory to LD_LIBRARY_PATH, and export it
yann@1391
   290
# If the specified patch is already present, just export
yann@1391
   291
# $1: path to add
yann@1391
   292
# $2: add as 'first' or 'last' path, 'first' is assumed if $2 is empty
yann@1391
   293
# Usage CT_SetLibPath /some/where/lib [first|last]
yann@1391
   294
CT_SetLibPath() {
yann@1391
   295
    local path="$1"
yann@1391
   296
    local pos="$2"
yann@1391
   297
yann@1391
   298
    case ":${LD_LIBRARY_PATH}:" in
yann@1391
   299
        *:"${path}":*)  ;;
yann@1391
   300
        *)  case "${pos}" in
yann@1391
   301
                last)
yann@1391
   302
                    CT_DoLog DEBUG "Adding '${path}' at end of LD_LIBRARY_PATH"
yann@1391
   303
                    LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}${path}"
yann@1391
   304
                    ;;
yann@1391
   305
                first|"")
yann@1391
   306
                    CT_DoLog DEBUG "Adding '${path}' at start of LD_LIBRARY_PATH"
yann@1391
   307
                    LD_LIBRARY_PATH="${path}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
yann@1391
   308
                    ;;
yann@1391
   309
                *)
yann@1391
   310
                    CT_Abort "Incorrect position '${pos}' to add '${path}' to LD_LIBRARY_PATH"
yann@1391
   311
                    ;;
yann@1391
   312
            esac
yann@1391
   313
            ;;
yann@1391
   314
    esac
yann@1391
   315
    CT_DoLog DEBUG "==> LD_LIBRARY_PATH='${LD_LIBRARY_PATH}'"
yann@1391
   316
    export LD_LIBRARY_PATH
yann@1391
   317
}
yann@1391
   318
yann@85
   319
# Get the file name extension of a component
yann@719
   320
# Usage: CT_GetFileExtension <component_name-component_version> [extension]
yann@1690
   321
# If found, echoes the extension to stdout, and return 0
yann@1690
   322
# If not found, echoes nothing on stdout, and return !0.
yann@85
   323
CT_GetFileExtension() {
yann@85
   324
    local ext
yann@85
   325
    local file="$1"
yann@719
   326
    shift
yann@719
   327
    local first_ext="$1"
yann@85
   328
yann@160
   329
    # we need to also check for an empty extension for those very
yann@160
   330
    # peculiar components that don't have one (such as sstrip from
yann@160
   331
    # buildroot).
yann@1763
   332
    for ext in ${first_ext} .tar.gz .tar.bz2 .tgz .tar /.git ''; do
yann@1763
   333
        if [ -e "${CT_TARBALLS_DIR}/${file}${ext}" ]; then
yann@85
   334
            echo "${ext}"
yann@1690
   335
            exit 0
yann@85
   336
        fi
yann@85
   337
    done
yann@85
   338
yann@1690
   339
    exit 1
yann@85
   340
}
yann@85
   341
yann@63
   342
# Download an URL using wget
yann@63
   343
# Usage: CT_DoGetFileWget <URL>
yann@63
   344
CT_DoGetFileWget() {
yann@63
   345
    # Need to return true because it is legitimate to not find the tarball at
yann@63
   346
    # some of the provided URLs (think about snapshots, different layouts for
yann@63
   347
    # different gcc versions, etc...)
yann@63
   348
    # Some (very old!) FTP server might not support the passive mode, thus
yann@63
   349
    # retry without
yann@63
   350
    # With automated download as we are doing, it can be very dangerous to use
yann@63
   351
    # -c to continue the downloads. It's far better to simply overwrite the
yann@63
   352
    # destination file
yann@492
   353
    # Some company networks have firewalls to connect to the internet, but it's
yann@1113
   354
    # not easy to detect them, and wget does not timeout by default while
yann@492
   355
    # connecting, so force a global ${CT_CONNECT_TIMEOUT}-second timeout.
yann@1257
   356
    CT_DoExecLog ALL wget -T ${CT_CONNECT_TIMEOUT} -nc --progress=dot:binary --tries=3 --passive-ftp "$1"    \
yann@1257
   357
    || CT_DoExecLog ALL wget -T ${CT_CONNECT_TIMEOUT} -nc --progress=dot:binary --tries=3 "$1"               \
yann@439
   358
    || true
yann@63
   359
}
yann@63
   360
yann@63
   361
# Download an URL using curl
yann@63
   362
# Usage: CT_DoGetFileCurl <URL>
yann@63
   363
CT_DoGetFileCurl() {
yann@492
   364
    # Note: comments about wget method (above) are also valid here
yann@439
   365
    # Plus: no good progress indicator is available with curl,
yann@1257
   366
    #       so, be silent.
richard@1720
   367
    CT_DoExecLog ALL curl -s --ftp-pasv -O --retry 3 "$1" --connect-timeout ${CT_CONNECT_TIMEOUT} -L -f  \
richard@1720
   368
    || CT_DoExecLog ALL curl -s -O --retry 3 "$1" --connect-timeout ${CT_CONNECT_TIMEOUT} -L -f          \
yann@439
   369
    || true
yann@63
   370
}
yann@63
   371
yann@1669
   372
# Download using aria2
yann@1669
   373
# Usage: CT_DoGetFileAria2 <URL>
yann@1669
   374
CT_DoGetFileAria2() {
yann@1669
   375
    # Note: comments about curl method (above) are also valid here
yann@1669
   376
    # Plus: default progress indicator is a single line, so use verbose log
yann@1669
   377
    #       so that the CT-NG's ouput is 'live'.
yann@1680
   378
    CT_DoExecLog ALL aria2c --summary-interval=1 -s ${CT_DOWNLOAD_MAX_CHUNKS} -m 3 -t ${CT_CONNECT_TIMEOUT} -p "$1" \
yann@1680
   379
    || CT_DoExecLog ALL aria2c --summary-interval=1 -s ${CT_DOWNLOAD_MAX_CHUNKS} -m 3 -t ${CT_CONNECT_TIMEOUT} "$1" \
yann@1673
   380
    || rm -f "${1##*/}"
yann@1669
   381
}
yann@1669
   382
yann@1669
   383
# OK, just look if we have them...
yann@1669
   384
_aria2c=$(CT_Which aria2c)
yann@523
   385
_wget=$(CT_Which wget)
yann@523
   386
_curl=$(CT_Which curl)
yann@1669
   387
yann@1669
   388
# Wrapper function to call one of, in order of preference:
yann@1669
   389
#   aria2
yann@1669
   390
#   curl
yann@1669
   391
#   wget
yann@63
   392
# Usage: CT_DoGetFile <URL>
yann@63
   393
CT_DoGetFile() {
yann@1669
   394
    if   [ -n "${_aria2c}" ]; then
yann@1669
   395
        CT_DoGetFileAria2 "$1"
yann@1669
   396
    elif [ -n "${_curl}" ]; then
yann@1668
   397
        CT_DoGetFileCurl "$1"
yann@1668
   398
    elif [ -n "${_wget}" ]; then
yann@1668
   399
        CT_DoGetFileWget "$1"
yann@1668
   400
    else
yann@1668
   401
        CT_Abort "Could find neither wget nor curl"
yann@1668
   402
    fi
yann@63
   403
}
yann@63
   404
yann@1113
   405
# This function tries to retrieve a tarball form a local directory
yann@1113
   406
# Usage: CT_GetLocal <basename> [.extension]
yann@1113
   407
CT_GetLocal() {
yann@1113
   408
    local basename="$1"
yann@1113
   409
    local first_ext="$2"
yann@1113
   410
    local ext
yann@1113
   411
yann@1113
   412
    # Do we already have it in *our* tarballs dir?
yann@1690
   413
    if ext="$( CT_GetFileExtension "${basename}" ${first_ext} )"; then
yann@1113
   414
        CT_DoLog DEBUG "Already have '${basename}'"
yann@1113
   415
        return 0
yann@1113
   416
    fi
yann@1113
   417
yann@1113
   418
    if [ -n "${CT_LOCAL_TARBALLS_DIR}" ]; then
yann@1113
   419
        CT_DoLog DEBUG "Trying to retrieve an already downloaded copy of '${basename}'"
yann@1113
   420
        # We'd rather have a bzip2'ed tarball, then gzipped tarball, plain tarball,
yann@1113
   421
        # or, as a failover, a file without extension.
yann@1113
   422
        for ext in ${first_ext} .tar.bz2 .tar.gz .tgz .tar ''; do
yann@1113
   423
            CT_DoLog DEBUG "Trying '${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}'"
yann@1113
   424
            if [ -r "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" -a \
yann@1113
   425
                 "${CT_FORCE_DOWNLOAD}" != "y" ]; then
yann@1113
   426
                CT_DoLog DEBUG "Got '${basename}' from local storage"
yann@1113
   427
                CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" "${CT_TARBALLS_DIR}/${basename}${ext}"
yann@1113
   428
                return 0
yann@1113
   429
            fi
yann@1113
   430
        done
yann@1113
   431
    fi
yann@1113
   432
    return 1
yann@1113
   433
}
yann@1113
   434
yann@1113
   435
# This function saves the specified to local storage if possible,
yann@1113
   436
# and if so, symlinks it for later usage
yann@1113
   437
# Usage: CT_SaveLocal </full/path/file.name>
yann@1113
   438
CT_SaveLocal() {
yann@1113
   439
    local file="$1"
yann@1113
   440
    local basename="${file##*/}"
yann@1113
   441
yann@1113
   442
    if [ "${CT_SAVE_TARBALLS}" = "y" ]; then
yann@1134
   443
        CT_DoLog EXTRA "Saving '${basename}' to local storage"
yann@1113
   444
        # The file may already exist if downloads are forced: remove it first
yann@1113
   445
        CT_DoExecLog ALL rm -f "${CT_LOCAL_TARBALLS_DIR}/${basename}"
yann@1113
   446
        CT_DoExecLog ALL mv -f "${file}" "${CT_LOCAL_TARBALLS_DIR}"
yann@1113
   447
        CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${basename}" "${file}"
yann@1113
   448
    fi
yann@1113
   449
}
yann@1113
   450
yann@63
   451
# Download the file from one of the URLs passed as argument
yann@1113
   452
# Usage: CT_GetFile <basename> [.extension] <url> [url ...]
yann@63
   453
CT_GetFile() {
yann@63
   454
    local ext
yann@1179
   455
    local url URLS LAN_URLS
yann@63
   456
    local file="$1"
yann@1113
   457
    local first_ext
yann@63
   458
    shift
yann@712
   459
    # If next argument starts with a dot, then this is not an URL,
yann@712
   460
    # and we can consider that it is a preferred extension.
yann@242
   461
    case "$1" in
yann@712
   462
        .*) first_ext="$1"
yann@242
   463
            shift
yann@242
   464
            ;;
yann@242
   465
    esac
yann@63
   466
yann@1113
   467
    # Does it exist localy?
yann@1113
   468
    CT_GetLocal "${file}" ${first_ext} && return 0 || true
yann@1113
   469
    # No, it does not...
yann@63
   470
yann@754
   471
    # Try to retrieve the file
yann@788
   472
    CT_DoLog EXTRA "Retrieving '${file}'"
yann@63
   473
    CT_Pushd "${CT_TARBALLS_DIR}"
yann@754
   474
yann@1179
   475
    URLS="$@"
yann@1179
   476
yann@1022
   477
    # Add URLs on the LAN mirror
yann@1022
   478
    LAN_URLS=
yann@1022
   479
    if [ "${CT_USE_MIRROR}" = "y" ]; then
yann@1294
   480
        CT_TestOrAbort "Please set the mirror base URL" -n "${CT_MIRROR_BASE_URL}"
yann@1294
   481
        LAN_URLS="${LAN_URLS} ${CT_MIRROR_BASE_URL}/${file%-*}"
yann@1294
   482
        LAN_URLS="${LAN_URLS} ${CT_MIRROR_BASE_URL}"
yann@695
   483
yann@1134
   484
        if [ "${CT_PREFER_MIRROR}" = "y" ]; then
yann@1134
   485
            CT_DoLog DEBUG "Pre-pending LAN mirror URLs"
yann@1179
   486
            URLS="${LAN_URLS} ${URLS}"
yann@1134
   487
        else
yann@1134
   488
            CT_DoLog DEBUG "Appending LAN mirror URLs"
yann@1179
   489
            URLS="${URLS} ${LAN_URLS}"
yann@1134
   490
        fi
yann@1022
   491
    fi
yann@1022
   492
yann@1022
   493
    # Scan all URLs in turn, and try to grab a tarball from there
yann@1763
   494
    # Do *not* try git trees (ext=/.git), this is handled in a specific
yann@1763
   495
    # wrapper, below
yann@242
   496
    for ext in ${first_ext} .tar.bz2 .tar.gz .tgz .tar ''; do
yann@102
   497
        # Try all urls in turn
yann@1022
   498
        for url in ${URLS}; do
yann@523
   499
            CT_DoLog DEBUG "Trying '${url}/${file}${ext}'"
yann@265
   500
            CT_DoGetFile "${url}/${file}${ext}"
yann@265
   501
            if [ -f "${file}${ext}" ]; then
yann@799
   502
                CT_DoLog DEBUG "Got '${file}' from the Internet"
yann@1113
   503
                CT_SaveLocal "${CT_TARBALLS_DIR}/${file}${ext}"
yann@265
   504
                return 0
yann@265
   505
            fi
yann@102
   506
        done
yann@102
   507
    done
yann@63
   508
    CT_Popd
yann@63
   509
yann@754
   510
    CT_Abort "Could not retrieve '${file}'."
yann@63
   511
}
yann@63
   512
yann@1113
   513
# Checkout from CVS, and build the associated tarball
yann@1113
   514
# The tarball will be called ${basename}.tar.bz2
yann@1113
   515
# Prerequisite: either the server does not require password,
yann@1113
   516
# or the user must already be logged in.
yann@1113
   517
# 'tag' is the tag to retrieve. Must be specified, but can be empty.
yann@1113
   518
# If dirname is specified, then module will be renamed to dirname
yann@1113
   519
# prior to building the tarball.
yann@1592
   520
# Usage: CT_GetCVS <basename> <url> <module> <tag> [dirname[=subdir]]
yann@1592
   521
# Note: if '=subdir' is given, then it is used instead of 'module'.
yann@1113
   522
CT_GetCVS() {
yann@1113
   523
    local basename="$1"
yann@1113
   524
    local uri="$2"
yann@1113
   525
    local module="$3"
yann@1113
   526
    local tag="${4:+-r ${4}}"
yann@1113
   527
    local dirname="$5"
yann@1113
   528
    local tmp_dir
yann@1113
   529
yann@1113
   530
    # Does it exist localy?
yann@1113
   531
    CT_GetLocal "${basename}" && return 0 || true
yann@1113
   532
    # No, it does not...
yann@1113
   533
yann@1113
   534
    CT_DoLog EXTRA "Retrieving '${basename}'"
yann@1113
   535
yann@1113
   536
    CT_MktempDir tmp_dir
yann@1113
   537
    CT_Pushd "${tmp_dir}"
yann@1113
   538
yann@1113
   539
    CT_DoExecLog ALL cvs -z 9 -d "${uri}" co -P ${tag} "${module}"
yann@1592
   540
    if [ -n "${dirname}" ]; then
yann@1592
   541
        case "${dirname}" in
yann@1592
   542
            *=*)
yann@1593
   543
                CT_DoExecLog DEBUG mv "${dirname#*=}" "${dirname%%=*}"
yann@1593
   544
                CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${dirname%%=*}"
yann@1592
   545
                ;;
yann@1592
   546
            *)
yann@1592
   547
                CT_DoExecLog ALL mv "${module}" "${dirname}"
yann@1592
   548
                CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${dirname:-${module}}"
yann@1592
   549
                ;;
yann@1592
   550
        esac
yann@1592
   551
    fi
yann@1113
   552
    CT_SaveLocal "${CT_TARBALLS_DIR}/${basename}.tar.bz2"
yann@1113
   553
yann@1113
   554
    CT_Popd
yann@1113
   555
    CT_DoExecLog ALL rm -rf "${tmp_dir}"
yann@1113
   556
}
yann@1113
   557
yann@1244
   558
# Check out from SVN, and build the associated tarball
yann@1244
   559
# The tarball will be called ${basename}.tar.bz2
yann@1244
   560
# Prerequisite: either the server does not require password,
yann@1244
   561
# or the user must already be logged in.
yann@1244
   562
# 'rev' is the revision to retrieve
yann@1244
   563
# Usage: CT_GetSVN <basename> <url> [rev]
yann@1244
   564
CT_GetSVN() {
yann@1244
   565
    local basename="$1"
yann@1244
   566
    local uri="$2"
yann@1244
   567
    local rev="$3"
yann@1244
   568
yann@1244
   569
    # Does it exist localy?
yann@1244
   570
    CT_GetLocal "${basename}" && return 0 || true
yann@1244
   571
    # No, it does not...
yann@1244
   572
yann@1244
   573
    CT_DoLog EXTRA "Retrieving '${basename}'"
yann@1244
   574
yann@1244
   575
    CT_MktempDir tmp_dir
yann@1244
   576
    CT_Pushd "${tmp_dir}"
yann@1244
   577
yann@1244
   578
    CT_DoExecLog ALL svn export ${rev:+-r ${rev}} "${uri}" "${basename}"
yann@1244
   579
    CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${basename}"
yann@1244
   580
    CT_SaveLocal "${CT_TARBALLS_DIR}/${basename}.tar.bz2"
yann@1244
   581
yann@1244
   582
    CT_Popd
yann@1244
   583
    CT_DoExecLog ALL rm -rf "${tmp_dir}"
yann@1244
   584
}
yann@1244
   585
yann@1763
   586
# Clone a git tree
yann@1763
   587
# Tries the given URLs in turn until one can get cloned. No tarball will be created.
yann@1763
   588
# Prerequisites: either the server does not require password,
yann@1763
   589
# or the user has already taken any action to authenticate to the server.
yann@1763
   590
# The cloned tree will *not* be stored in the local tarballs dir!
yann@1763
   591
# Usage: CT_GetGit <basename> <url [url ...]>
yann@1763
   592
CT_GetGit() {
yann@1763
   593
    local basename="$1"; shift
yann@1763
   594
    local url
yann@1763
   595
    local cloned=0
yann@1763
   596
yann@1763
   597
    # Do we have it in our tarballs dir?
yann@1763
   598
    if [ -d "${CT_TARBALLS_DIR}/${basename}/.git" ]; then
yann@1763
   599
        CT_DoLog EXTRA "Updating git tree '${basename}'"
yann@1763
   600
        CT_Pushd "${CT_TARBALLS_DIR}/${basename}"
yann@1763
   601
        CT_DoExecLog ALL git pull
yann@1763
   602
        CT_Popd
yann@1763
   603
    else
yann@1763
   604
        CT_DoLog EXTRA "Retrieving git tree '${basename}'"
yann@1763
   605
        for url in "${@}"; do
yann@1763
   606
            CT_DoLog ALL "Trying to clone from '${url}'"
yann@1763
   607
            CT_DoForceRmdir "${CT_TARBALLS_DIR}/${basename}"
yann@1763
   608
            if git clone "${url}" "${CT_TARBALLS_DIR}/${basename}" 2>&1 |CT_DoLog ALL; then
yann@1763
   609
                cloned=1
yann@1763
   610
                break
yann@1763
   611
            fi
yann@1763
   612
        done
yann@1763
   613
        CT_TestOrAbort "Could not clone '${basename}'" ${cloned} -ne 0
yann@1763
   614
    fi
yann@1763
   615
}
yann@1763
   616
yann@1126
   617
# Extract a tarball
yann@63
   618
# Some tarballs need to be extracted in specific places. Eg.: glibc addons
yann@63
   619
# must be extracted in the glibc directory; uCLibc locales must be extracted
yann@1123
   620
# in the extra/locale sub-directory of uClibc. This is taken into account
yann@1123
   621
# by the caller, that did a 'cd' into the correct path before calling us
yann@1123
   622
# and sets nochdir to 'nochdir'.
yann@1763
   623
# Note also that this function handles the git trees!
yann@1763
   624
# Usage: CT_Extract <basename> [nochdir] [options]
yann@1763
   625
# where 'options' are dependent on the source (eg. git branch/tag...)
yann@1126
   626
CT_Extract() {
yann@1761
   627
    local nochdir="$1"
yann@1761
   628
    local basename
yann@1690
   629
    local ext
yann@1690
   630
yann@1761
   631
    if [ "${nochdir}" = "nochdir" ]; then
yann@1761
   632
        shift
yann@1761
   633
        nochdir="$(pwd)"
yann@1761
   634
    else
yann@1761
   635
        nochdir="${CT_SRC_DIR}"
yann@1761
   636
    fi
yann@1761
   637
yann@1761
   638
    basename="$1"
yann@1761
   639
    shift
yann@1761
   640
yann@1690
   641
    if ! ext="$(CT_GetFileExtension "${basename}")"; then
yann@1763
   642
      CT_Abort "'${basename}' not found in '${CT_TARBALLS_DIR}'"
yann@1690
   643
    fi
yann@1126
   644
    local full_file="${CT_TARBALLS_DIR}/${basename}${ext}"
yann@1126
   645
yann@1718
   646
    # Check if already extracted
yann@1718
   647
    if [ -e "${CT_SRC_DIR}/.${basename}.extracted" ]; then
yann@1718
   648
        CT_DoLog DEBUG "Already extracted '${basename}'"
yann@1718
   649
        return 0
yann@1718
   650
    fi
yann@1718
   651
yann@1691
   652
    # Check if previously partially extracted
yann@1691
   653
    if [ -e "${CT_SRC_DIR}/.${basename}.extracting" ]; then
yann@1691
   654
        CT_DoLog ERROR "The '${basename}' sources were partially extracted."
yann@1691
   655
        CT_DoLog ERROR "Please remove first:"
yann@1691
   656
        CT_DoLog ERROR " - the source dir for '${basename}', in '${CT_SRC_DIR}'"
yann@1691
   657
        CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${basename}.extracting'"
yann@1691
   658
        CT_Abort "I'll stop now to avoid any carnage..."
yann@1691
   659
    fi
yann@1691
   660
    CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${basename}.extracting"
yann@1691
   661
yann@1761
   662
    CT_Pushd "${nochdir}"
yann@63
   663
yann@1126
   664
    CT_DoLog EXTRA "Extracting '${basename}'"
yann@63
   665
    case "${ext}" in
yann@776
   666
        .tar.bz2)     CT_DoExecLog ALL tar xvjf "${full_file}";;
yann@776
   667
        .tar.gz|.tgz) CT_DoExecLog ALL tar xvzf "${full_file}";;
yann@776
   668
        .tar)         CT_DoExecLog ALL tar xvf  "${full_file}";;
yann@1763
   669
        /.git)        CT_ExtractGit "${basename}" "${@}";;
yann@1763
   670
        *)            CT_Abort "Don't know how to handle '${basename}${ext}': unknown extension";;
yann@63
   671
    esac
yann@63
   672
yann@1208
   673
    # Some tarballs have read-only files... :-(
yann@1258
   674
    # Because of nochdir, we don't know where we are, so chmod all
yann@1258
   675
    # the src tree
yann@1271
   676
    CT_DoExecLog DEBUG chmod -R u+w "${CT_SRC_DIR}"
yann@1208
   677
yann@1763
   678
    # Don't mark as being extracted for git
yann@1763
   679
    case "${ext}" in
yann@1763
   680
        /.git)  ;;
yann@1763
   681
        *)      CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${basename}.extracted";;
yann@1763
   682
    esac
yann@1691
   683
    CT_DoExecLog DEBUG rm -f "${CT_SRC_DIR}/.${basename}.extracting"
yann@1126
   684
yann@1761
   685
    CT_Popd
yann@1126
   686
}
yann@1126
   687
yann@1763
   688
# Create a working git clone
yann@1763
   689
# Usage: CT_ExtractGit <basename> [ref]
yann@1763
   690
# where 'ref' is the reference to use:
yann@1763
   691
#   the full name of a branch, like "remotes/origin/branch_name"
yann@1763
   692
#   a date as understandable by git, like "YYYY-MM-DD[ hh[:mm[:ss]]]"
yann@1763
   693
#   a tag name
yann@1763
   694
CT_ExtractGit() {
yann@1763
   695
    local basename="${1}"
yann@1763
   696
    local ref="${2}"
yann@1763
   697
    local clone_dir
yann@1763
   698
    local ref_type
yann@1763
   699
yann@1763
   700
    # pushd now to be able to get git revlist in case ref is a date
yann@1763
   701
    clone_dir="${CT_TARBALLS_DIR}/${basename}"
yann@1763
   702
    CT_Pushd "${clone_dir}"
yann@1763
   703
yann@1763
   704
    # What kind of reference is ${ref} ?
yann@1763
   705
    if [ -z "${ref}" ]; then
yann@1763
   706
        # Don't update the clone, keep as-is
yann@1763
   707
        ref_type=none
yann@1763
   708
    elif git tag |grep -E "^${ref}$" >/dev/null 2>&1; then
yann@1763
   709
        ref_type=tag
yann@1763
   710
    elif git branch -a --no-color |grep -E "^. ${ref}$" >/dev/null 2>&1; then
yann@1763
   711
        ref_type=branch
yann@1763
   712
    elif date -d "${ref}" >/dev/null 2>&1; then
yann@1763
   713
        ref_type=date
yann@1763
   714
        ref=$(git rev-list -n1 --before="${ref}")
yann@1763
   715
    else
yann@1763
   716
        CT_Abort "Reference '${ref}' is an incorrect git reference: neither tag, branch nor date"
yann@1763
   717
    fi
yann@1763
   718
yann@1763
   719
    CT_DoExecLog DEBUG rm -f "${CT_SRC_DIR}/${basename}"
yann@1763
   720
    CT_DoExecLog ALL ln -sf "${clone_dir}" "${CT_SRC_DIR}/${basename}"
yann@1763
   721
yann@1763
   722
    case "${ref_type}" in
yann@1763
   723
        none)   ;;
yann@1763
   724
        *)      CT_DoExecLog ALL git checkout "${ref}";;
yann@1763
   725
    esac
yann@1763
   726
yann@1763
   727
    CT_Popd
yann@1763
   728
}
yann@1763
   729
yann@1126
   730
# Patches the specified component
yann@1761
   731
# See CT_Extract, above, for explanations on 'nochdir'
yann@1901
   732
# Usage: CT_Patch [nochdir] <packagename> <packageversion>
yann@1901
   733
# If the package directory is *not* packagename-packageversion, then
yann@1901
   734
# the caller must cd into the proper directory first, and call us
yann@1901
   735
# with nochdir
yann@1126
   736
CT_Patch() {
yann@1761
   737
    local nochdir="$1"
yann@1901
   738
    local pkgname
yann@1901
   739
    local version
yann@1901
   740
    local pkgdir
yann@1761
   741
    local base_file
yann@1761
   742
    local ver_file
yann@1507
   743
    local d
yann@1507
   744
    local -a patch_dirs
yann@1507
   745
    local bundled_patch_dir
yann@1507
   746
    local local_patch_dir
yann@1126
   747
yann@1761
   748
    if [ "${nochdir}" = "nochdir" ]; then
yann@1761
   749
        shift
yann@1906
   750
        pkgname="$1"
yann@1906
   751
        version="$2"
yann@1906
   752
        pkgdir="${pkgname}-${version}"
yann@1761
   753
        nochdir="$(pwd)"
yann@1761
   754
    else
yann@1906
   755
        pkgname="$1"
yann@1906
   756
        version="$2"
yann@1906
   757
        pkgdir="${pkgname}-${version}"
yann@1901
   758
        nochdir="${CT_SRC_DIR}/${pkgdir}"
yann@1761
   759
    fi
yann@1761
   760
yann@1126
   761
    # Check if already patched
yann@1901
   762
    if [ -e "${CT_SRC_DIR}/.${pkgdir}.patched" ]; then
yann@1901
   763
        CT_DoLog DEBUG "Already patched '${pkgdir}'"
yann@1126
   764
        return 0
yann@63
   765
    fi
yann@63
   766
yann@1271
   767
    # Check if already partially patched
yann@1901
   768
    if [ -e "${CT_SRC_DIR}/.${pkgdir}.patching" ]; then
yann@1901
   769
        CT_DoLog ERROR "The '${pkgdir}' sources were partially patched."
yann@1271
   770
        CT_DoLog ERROR "Please remove first:"
yann@1901
   771
        CT_DoLog ERROR " - the source dir for '${pkgdir}', in '${CT_SRC_DIR}'"
yann@1901
   772
        CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${pkgdir}.extracted'"
yann@1901
   773
        CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${pkgdir}.patching'"
yann@1271
   774
        CT_Abort "I'll stop now to avoid any carnage..."
yann@1271
   775
    fi
yann@1901
   776
    touch "${CT_SRC_DIR}/.${pkgdir}.patching"
yann@1271
   777
yann@1761
   778
    CT_Pushd "${nochdir}"
yann@1123
   779
yann@1901
   780
    CT_DoLog EXTRA "Patching '${pkgdir}'"
yann@63
   781
yann@1901
   782
    bundled_patch_dir="${CT_LIB_DIR}/patches/${pkgname}/${version}"
yann@1901
   783
    local_patch_dir="${CT_LOCAL_PATCH_DIR}/${pkgname}/${version}"
yann@1507
   784
yann@1507
   785
    case "${CT_PATCH_ORDER}" in
yann@1507
   786
        bundled)        patch_dirs=("${bundled_patch_dir}");;
yann@1507
   787
        local)          patch_dirs=("${local_patch_dir}");;
yann@1507
   788
        bundled,local)  patch_dirs=("${bundled_patch_dir}" "${local_patch_dir}");;
yann@1508
   789
        local,bundled)  patch_dirs=("${local_patch_dir}" "${bundled_patch_dir}");;
yann@1630
   790
        none)           patch_dirs=;;
yann@1507
   791
    esac
yann@1507
   792
yann@1507
   793
    for d in "${patch_dirs[@]}"; do
yann@1507
   794
        CT_DoLog DEBUG "Looking for patches in '${d}'..."
yann@1507
   795
        if [ -n "${d}" -a -d "${d}" ]; then
yann@1507
   796
            for p in "${d}"/*.patch; do
yann@63
   797
                if [ -f "${p}" ]; then
yann@523
   798
                    CT_DoLog DEBUG "Applying patch '${p}'"
yann@1765
   799
                    CT_DoExecLog ALL patch --no-backup-if-mismatch -g0 -F1 -p1 -f <"${p}"
yann@63
   800
                fi
yann@63
   801
            done
yann@1509
   802
            if [ "${CT_PATCH_SINGLE}" = "y" ]; then
yann@1509
   803
                break
yann@1509
   804
            fi
yann@63
   805
        fi
yann@63
   806
    done
yann@63
   807
yann@508
   808
    if [ "${CT_OVERIDE_CONFIG_GUESS_SUB}" = "y" ]; then
yann@508
   809
        CT_DoLog ALL "Overiding config.guess and config.sub"
yann@508
   810
        for cfg in config_guess config_sub; do
yann@1101
   811
            eval ${cfg}="${CT_LIB_DIR}/scripts/${cfg/_/.}"
yann@1101
   812
            [ -e "${CT_TOP_DIR}/scripts/${cfg/_/.}" ] && eval ${cfg}="${CT_TOP_DIR}/scripts/${cfg/_/.}"
yann@776
   813
            # Can't use CT_DoExecLog because of the '{} \;' to be passed un-mangled to find
yann@508
   814
            find . -type f -name "${cfg/_/.}" -exec cp -v "${!cfg}" {} \; |CT_DoLog ALL
yann@508
   815
        done
yann@508
   816
    fi
yann@508
   817
yann@1903
   818
    CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${pkgdir}.patched"
yann@1903
   819
    CT_DoExecLog DEBUG rm -f "${CT_SRC_DIR}/.${pkgdir}.patching"
yann@1126
   820
yann@1761
   821
    CT_Popd
yann@63
   822
}
yann@63
   823
yann@182
   824
# Two wrappers to call config.(guess|sub) either from CT_TOP_DIR or CT_LIB_DIR.
yann@182
   825
# Those from CT_TOP_DIR, if they exist, will be be more recent than those from CT_LIB_DIR.
yann@182
   826
CT_DoConfigGuess() {
yann@1101
   827
    if [ -x "${CT_TOP_DIR}/scripts/config.guess" ]; then
yann@1101
   828
        "${CT_TOP_DIR}/scripts/config.guess"
yann@182
   829
    else
yann@1101
   830
        "${CT_LIB_DIR}/scripts/config.guess"
yann@182
   831
    fi
yann@182
   832
}
yann@182
   833
yann@182
   834
CT_DoConfigSub() {
yann@1101
   835
    if [ -x "${CT_TOP_DIR}/scripts/config.sub" ]; then
yann@1101
   836
        "${CT_TOP_DIR}/scripts/config.sub" "$@"
yann@182
   837
    else
yann@1101
   838
        "${CT_LIB_DIR}/scripts/config.sub" "$@"
yann@182
   839
    fi
yann@182
   840
}
yann@182
   841
yann@335
   842
# Compute the target tuple from what is provided by the user
yann@335
   843
# Usage: CT_DoBuildTargetTuple
yann@63
   844
# In fact this function takes the environment variables to build the target
yann@335
   845
# tuple. It is needed both by the normal build sequence, as well as the
yann@63
   846
# sample saving sequence.
yann@335
   847
CT_DoBuildTargetTuple() {
yann@383
   848
    # Set the endianness suffix, and the default endianness gcc option
yann@63
   849
    case "${CT_ARCH_BE},${CT_ARCH_LE}" in
yann@383
   850
        y,) target_endian_eb=eb
yann@383
   851
            target_endian_el=
yann@391
   852
            CT_ARCH_ENDIAN_CFLAG="-mbig-endian"
yann@527
   853
            CT_ARCH_ENDIAN_LDFLAG="-EB"
yann@383
   854
            ;;
yann@383
   855
        ,y) target_endian_eb=
yann@383
   856
            target_endian_el=el
yann@391
   857
            CT_ARCH_ENDIAN_CFLAG="-mlittle-endian"
yann@527
   858
            CT_ARCH_ENDIAN_LDFLAG="-EL"
yann@383
   859
            ;;
yann@63
   860
    esac
yann@383
   861
yann@965
   862
    # Build the default architecture tuple part
yann@965
   863
    CT_TARGET_ARCH="${CT_ARCH}"
yann@965
   864
yann@383
   865
    # Set defaults for the system part of the tuple. Can be overriden
yann@383
   866
    # by architecture-specific values.
yann@383
   867
    case "${CT_LIBC}" in
yann@787
   868
        *glibc) CT_TARGET_SYS=gnu;;
yann@383
   869
        uClibc) CT_TARGET_SYS=uclibc;;
yann@1591
   870
        *)      CT_TARGET_SYS=elf;;
yann@63
   871
    esac
yann@383
   872
yann@391
   873
    # Set the default values for ARCH, ABI, CPU, TUNE, FPU and FLOAT
yann@497
   874
    unset CT_ARCH_ARCH_CFLAG CT_ARCH_ABI_CFLAG CT_ARCH_CPU_CFLAG CT_ARCH_TUNE_CFLAG CT_ARCH_FPU_CFLAG CT_ARCH_FLOAT_CFLAG
yann@497
   875
    unset CT_ARCH_WITH_ARCH CT_ARCH_WITH_ABI CT_ARCH_WITH_CPU CT_ARCH_WITH_TUNE CT_ARCH_WITH_FPU CT_ARCH_WITH_FLOAT
yann@391
   876
    [ "${CT_ARCH_ARCH}"     ] && { CT_ARCH_ARCH_CFLAG="-march=${CT_ARCH_ARCH}";  CT_ARCH_WITH_ARCH="--with-arch=${CT_ARCH_ARCH}"; }
yann@391
   877
    [ "${CT_ARCH_ABI}"      ] && { CT_ARCH_ABI_CFLAG="-mabi=${CT_ARCH_ABI}";     CT_ARCH_WITH_ABI="--with-abi=${CT_ARCH_ABI}";    }
yann@391
   878
    [ "${CT_ARCH_CPU}"      ] && { CT_ARCH_CPU_CFLAG="-mcpu=${CT_ARCH_CPU}";     CT_ARCH_WITH_CPU="--with-cpu=${CT_ARCH_CPU}";    }
yann@405
   879
    [ "${CT_ARCH_TUNE}"     ] && { CT_ARCH_TUNE_CFLAG="-mtune=${CT_ARCH_TUNE}";  CT_ARCH_WITH_TUNE="--with-tune=${CT_ARCH_TUNE}"; }
yann@391
   880
    [ "${CT_ARCH_FPU}"      ] && { CT_ARCH_FPU_CFLAG="-mfpu=${CT_ARCH_FPU}";     CT_ARCH_WITH_FPU="--with-fpu=${CT_ARCH_FPU}";    }
yann@412
   881
    [ "${CT_ARCH_FLOAT_SW}" ] && { CT_ARCH_FLOAT_CFLAG="-msoft-float";           CT_ARCH_WITH_FLOAT="--with-float=soft";          }
yann@391
   882
yann@965
   883
    # Build the default kernel tuple part
yann@965
   884
    CT_TARGET_KERNEL="${CT_KERNEL}"
yann@964
   885
yann@965
   886
    # Overide the default values with the components specific settings
yann@964
   887
    CT_DoArchTupleValues
yann@965
   888
    CT_DoKernelTupleValues
yann@383
   889
yann@391
   890
    # Finish the target tuple construction
bartvdrmeulen@1896
   891
    CT_TARGET="${CT_TARGET_ARCH}"
bartvdrmeulen@1896
   892
    CT_TARGET="${CT_TARGET}${CT_TARGET_VENDOR:+-${CT_TARGET_VENDOR}}"
bartvdrmeulen@1896
   893
    CT_TARGET="${CT_TARGET}${CT_TARGET_KERNEL:+-${CT_TARGET_KERNEL}}"
bartvdrmeulen@1896
   894
    CT_TARGET="${CT_TARGET}${CT_TARGET_SYS:+-${CT_TARGET_SYS}}"
yann@1094
   895
yann@1094
   896
    # Sanity checks
yann@1094
   897
    __sed_alias=""
yann@1094
   898
    if [ -n "${CT_TARGET_ALIAS_SED_EXPR}" ]; then
yann@1094
   899
        __sed_alias=$(echo "${CT_TARGET}" |sed -r -e "${CT_TARGET_ALIAS_SED_EXPR}")
yann@1094
   900
    fi
yann@1094
   901
    case ":${CT_TARGET_VENDOR}:${CT_TARGET_ALIAS}:${__sed_alias}:" in
yann@1094
   902
      :*" "*:*:*:) CT_Abort "Don't use spaces in the vendor string, it breaks things.";;
yann@1094
   903
      :*"-"*:*:*:) CT_Abort "Don't use dashes in the vendor string, it breaks things.";;
yann@1094
   904
      :*:*" "*:*:) CT_Abort "Don't use spaces in the target alias, it breaks things.";;
yann@1094
   905
      :*:*:*" "*:) CT_Abort "Don't use spaces in the target sed transform, it breaks things.";;
yann@1094
   906
    esac
yann@1094
   907
yann@1094
   908
    # Canonicalise it
yann@1094
   909
    CT_TARGET=$(CT_DoConfigSub "${CT_TARGET}")
yann@391
   910
    # Prepare the target CFLAGS
yann@767
   911
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ENDIAN_CFLAG}"
yann@527
   912
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ARCH_CFLAG}"
yann@397
   913
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ABI_CFLAG}"
yann@397
   914
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_CPU_CFLAG}"
yann@397
   915
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_TUNE_CFLAG}"
yann@397
   916
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FPU_CFLAG}"
yann@397
   917
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FLOAT_CFLAG}"
yann@527
   918
yann@527
   919
    # Now on for the target LDFLAGS
yann@767
   920
    CT_ARCH_TARGET_LDFLAGS="${CT_ARCH_TARGET_LDFLAGS} ${CT_ARCH_ENDIAN_LDFLAG}"
yann@63
   921
}
yann@121
   922
yann@121
   923
# This function does pause the build until the user strikes "Return"
yann@121
   924
# Usage: CT_DoPause [optional_message]
yann@121
   925
CT_DoPause() {
yann@121
   926
    local foo
yann@121
   927
    local message="${1:-Pausing for your pleasure}"
yann@121
   928
    CT_DoLog INFO "${message}"
yann@523
   929
    read -p "Press 'Enter' to continue, or Ctrl-C to stop..." foo >&6
yann@121
   930
    return 0
yann@121
   931
}
yann@121
   932
yann@1907
   933
# This function creates a tarball of the specified directory, but
yann@1907
   934
# only if it exists
yann@1907
   935
# Usage: CT_DoTarballIfExists <dir> <tarball_basename> [extra_tar_options [...]]
yann@1907
   936
CT_DoTarballIfExists() {
yann@1907
   937
    local dir="$1"
yann@1907
   938
    local tarball="$2"
yann@1907
   939
    shift 2
yann@1907
   940
    local -a extra_tar_opts=( "$@" )
yann@1908
   941
    local -a compress
yann@1907
   942
yann@1907
   943
    case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
yann@1908
   944
        y)  compress=( gzip -c -3 - ); tar_ext=.gz;;
yann@1908
   945
        *)  compress=( cat - );        tar_ext=;;
yann@1907
   946
    esac
yann@1907
   947
yann@1907
   948
    if [ -d "${dir}" ]; then
yann@1907
   949
        CT_DoLog DEBUG "  Saving '${dir}'"
yann@1908
   950
        { tar c -C "${dir}" -v -f - "${extra_tar_opts[@]}" .    \
yann@1908
   951
          |"${compress[@]}" >"${tarball}.tar${tar_ext}"         ;
yann@1908
   952
        } 2>&1 |sed -r -e 's/^/    /;' |CT_DoLog DEBUG
yann@1907
   953
    else
yann@1907
   954
        CT_DoLog DEBUG "  Not saving '${dir}': does not exist"
yann@1907
   955
    fi
yann@1907
   956
}
yann@1907
   957
yann@1907
   958
# This function extracts a tarball to the specified directory, but
yann@1907
   959
# only if the tarball exists
yann@1907
   960
# Usage: CT_DoTarballIfExists <tarball_basename> <dir> [extra_tar_options [...]]
yann@1907
   961
CT_DoExtractTarballIfExists() {
yann@1907
   962
    local tarball="$1"
yann@1907
   963
    local dir="$2"
yann@1907
   964
    shift 2
yann@1907
   965
    local -a extra_tar_opts=( "$@" )
yann@1908
   966
    local -a uncompress
yann@1907
   967
yann@1907
   968
    case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
yann@1908
   969
        y)  uncompress=( gzip -c -d ); tar_ext=.gz;;
yann@1908
   970
        *)  uncompress=( cat );        tar_ext=;;
yann@1907
   971
    esac
yann@1907
   972
yann@1907
   973
    if [ -f "${tarball}.tar${tar_ext}" ]; then
yann@1907
   974
        CT_DoLog DEBUG "  Restoring '${dir}'"
yann@1907
   975
        CT_DoForceRmdir "${dir}"
yann@1907
   976
        CT_DoExecLog DEBUG mkdir -p "${dir}"
yann@1908
   977
        { "${uncompress[@]}" "${tarball}.tar${tar_ext}"     \
yann@1908
   978
          |tar x -C "${dir}" -v -f - "${extra_tar_opts[@]}" ;
yann@1908
   979
        } 2>&1 |sed -r -e 's/^/    /;' |CT_DoLog DEBUG
yann@1907
   980
    else
yann@1907
   981
        CT_DoLog DEBUG "  Not restoring '${dir}': does not exist"
yann@1907
   982
    fi
yann@1907
   983
}
yann@1907
   984
yann@121
   985
# This function saves the state of the toolchain to be able to restart
yann@121
   986
# at any one point
yann@121
   987
# Usage: CT_DoSaveState <next_step_name>
yann@121
   988
CT_DoSaveState() {
yann@121
   989
	[ "${CT_DEBUG_CT_SAVE_STEPS}" = "y" ] || return 0
yann@121
   990
    local state_name="$1"
yann@121
   991
    local state_dir="${CT_STATE_DIR}/${state_name}"
yann@121
   992
yann@1266
   993
    # Log this to the log level required by the user
yann@1266
   994
    CT_DoLog ${CT_LOG_LEVEL_MAX} "Saving state to restart at step '${state_name}'..."
yann@1134
   995
yann@121
   996
    rm -rf "${state_dir}"
yann@121
   997
    mkdir -p "${state_dir}"
yann@121
   998
yann@121
   999
    CT_DoLog DEBUG "  Saving environment and aliases"
yann@738
  1000
    # We must omit shell functions, and some specific bash variables
yann@738
  1001
    # that break when restoring the environment, later. We could do
yann@1299
  1002
    # all the processing in the awk script, but a sed is easier...
yann@1299
  1003
    set |awk '
yann@1017
  1004
              BEGIN { _p = 1; }
yann@1017
  1005
              $0~/^[^ ]+ \(\)/ { _p = 0; }
yann@1017
  1006
              _p == 1
yann@1017
  1007
              $0 == "}" { _p = 1; }
yann@1017
  1008
              ' |sed -r -e '/^BASH_(ARGC|ARGV|LINENO|SOURCE|VERSINFO)=/d;
yann@738
  1009
                           /^(UID|EUID)=/d;
yann@738
  1010
                           /^(FUNCNAME|GROUPS|PPID|SHELLOPTS)=/d;' >"${state_dir}/env.sh"
yann@121
  1011
yann@1894
  1012
    if [ "${CT_COMPLIBS_SHARED}" != "y" ]; then
yann@1907
  1013
        # If complibs are not shared, then COMPLIBS_DIR == PREFIX_DIR,
yann@1907
  1014
        # so do not save.
yann@1907
  1015
        CT_DoTarballIfExists "${CT_COMPLIBS_DIR}" "${state_dir}/complibs_dir"
yann@1894
  1016
    fi
yann@1907
  1017
    CT_DoTarballIfExists "${CT_CONFIG_DIR}" "${state_dir}/config_dir"
yann@1907
  1018
    CT_DoTarballIfExists "${CT_CC_CORE_STATIC_PREFIX_DIR}" "${state_dir}/cc_core_static_prefix_dir"
yann@1907
  1019
    CT_DoTarballIfExists "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${state_dir}/cc_core_shared_prefix_dir"
yann@1907
  1020
    CT_DoTarballIfExists "${CT_PREFIX_DIR}" "${state_dir}/prefix_dir" --exclude '*.log'
yann@121
  1021
yann@121
  1022
    if [ "${CT_LOG_TO_FILE}" = "y" ]; then
yann@121
  1023
        CT_DoLog DEBUG "  Saving log file"
yann@121
  1024
        exec >/dev/null
yann@121
  1025
        case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
yann@121
  1026
            y)  gzip -3 -c "${CT_LOG_FILE}"  >"${state_dir}/log.gz";;
yann@121
  1027
            *)  cat "${CT_LOG_FILE}" >"${state_dir}/log";;
yann@121
  1028
        esac
yann@121
  1029
        exec >>"${CT_LOG_FILE}"
yann@121
  1030
    fi
yann@121
  1031
}
yann@121
  1032
yann@136
  1033
# This function restores a previously saved state
yann@121
  1034
# Usage: CT_DoLoadState <state_name>
yann@121
  1035
CT_DoLoadState(){
yann@121
  1036
    local state_name="$1"
yann@121
  1037
    local state_dir="${CT_STATE_DIR}/${state_name}"
yann@135
  1038
    local old_RESTART="${CT_RESTART}"
yann@135
  1039
    local old_STOP="${CT_STOP}"
yann@121
  1040
yann@523
  1041
    CT_TestOrAbort "The previous build did not reach the point where it could be restarted at '${CT_RESTART}'" -d "${state_dir}"
yann@141
  1042
yann@121
  1043
    # We need to do something special with the log file!
yann@121
  1044
    if [ "${CT_LOG_TO_FILE}" = "y" ]; then
yann@121
  1045
        exec >"${state_dir}/tail.log"
yann@121
  1046
    fi
yann@1266
  1047
yann@1266
  1048
    # Log this to the log level required by the user
yann@1266
  1049
    CT_DoLog ${CT_LOG_LEVEL_MAX} "Restoring state at step '${state_name}', as requested."
yann@121
  1050
yann@1907
  1051
    CT_DoExtractTarballIfExists "${state_dir}/prefix_dir" "${CT_PREFIX_DIR}"
yann@1907
  1052
    CT_DoExtractTarballIfExists "${state_dir}/cc_core_shared_prefix_dir" "${CT_CC_CORE_SHARED_PREFIX_DIR}"
yann@1907
  1053
    CT_DoExtractTarballIfExists "${state_dir}/cc_core_static_prefix_dir" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
yann@1907
  1054
    CT_DoExtractTarballIfExists "${state_dir}/config_dir" "${CT_CONFIG_DIR}"
yann@1894
  1055
    if [ "${CT_COMPLIBS_SHARED}" != "y" ]; then
yann@1907
  1056
        # If complibs are not shared, then COMPLIBS_DIR == PREFIX_DIR,
yann@1907
  1057
        # so do not restore.
yann@1907
  1058
        CT_DoExtractTarballIfExists "${state_dir}/complibs_dir" "${CT_COMPLIBS_DIR}"
yann@1894
  1059
    fi
yann@1894
  1060
yann@121
  1061
    # Restore the environment, discarding any error message
yann@121
  1062
    # (for example, read-only bash internals)
yann@121
  1063
    CT_DoLog DEBUG "  Restoring environment"
yann@121
  1064
    . "${state_dir}/env.sh" >/dev/null 2>&1 || true
yann@121
  1065
yann@135
  1066
    # Restore the new RESTART and STOP steps
yann@135
  1067
    CT_RESTART="${old_RESTART}"
yann@135
  1068
    CT_STOP="${old_STOP}"
yann@135
  1069
    unset old_stop old_restart
yann@135
  1070
yann@121
  1071
    if [ "${CT_LOG_TO_FILE}" = "y" ]; then
yann@121
  1072
        CT_DoLog DEBUG "  Restoring log file"
yann@121
  1073
        exec >/dev/null
yann@121
  1074
        case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
yann@121
  1075
            y)  zcat "${state_dir}/log.gz" >"${CT_LOG_FILE}";;
yann@121
  1076
            *)  cat "${state_dir}/log" >"${CT_LOG_FILE}";;
yann@121
  1077
        esac
yann@121
  1078
        cat "${state_dir}/tail.log" >>"${CT_LOG_FILE}"
yann@121
  1079
        exec >>"${CT_LOG_FILE}"
yann@121
  1080
        rm -f "${state_dir}/tail.log"
yann@121
  1081
    fi
yann@121
  1082
}