1#!/usr/bin/env bash
2
3###############################################################################
4#
5# Copyright (C) 2009-2013 Nintendo.  All rights reserved.
6#
7# These coded instructions, statements, and computer programs contain
8# proprietary information of Nintendo of America Inc. and/or Nintendo
9# Company Ltd., and are protected by Federal copyright law.  They may
10# not be disclosed to third parties or copied or duplicated in any form,
11# in whole or in part, without the prior written consent of Nintendo.
12#
13###############################################################################
14
15# use for debugging and remove this and lines above
16#!/bin/sh -vx
17
18
19if [ "$USE_CAFEX" == "1" ]
20then
21    # Set IFS to something that will not be in the args, so that BASH will pass the entire un-parsed string to CafeX
22    saveIFS="$IFS"
23    IFS=$'\n'
24    echo "Using CafeControl"
25    cafex.exe run $@
26    rval=$?
27    IFS="$saveIFS"
28    exit $rval
29fi
30
31export PLATFORM=cafe
32
33# DO NOT CHANGE CAFE_ROOT to a DOS path, if you need a DOS path use CAFE_ROOT_DOS
34# CAFE_ROOT_DOS=`cygpath -m "$CAFE_ROOT"`
35
36QUIET=-q
37CAFESTOP_ONLY_IF_FSEMUL=0 # by default, always call cafestop
38PPC_OS_FLAGS=0
39PPC_APP_FLAGS=0
40ALLOW_DISCRUN_IN_SOFTLAUNCH=0
41BOOTRUN_ELF_OPT=
42BOOTRUN_ELF_VALUE=
43ELF_NEST_OPT=
44ELF_NEST_VALUE=
45SOFT_LAUNCH_CAFE_ELF=
46PCFS_SYNC_DATE=
47MCP_LAUNCH_HINT=
48MCP_INFO_OPTION=
49DEBUGGER=${DEBUGGER:-none}
50CONSOLE=${CAFE_CONSOLE:-cattoucan}
51CAFE_DEBUG_PORT=${CAFE_DEBUG_PORT:-toucan}
52DEBUG_ELF_FILE=${DEBUG_ELF_FILE:-}
53CAFERUN_OPTION_SOFT_RESTART=0
54CAFERUN_OPTION_FAST_RELAUNCH=0
55CAFERUN_OPTION_MLC_EMU_LAUNCH=0
56CAFERUN_OPTION_MLC_EMU_TITLEID=0xFFFFFFFFFFFFFFFF
57CAFERUN_OS_MAJOR_VERSION_LO=`grep "00050010" "${CAFE_ROOT}/system/include/sdk_ver.h" | sed 's/.*00050010//'`
58CAFERUN_OS_MAJOR_VERSION=${CAFERUN_OS_MAJOR_VERSION_LO:6:2}
59CAFERUN_COLDBOOT_OS_VERSION=0x${CAFERUN_COLDBOOT_OS_VERSION:-00050010100040${CAFERUN_OS_MAJOR_VERSION}}
60export CAFERUN_COLDBOOT_OS_VERSION
61HEARTBEAT_DISABLE=0
62PCFS_DIR_MAPPING=( )
63MAPDIR_MLC=
64MAPDIR_SLC=
65MAPDIR_CODE=
66MAPDIR_META=
67MAPDIR_CONTENT=
68MAPDIR_SAVE=
69PCFS_LOG_TIMESTAMP=
70PCFS_SRV_LOG_OUTPUT=
71RUN_FROM_HDD_BANK=
72EJECT_STATE=
73BRIDGE_PARAMETERS=
74BRIDGE_PARAMETERS_WITH_E=
75PCFSSERVER_PARAMETERS=
76PCFS_OVER_SATA_PORT=
77PCFS_HEADLESS_EMUL=${PCFS_HEADLESS_EMUL:--pcfsenable}
78PREPHDD_STAT=
79DISC_EMU_TID=
80CAFE_WUMAD=
81WUMAD_WORK_DIR=
82SYSTEM_MODE="" # "dev", or "test"
83export RPL_DIRS
84export RPL_FILES
85
86USE_EXI_AS_DEBUG_CHANNEL=${USE_EXI_AS_DEBUG_CHANNEL:-0}
87
88export CAFERUN_INS=${CAFERUN_INS:-0}
89
90if [ -f "$MION_BRIDGE_TOOLS/PCFS/PCFSServer.exe" ]
91then
92    PCFSSERVER_EXE="$MION_BRIDGE_TOOLS/PCFS/PCFSServer.exe"
93else
94    PCFSSERVER_EXE="PCFSServer.exe"
95fi
96
97
98export CAFERUN_OPTION_NO_DATA_SYNC=${CAFERUN_OPTION_NO_DATA_SYNC:-0}
99
100if [ "$(basename "$0")" != "cafeon" -a "$CAFE_BOOT_MODE" == "NAND" ]
101then
102    CAFERUN_OPTION_SOFT_LAUNCH=1
103else
104    CAFERUN_OPTION_SOFT_LAUNCH=0
105fi
106
107# these two are set by hostcheckversion
108CAFERUN_HOSTBRIDGE_VERSION=unknown
109CAFERUN_FW_VERSION=unknown
110
111
112# tell debugger to not stop in init code (by default)
113CAFE_DEBUG_INIT=${CAFE_DEBUG_INIT:-0}
114CAFE_DEBUG_PREINIT=${CAFE_DEBUG_PREINIT:-0}
115CAFE_DEBUG_DONTSTOP=${CAFE_DEBUG_DONTSTOP:-0}
116CAFE_LAUNCH_DEBUG=${CAFE_LAUNCH_DEBUG:-1}
117CAFE_SYSLOG_LEVEL=${CAFE_SYSLOG_LEVEL:-1}    # default to print warnings
118export CAFE_RUN_FORCERESTART=${CAFE_RUN_FORCERESTART:-0}
119DEBUG_PROC_ID=${DEBUG_PROC_ID:-15}
120DEBUG_FLAGS=0
121if [ $CAFE_DEBUG_INIT != 0 ]
122then
123    DEBUG_FLAGS=16
124fi
125# no initial breakpoint
126if [ $CAFE_DEBUG_DONTSTOP != 0 ]
127then
128    DEBUG_FLAGS=32
129fi
130# debugger can only set one initial breakpoint
131if [ $CAFE_DEBUG_PREINIT != 0 ]
132then
133    DEBUG_FLAGS=64
134fi
135if [ $USE_EXI_AS_DEBUG_CHANNEL -eq 0 ]
136then
137    DEBUG_FLAGS=$(($DEBUG_FLAGS | 256))
138fi
139CATOUTPUT=0
140CMDOUTPUT=0
141case "$CONSOLE" in
142  sdio)
143    CONSOLE=toucan
144    ;;
145  cattoucan)
146    CONSOLE=toucan
147    DEBUGGER=cattoucan
148    CATOUTPUT=1
149    ;;
150  cmdtoucan)
151    CONSOLE=toucan
152    DEBUGGER=cattoucan
153    CMDOUTPUT=1
154    ;;
155esac
156
157# when running autotest don't enable the "cat function"
158if [ "$CAFE_AUTOTEST" = "1" ]
159then
160    DEBUGGER=none
161fi
162
163###############################################################################
164# print usage help message
165###############################################################################
166usage ()
167{
168    cat <<EOF
169    Usage: $(basename $0) [options] <app>.rpx "[arg1]" "[arg2]" ... "[argN]"
170    
171    options:
172      -a a,b... : arguments (comma delimited)
173      -b        : use DEBUG OS version
174      -u        : use FDEBUG OS version
175      -l <path> : user RPL directory or file to gather for RPX
176
177      -d multi  : launch multi (GHS UI) on elf file
178  	  -L        : run legacy application independent of xml versions
179      -i        : stop debugger in the initialization code
180      -j        : stop debugger in the pre-initialization code
181      -R        : do not stop in debugger until OSDebug or OSDebugStr call
182      -p <n>    : indicate process to debug (defaults to game process)
183      -g <n>    : 32-bit flag to pass along to PPC COS
184      -w <n>    : 32-bit flag to pass along to PPC COS.
185      -k <file> : path to elf file for debugger
186      -x        : Enable AHCI/SATA disk access. Deprecated - will soon become default.
187      -r        : restart last application
188      -s        : use soft launch to run
189      -F		: force restart (stop and then boot hw)
190      -t <tid>  : title launch from mlc emulation (tid is hex that starts with 0x) 
191      -e <op>   : pass op through to FSEmul or MCP (e.g.: -e sata -> FSEmul -sata)
192
193      -v <n>    : set COS verbose level (0=off 7 == MAX)
194      -q        : do not display OS warning or informational messages.
195      -z        : suppress mirroring the data to the session data directory.
196
197      -h        : (help) display options
198
199EOF
200
201}
202
203###############################################################################
204# launch to serial or debugger
205###############################################################################
206connect_serial_or_debugger()
207{
208    case ${DEBUGGER} in
209      multi)
210        ;;
211      gdb|gdbtui)
212        ;;
213      cattoucan)
214        set +e
215        cattoucan $QUIET -p localhost:$SESSION_DEBUG_OUT_PORT
216        exit $?
217        ;;
218      none)
219        # if console is not toucan
220        # set CAFE_DEBUG_PORT=toucan
221        if [ ${CONSOLE} != "toucan" ]
222        then
223            CAFE_DEBUG_PORT=toucan
224        fi
225        return 0;
226        ;;
227      *)
228        echo "$(basename "$0") failed: ${DEBUGGER} unsupported debugger." >&2
229        exit 20
230        ;;
231    esac
232
233    if [ "${CAFE_DEBUG_PORT}" = "toucan" ]
234    then
235        PORT=localhost:$SESSION_DEBUG_OUT_PORT
236    else
237        echo "$(basename "$0") failed: Unknown debugger port '${CAFE_DEBUG_PORT}'"
238        exit 21
239    fi
240    if [ ${DEBUGGER} = "multi" ]
241    then
242        MULTIELF=""
243        if [ ! -z "$DEBUG_ELF_FILE" ]
244        then
245            MULTIELF=`cygpath -m "$DEBUG_ELF_FILE"`
246        fi
247        set +e
248        cattoucan $QUIET -p $PORT
249        CATTOUCAN_STATUS=$?
250        set -e
251        if [ $USE_EXI_AS_DEBUG_CHANNEL -eq 1 ]
252        then
253            MULTI_CONNECT=${MULTI_CONNECT:--connect=cafeserv -iphost $BRIDGE_CURRENT_IP_ADDRESS -ipport 7977 -console_iphost localhost -console_ipport $SESSION_DEBUG_OUT_PORT -auto_first}
254        else
255            MULTI_CONNECT=${MULTI_CONNECT:--connect=cafeserv -iphost localhost -ipport $SESSION_DEBUG_CONTROL_PORT -console_ipport $SESSION_DEBUG_OUT_PORT -auto_first}
256        fi
257        if [ $CATTOUCAN_STATUS = 42 ]
258        then
259            if [ $CAFE_LAUNCH_DEBUG = 1 ]
260            then
261                nohup ${GHS_ROOT}/multi.exe -cmd prepare_target "${MULTI_CONNECT}" ${CAFE_MULTI_INIT} "$MULTIELF" < /dev/null &> /dev/null &
262            else
263                echo "Ready to connect from multi"
264                echo ${GHS_ROOT}/multi.exe -cmd prepare_target "${MULTI_CONNECT}" ${CAFE_MULTI_INIT} "$MULTIELF"
265            fi
266            if [ $CMDOUTPUT = 1 ]
267            then
268                cattoucan $QUIET -p $PORT
269            fi
270        fi
271    else
272        echo > .caferun_gdbcmds
273        if [ ! -z "$DEBUG_ELF_FILE" ]
274        then
275            echo "file \"$DEBUG_ELF_FILE\"" >> .caferun_gdbcmds
276        fi
277        echo "set arch powerpc:broadway" >> .caferun_gdbcmds
278        echo "target remote localhost:$SESSION_DEBUG_CONTROL_PORT" >> .caferun_gdbcmds
279        set +e
280        cattoucan $QUIET -p $PORT
281        CATTOUCAN_STATUS=$?
282        set -e
283        if [ $CATTOUCAN_STATUS = 42 ]
284        then
285            if [ $CAFE_LAUNCH_DEBUG = 1 ]
286            then
287                powerpc-cos-eabi-${DEBUGGER} -x .caferun_gdbcmds
288            else
289                echo "Ready to connect from gdb"
290                echo powerpc-cos-eabi-${DEBUGGER} -x .caferun_gdbcmds
291            fi
292        fi
293    fi
294}
295
296###############################################################################
297# args_to_bar_sep_list
298#
299# converts an argument list into bar separated one
300# spaces inside of quoted arguments are supported
301#  e.g.  1 2 3 "a b c" 4 5 6 -->  1|2|3|a b c|4|5
302# idea is to then convert the bars to either commas or something else
303# when needed using something like sed 's?|?,?'
304###############################################################################
305args_to_bar_sep_list()
306{
307    R=$1
308    shift
309
310    while [ $# -gt 0 ]
311    do
312        R=$R'|'$1
313        shift
314    done
315}
316
317###############################################################################
318# check_title_id
319#
320#   copy default xml if destination xml doesn't exist
321#   otherwise, compare title id.  exit or copy default if mismatch
322###############################################################################
323check_title_id()
324{
325    local FILE_DEST="$1"
326    local FILE_DEFAULT="$2"
327    local FILE_APP="$3"
328
329    if [ ! -f "$FILE_DEST" ]
330    then
331        echo "$(basename "$0"): Copying default config file to $FILE_DEST"
332        if [ ! -f "$FILE_DEFAULT" ]
333        then
334            echo "$(basename "$0") failed: Cannot find default config file $FILE_DEFAULT"
335            exit 12
336        fi
337        install -Dp "$FILE_DEFAULT" "$FILE_DEST"
338    else
339        # extract version number of xml element in file of the form:
340        local TITLEID_DEST=`sed -n 's|.*<title_id .*>\([[:xdigit:]]*\)</title_id>|\1|p' "$FILE_DEST"`
341        local TITLEID_APP=`sed -n 's|.*<title_id .*>\([[:xdigit:]]*\)</title_id>|\1|p' "$FILE_APP"`
342
343        if [ -z "$TITLEID_DEST" -o -z "$TITLEID_APP" ]
344        then
345            echo "caferun failed: Cannot get title id"
346            exit 12
347        fi
348
349        if [ $TITLEID_DEST != $TITLEID_APP ]
350        then
351            echo "$(basename "$0"): Config file title id mismatch detected: $TITLEID_DEST vs. required $TITLEID_APP"
352            echo "         Copying default config file to $FILE_DEST"
353            if [ ! -f "$FILE_DEFAULT" ]
354            then
355                echo "$(basename "$0") failed: Cannot find default config file $FILE_DEFAULT"
356                exit 12
357            fi
358            install -Dp "$FILE_DEFAULT" "$FILE_DEST"
359        fi
360    fi
361}
362
363###############################################################################
364# check_xml_version
365#
366#   copy default xml if destination xml doesn't exist
367#   otherwise, compare version.  exit or copy default if mismatch
368###############################################################################
369check_xml_version()
370{
371    local FILE_DEST="$1"
372    local FILE_DEFAULT="$2"
373    local FILE_OPTION="$3"
374
375    if [ ! -f "$FILE_DEST" ]
376    then
377        echo "$(basename "$0"): Copying default config file to $FILE_DEST"
378        if [ ! -f "$FILE_DEFAULT" ]
379        then
380            echo "$(basename "$0") failed: Cannot find default config file $FILE_DEFAULT"
381            exit 12
382        fi
383        install -Dp "$FILE_DEFAULT" "$FILE_DEST"
384    else
385        # extract version number of xml element in file of the form:
386        local VER_DEFAULT=`sed -n 's|.*<version .*>\([0-9]*\)</version>|\1|p' "$FILE_DEFAULT"`
387        local VER_DEST=`sed -n 's|.*<version .*>\([0-9]*\)</version>|\1|p' "$FILE_DEST"`
388
389        if [ -z "$VER_DEST" -o -z "$VER_DEFAULT" ]
390        then
391            echo "caferun failed: Cannot get xml version numbers"
392            exit 12
393        fi
394
395        if [ "$IGNORE_VERSION" != "TRUE" ]
396		then
397            if [ $VER_DEST -ne $VER_DEFAULT ]
398            then
399                if [ "$FILE_OPTION" = "copy_default_if_mismatch" ]
400                then
401                    echo "$(basename "$0"): Config file version mismatch detected: $VER_DEST vs. required $VER_DEFAULT"
402                    echo "         Copying default config file to $FILE_DEST"
403                    if [ ! -f "$FILE_DEFAULT" ]
404                    then
405                        echo "$(basename "$0") failed: Cannot find default config file $FILE_DEFAULT"
406                        exit 12
407                    fi
408                    install -Dp "$FILE_DEFAULT" "$FILE_DEST"
409                else
410                    echo "$(basename "$0") failed: Please update or delete config file: $FILE_DEST"
411                    echo "                Version number mismatch: $VER_DEST vs. required $VER_DEFAULT"
412                    exit 10
413                fi
414            fi
415		fi
416    fi
417}
418
419###############################################################################
420# exit_if_specials
421#
422# check for special characters in arglist
423#  '?' : get used as spaces in connected words
424#  '<' : used as xml delimiters, used to find arglist
425#  '|' : used as spaces in connected words (in first part of cdoe)
426# - perhaps eventually we can auto-escape these.  For now, simply punt
427###############################################################################
428exit_if_specials()
429{
430    if [ -n "`echo "$@" | egrep '[?|<>+]'`" ]
431    then
432        echo "$(basename "$0") failed: Unable to parse special character (?+<>|) in arg list."
433        echo "                arglist: \"$@\" "
434        exit 11
435    fi
436}
437
438###############################################################################
439# update_arglist
440#
441# Updates argument list in user .xml file with program name and extra arguments
442# arguments are bar-delimited
443###############################################################################
444update_arglist()
445{
446    local FILE_DEST="$1"           # root directory
447    local CAFE_ELF="$2"            # program name of our program.elf
448    shift 2
449    local ARGLIST="$@"             # all the rest of the arguments
450
451    # now don't abort script when any command returns an error (non-zero value).
452    # (Legitimate Null strings being passed to sed/grep causing script to die
453    #   in unexpected locations)
454    set +e
455
456    # update the argc/argv string in user file with options passed in from user
457    # with extra arguments from the end (the shift and $* calls below)
458    #  - this code is pretty ugly, I'm sure somone (using IFS?) could clean it up alot
459
460    shift
461    exit_if_specials "$@"                   # exit if special characters found
462
463    args_to_bar_sep_list "$@"
464    local ARGS_TRAILING_WITH_BARS=$R        # arguments after the file name
465
466    # convert commas in the -a command to vertical bars, and append trailing values from user
467    if [ -z "${DASH_A_ARGS}" ]
468    then
469        ARGS_WITH_BARS="${ARGS_TRAILING_WITH_BARS}"
470    else
471        ARGS_WITH_BARS="`echo ${DASH_A_ARGS} | sed 's?,?|?g'`"
472        if [ "${ARGS_WITH_BARS}" == "" ]
473        then
474            ARGS_WITH_BARS=$DASH_A_ARGS
475        fi
476
477        if [ -n "${ARGS_TRAILING_WITH_BARS}" ]
478        then
479            ARGS_WITH_BARS="${ARGS_WITH_BARS}|${ARGS_TRAILING_WITH_BARS}"
480        fi
481    fi
482
483    # convert any remaining " to \"
484    local ARGS_WITH_BARS_NO_QUOTES="`echo $ARGS_WITH_BARS | sed 's?\"?\\\"?g'`"
485    if [ -z "$ARGS_WITH_BARS_NO_QUOTES" ]
486    then
487        ARGS_WITH_BARS_NO_QUOTES=$ARGS_WITH_BARS
488    fi
489
490    # third, construct the total argument list  (prog_name <|input_args> )
491    local TOTAL_ARGLIST="${CAFE_ELF##/*/}"
492    if [ -n "$ARGS_WITH_BARS_NO_QUOTES" ]
493    then
494        TOTAL_ARGLIST="$TOTAL_ARGLIST|$ARGS_WITH_BARS_NO_QUOTES"
495    fi
496
497    # (e.g. 'a b "1 2 3" c d' => "a b 1?2?3 c d"
498    local TOTAL_ARGLIST_WITH_QS=`echo ${TOTAL_ARGLIST} | sed -e 's+ +?+g' -e 's+|+ +g'`
499
500    #finally, push it back into the file
501    #  append extra args
502    #      <argstr ...>*</argstr> ==> <argstr ...>app.elf default_args input_args</argstr>
503    sed -i -e "s|\(<argstr.*>\)\(.*\)\(</argstr.*>\)|\1$TOTAL_ARGLIST_WITH_QS\3|" "$FILE_DEST"
504
505    set -e
506}
507
508###############################################################################
509# update_system_xml
510###############################################################################
511update_system_xml()
512{
513    local FILE_DEST="$1"
514    local CMD_FLAGS="$2"
515    local SYSTEM_MODE="$3"
516	local SYS_XML_MCP_LAUNCH_HINT="$4"
517	local STRINGS_REPLACED=0
518    local SYS_DEFAULT_XML="$CAFE_ROOT/system/bin/ghs/cafe/boot/system_default.xml"
519
520    check_xml_version "$FILE_DEST" "$SYS_DEFAULT_XML" "copy_default_if_mismatch"
521
522    # Set system mode, updating system.xml in emulated slc
523    local OLD_SYSTEM_MODE_NUM=`sed -n 's|.*<dev_mode.*>\(.*\)</dev_mode>.*|\1|p' "$FILE_DEST"`
524    local SYSTEM_MODE_NAME_TABLE[0]="PROD"
525    local SYSTEM_MODE_NAME_TABLE[1]="DEV"
526    local SYSTEM_MODE_NAME_TABLE[2]="TEST"
527    local SYSTEM_MODE_NAME_TABLE[3]="Unknown"
528
529    if [ ! "$OLD_SYSTEM_MODE_NUM" = "0" -a ! "$OLD_SYSTEM_MODE_NUM" = "1" -a ! "$OLD_SYSTEM_MODE_NUM" = "2" ]
530    then
531        OLD_SYSTEM_MODE_NUM=3 # Invalid value
532    fi
533
534    if [ "$SYSTEM_MODE" = "dev" ]
535    then
536        NEW_SYSTEM_MODE_NUM=1
537    elif [ "$SYSTEM_MODE" = "test" ]
538    then
539        NEW_SYSTEM_MODE_NUM=2
540    else
541        if [ "$SYSTEM_MODE" = "prod" ] # PROD mode does not work in PCFS boot mode
542        then
543            echo "$(basename "$0") Warning: Changing to PROD mode is not supported."
544            echo "                 Please specify '-M dev' or '-M test'."
545        elif [ ! "$SYSTEM_MODE" = "" ] # User specified something invalid through the option
546        then
547            echo "$(basename "$0") Warning: Invalid system mode is specified."
548        fi
549        if [ $OLD_SYSTEM_MODE_NUM -ne 3 ]
550        then
551            NEW_SYSTEM_MODE_NUM=$OLD_SYSTEM_MODE_NUM
552        else
553            NEW_SYSTEM_MODE_NUM=1
554            echo "$(basename "$0"): System mode is broken. Fixing it to DEV"
555        fi
556    fi
557
558    if [ "$CAFE_BOOT_MODE" == "PCFS" ]
559    then
560        if [ $NEW_SYSTEM_MODE_NUM -ne $OLD_SYSTEM_MODE_NUM ]
561        then
562            echo "$(basename "$0"): Changing system mode ${SYSTEM_MODE_NAME_TABLE[$OLD_SYSTEM_MODE_NUM]} to ${SYSTEM_MODE_NAME_TABLE[$NEW_SYSTEM_MODE_NUM]}"
563            sed -i -e "s|\(<dev_mode.*>\).*\(<.*>\)|\1${NEW_SYSTEM_MODE_NUM}\2|" "$FILE_DEST"
564        else
565            echo "$(basename "$0"): Current system mode is ${SYSTEM_MODE_NAME_TABLE[$NEW_SYSTEM_MODE_NUM]}"
566        fi
567    fi
568
569    if [ $CAFERUN_OPTION_MLC_EMU_LAUNCH -eq 1 ]
570    then
571        local MLC_EMU_TID_HI=$(printf %08x $(($CAFERUN_OPTION_MLC_EMU_TITLEID >> 32 & 0xFFFFFFFF)))
572        local MLC_EMU_TID_LO=$(printf %08x $(($CAFERUN_OPTION_MLC_EMU_TITLEID & 0xFFFFFFFF)))
573
574        if [ "$MLC_EMU_TID_HI" = "00050010" ]
575        then
576            local MLC_EMU_TITLE_DIR=$CAFE_MLC_DIR/sys/title/$MLC_EMU_TID_HI/$MLC_EMU_TID_LO
577        else
578            local MLC_EMU_TITLE_DIR=$CAFE_MLC_DIR/usr/title/$MLC_EMU_TID_HI/$MLC_EMU_TID_LO
579        fi
580
581        if [ -f "$MLC_EMU_TITLE_DIR/code/app.xml" ]
582        then
583            local MLC_EMU_OS_VERSION=`sed -n 's|.*<os_version .*>\(.*\)</os_version>|\1|p' "$MLC_EMU_TITLE_DIR/code/app.xml"`
584            CAFERUN_COLDBOOT_OS_VERSION=$(printf %016llx 0x$MLC_EMU_OS_VERSION)
585        else
586            # HDD mode does not require any app.xml
587            if [ "$DISC_EMU_TYPE" != "hdd" -a "$ALLOW_DISCRUN_IN_SOFTLAUNCH" == 0 ]
588            then
589                echo "$(basename "$0") failed: Cannot find title 0x$MLC_EMU_TID_HI$MLC_EMU_TID_LO on MLC emulation"
590                echo "                Please cafeinstall before using -t option"
591                exit 7
592            fi
593        fi
594
595        # insert system.default_title_id
596        sed -i -e "s|\(<default_title_id .*>\)\(.*\)\(</default_title_id.*>\)|\1${MLC_EMU_TID_HI}${MLC_EMU_TID_LO}\3|" "$FILE_DEST"
597    else
598        if [ -n "$APP_XML_FILE" ]
599        then
600            # get titleId from disc emulation's app.xml
601            DISC_EMU_TID=`sed -n 's|.*<title_id.*>\(.*\)</title_id>|\1|p' "$APP_XML_FILE"`
602
603            # insert system.default_title_id
604            sed -i -e "s|\(<default_title_id .*>\)\(.*\)\(</default_title_id.*>\)|\1${DISC_EMU_TID}\3|" "$FILE_DEST"
605        else
606            # Is it OK to not update default_title_id for HDD mode?
607            if [ "$DISC_EMU_TYPE" == "hdd" -a -z "$CAFE_WUMAD" ]
608            then
609                echo ""
610                echo "-------"
611                echo "$(basename "$0") WARNING: Title ID is not specified."
612                echo "       Use -t option to specify Title ID of application on HDD."
613                echo "       Title ID of previously launched app will be used at this time,"
614                echo "       but launch may fail if it was different from that of application on HDD."
615                echo "-------"
616                echo ""
617            fi
618        fi
619    fi
620
621    # get app_type from disc emulation's app.xml
622    if [ -n "$APP_XML_FILE" ]
623    then
624        local DISC_EMU_APP_TYPE=`sed -n 's|.*<app_type.*>\(.*\)</app_type>|\1|p' "$APP_XML_FILE"`
625        # insert system.default_app_type
626        sed -i -e "s|\(<default_app_type .*>\)\(.*\)\(</default_app_type.*>\)|\1${DISC_EMU_APP_TYPE}\3|" "$FILE_DEST"
627    fi
628
629    if [ $CAFERUN_OPTION_SOFT_RESTART -eq 0 ]
630    then
631        # insert OSFlags between <cmdFlags.> and </cmdFlags.> xml tags
632        sed -i -e "s|\(<cmdFlags.*>\).*\(<.*>\)|\1${CMD_FLAGS}\2|" "$FILE_DEST"
633    fi
634
635    # insert default os version, which must be same as os_version of cold boot application's app.xml
636    sed -i -e "s|\(<default_os_id .*>\).*\(<.*>\)|\1${CAFERUN_COLDBOOT_OS_VERSION}\2|" "$FILE_DEST"
637
638
639	if [ ! -z "$SYS_XML_MCP_LAUNCH_HINT" ]
640	then
641	    # first try to replace the launch hint that's already there
642		set +e
643		STRINGS_REPLACED=$(grep -c default_device_type "$FILE_DEST")
644		set -e
645        if [ $STRINGS_REPLACED -eq 0 ]
646		then
647            # insert launch hint right before the closing of the file
648			sed -i -e "s|\(</system>\)|  \<default_device_type type=\"string\" length=\"16\"\>${SYS_XML_MCP_LAUNCH_HINT}\<\/default_device_type\>\n&|" "$FILE_DEST"
649		else
650			# replace launch string with new value
651            sed -i -e "s|\(<default_device_type .*>\).*\(<.*>\)|\1${SYS_XML_MCP_LAUNCH_HINT}\2|" "$FILE_DEST"
652		fi
653	else
654  	    # no hint - remove any that may be there
655        sed -i -e "s|\(<default_device_type .*>\).*\(<.*>\)|\1\2|" "$FILE_DEST"
656	fi
657
658}
659
660###############################################################################
661# set_system_xml_cos_flags
662###############################################################################
663set_system_xml_cos_flags()
664{
665    # must be called with out errors causing exit
666    # as part of the NAND reboot
667    local ERROR=0
668    local CMD_FLAGS=$1
669    local FILE_DEST="$CAFE_SLC_DIR/sys/config/system.xml"
670
671    # insert OSFlags between <cmdFlags.> and </cmdFlags.> xml tags
672    sed -i -e "s|\(<cmdFlags.*>\).*\(<.*>\)|\1${CMD_FLAGS}\2|" "$FILE_DEST"
673    ERROR=$?
674    if [ $ERROR != 0 ]
675    then
676        echo "Setting OSFlags in system.xml - failed result = $ERROR"
677        return $ERROR
678    fi
679
680    devkitmsg "cos_flags $1" -v -p $SESSION_LAUNCH_CTRL_PORT
681    ERROR=$?
682    if [ $ERROR != 0 ]
683    then
684        echo "devkitmsg \"cos_flags $1\" - failed result = $ERROR"
685    fi
686    return $ERROR
687}
688
689###############################################################################
690# update_app_xml
691###############################################################################
692update_app_xml()
693{
694    local FILE_DEST="$1"
695    local APP_DEFAULT_XML="$CAFE_ROOT/system/bin/ghs/cafe/boot/app_default.xml"
696
697    check_xml_version "$FILE_DEST" "$APP_DEFAULT_XML"
698
699    # insert os version
700    sed -i -e "s|\(<os_version .*>\).*\(<.*>\)|\1${CAFERUN_COLDBOOT_OS_VERSION}\2|" "$FILE_DEST"
701}
702
703###############################################################################
704# update_cos_xml
705###############################################################################
706update_cos_xml()
707{
708    local FILE_DEST="$1"
709    local CMD_FLAGS="$2"
710    local COS_DEFAULT_XML="$CAFE_ROOT/system/bin/ghs/cafe/boot/cos_default.xml"
711
712    check_xml_version "$FILE_DEST" "$COS_DEFAULT_XML"
713
714    local ORIG_CMD_FLAGS="`sed -n -e "s/^.*>\([0-9A-Fa-f]*\)<\/cmdFlags>/\1/p" $COS_DEFAULT_XML`"
715
716    CMD_FLAGS=$(($((ORIG_CMD_FLAGS & ~0xff)) | $CMD_FLAGS))
717    # insert OSFlags between <cmdFlags.> and </cmdFlags.> xml tags if different
718    if [ $CMD_FLAGS -ne $ORIG_CMD_FLAGS ]; then
719        sed -i -e "s|\(<cmdFlags.*>\).*\(<.*>\)|\1${CMD_FLAGS}\2|" "$FILE_DEST"
720    fi
721}
722
723###############################################################################
724# update_meta_xml
725###############################################################################
726update_meta_xml()
727{
728    local FILE_DEST="$1"
729    local META_DEFAULT_XML="$CAFE_ROOT/system/bin/ghs/cafe/boot/meta_default.xml"
730    local OWN_META_XML="$CAFE_CODE_DIR/../meta/meta.xml"
731
732    if [ $CAFERUN_OPTION_MLC_EMU_LAUNCH -eq 0 ]
733    then
734        if [ -f "$OWN_META_XML" ]; then
735            ABS_OWN_META_XML=$(cd $(dirname "$OWN_META_XML") && pwd)/$(basename "$OWN_META_XML")
736            ABS_FILE_DEST=$(cd $(dirname "$FILE_DEST") && pwd)/$(basename "$FILE_DEST")
737            if [ $ABS_OWN_META_XML != $ABS_FILE_DEST ]
738            then
739                echo Copy "$OWN_META_XML" to "$FILE_DEST"
740                cp -f "$OWN_META_XML" "$FILE_DEST"
741            fi
742        else
743            check_title_id "$FILE_DEST" "$META_DEFAULT_XML" "$APP_XML_FILE"
744        fi
745
746        check_xml_version "$FILE_DEST" "$META_DEFAULT_XML"
747
748        # insert os version
749        sed -i -e "s|\(<os_version .*>\).*\(<.*>\)|\1${CAFERUN_COLDBOOT_OS_VERSION}\2|" "$FILE_DEST"
750
751        echo Updating title id, group id, title version and app type in $FILE_DEST, based on $APP_XML_FILE...
752
753        # get titleId from disc emulation's app.xml
754        DISC_EMU_TID=`sed -n 's|.*<title_id.*>\(.*\)</title_id>|\1|p' "$APP_XML_FILE"`
755        # insert system.default_title_id
756        sed -i -e "s|\(<title_id .*>\)\(.*\)\(</title_id.*>\)|\1${DISC_EMU_TID}\3|" "$FILE_DEST"
757
758        # get group Id from disc emulation's app.xml
759        local DISC_EMU_GID=`sed -n 's|.*<group_id.*>\(.*\)</group_id>|\1|p' "$APP_XML_FILE"`
760        # insert system.default_title_id
761        sed -i -e "s|\(<group_id .*>\)\(.*\)\(</group_id.*>\)|\1${DISC_EMU_GID}\3|" "$FILE_DEST"
762
763        # get title version from disc emulation's app.xml
764        local DISC_EMU_TITLEVER_HEX=`sed -n 's|.*<title_version.*>\(.*\)</title_version>|\1|p' "$APP_XML_FILE"`
765        local DISC_EMU_TITLEVER_DECIMAL=`printf "%05u" 0x$DISC_EMU_TITLEVER_HEX`
766        # insert system.default_title_id
767        sed -i -e "s|\(<title_version .*>\)\(.*\)\(</title_version.*>\)|\1${DISC_EMU_TITLEVER_DECIMAL}\3|" "$FILE_DEST"
768
769    # else
770    #     No need to update meta.xml in $CAFE_META_DIR.
771    #     System uses $CAFE_MLC_DIR/title/$MLC_EMU_TID_HI/$MLC_EMU_TID_LO/meta/meta.xml installed by cafeinstall.
772
773    fi
774}
775
776###############################################################################
777# update_boot_logos
778###############################################################################
779update_boot_logos()
780{
781    local FILE_DEST="$1"
782
783    # Src files
784    local BOOT_MOVIE_H264="$CAFE_ROOT/system/bin/ghs/cafe/meta/bootMovie.h264"
785    local BOOT_LOGO_TEX_TGA="$CAFE_ROOT/system/bin/ghs/cafe/meta/bootLogoTex.tga"
786
787    local ICON_TEX_TGA="$CAFE_ROOT/system/bin/ghs/cafe/meta/iconTex.tga"
788    local BOOT_TV_TGA="$CAFE_ROOT/system/bin/ghs/cafe/meta/bootTvTex.tga"
789    local BOOT_DRC_TGA="$CAFE_ROOT/system/bin/ghs/cafe/meta/bootDrcTex.tga"
790
791    # Dest files
792    local DEST_BOOT_MOVIE_H264="$FILE_DEST/bootMovie.h264"
793    local DEST_BOOT_LOGO_TEX_TGA="$FILE_DEST/bootLogoTex.tga"
794
795    local DEST_ICON_TEX_TGA="$FILE_DEST/iconTex.tga"
796    local DEST_BOOT_TV_TGA="$FILE_DEST/bootTvTex.tga"
797    local DEST_BOOT_DRC_TGA="$FILE_DEST/bootDrcTex.tga"
798
799    # Boot Logo should be updated
800
801    cp -u "$BOOT_MOVIE_H264"   "$DEST_BOOT_MOVIE_H264"
802    cp -u "$BOOT_LOGO_TEX_TGA" "$DEST_BOOT_LOGO_TEX_TGA"
803
804    # Applicaion Boot Textures should be copy if files do not exist
805
806    if [ ! -f "$DEST_ICON_TEX_TGA" ]
807    then
808    	cp -u "$ICON_TEX_TGA" "$DEST_ICON_TEX_TGA"
809    fi
810
811    if [ ! -f "$DEST_BOOT_TV_TGA" ]
812    then
813        cp -u "$BOOT_TV_TGA"  "$DEST_BOOT_TV_TGA"
814    fi
815
816    if [ ! -f "$DEST_BOOT_DRC_TGA" ]
817    then
818        cp -u "$BOOT_DRC_TGA" "$DEST_BOOT_DRC_TGA"
819    fi
820}
821
822###############################################################################
823# check_directory_cygdrive_path
824###############################################################################
825check_directory_cygdrive_path()
826{
827    if [ -z "$1" ]
828    then
829        echo "$(basename "$0") failed: Please define $2"
830        echo "                Please 'export $2=/cygdrive/<drive>/<valid>/<dir>'"
831        exit 15
832    fi
833
834    if [ "${1:0:10}" != "/cygdrive/" ]
835    then
836        echo "$(basename "$0") failed: $2 path must start with /cygdrive/"
837        echo "                $2 = $1"
838        echo "                Please 'export $2=/cygdrive/<drive>/<valid>/<dir>'"
839        exit 15
840    fi
841}
842
843###############################################################################
844# create_directory_if_noexist
845###############################################################################
846create_directory_if_noexist()
847{
848    if [ ! -d "$1" ]
849    then
850        echo "$(basename "$0"): Creating dir: $1"
851        mkdir -m 0777 -p "$1"
852    fi
853}
854
855###############################################################################
856# compute_flat_version
857#
858# Function to make version checking the Host Bridge easier for comparisons
859# Imported from hostcheckversion
860###############################################################################
861
862compute_flat_version()
863{
864    IFS="."
865    local v=( $1 )
866    echo $((${v[0]} * 1000000 + ${v[1]} * 10000 + ${v[2]} * 1000 + ${v[3]}))
867}
868
869################################################################################
870# sed
871#
872# Wrapper function for /usr/bin/sed. Needed because of a sed bug: when using
873# some non-UTF-8 encoding formats (ex: Shift-JIS), executing on a file with
874# multibyte characters, sed can hang. This function forces sed to use the UTF-8
875# encoding format, then restores to previous format.
876################################################################################
877sed()
878{
879    local saved_lang=$LANG
880    LANG=C.UTF-8
881    /usr/bin/sed "$@"
882    LANG=$saved_lang
883}
884
885###############################################################################
886# main
887###############################################################################
888
889echo `basename "$BASH_SOURCE"`: using sed workaround
890
891
892while getopts :m:g:e:p:d:k:w:a:o:unxbijqNADLRFcfsryt:l:hH:2Vv:WM:z OPT
893do
894  case $OPT in
895    m ) echo "$(basename "$0") failed: memmap not supported" >&2
896        usage
897        exit;;
898    g ) PPC_OS_FLAGS=$(($PPC_OS_FLAGS | $OPTARG));; # set flags to pass to PPC COS
899    p ) DEBUG_PROC_ID="$OPTARG"              # specify a process to debug
900    	if [ "$((DEBUG_FLAGS & 0xf))" -ne 0 ]
901    	then
902    		DEBUG_FLAGS=$(($((DEBUG_FLAGS & ~0xf)) | $((DEBUG_PROC_ID & 0xf))))
903    	fi;;
904    d ) DEBUGGER="$OPTARG"                   # specify a debugger
905        DEBUG_FLAGS=$(($DEBUG_FLAGS | $((DEBUG_PROC_ID & 0xf))))
906        #export CAFE_RUN_FORCERESTART=1
907        ;;
908    k ) DEBUG_ELF_FILE="$OPTARG";;           # file to send to debugger
909    w ) PPC_OS_FLAGS=$(($PPC_OS_FLAGS | $OPTARG));; # temp hack for RiscWatch
910    a ) DASH_A_ARGS="$OPTARG";;              # arguments
911    o ) CAFERUN_COLDBOOT_OS_VERSION="$OPTARG";;
912    b ) CAFERUN_COLDBOOT_OS_VERSION=0x00050010100080${CAFERUN_OS_MAJOR_VERSION};;
913    u ) CAFERUN_COLDBOOT_OS_VERSION=0x000500101000C0${CAFERUN_OS_MAJOR_VERSION};;
914    n ) PPC_OS_FLAGS=$(($PPC_OS_FLAGS | 0x02000));;   # specifically enable shared code
915    i ) DEBUG_FLAGS=$(($DEBUG_FLAGS | 16));; # stop in init code
916    R ) DEBUG_FLAGS=$(($DEBUG_FLAGS | 32));; # don't stop in main code
917    j ) DEBUG_FLAGS=$(($DEBUG_FLAGS | 64));; # stop in pre-init code
918    q ) CAFE_SYSLOG_LEVEL=0;;                # turn warnings off
919    v ) CAFE_SYSLOG_LEVEL="$OPTARG";;        # set a syslog level (0..7)
920    e ) # Use name-spacing to segregate consumers of options
921        BRIDGE_PARAMETERS_WITH_E="$BRIDGE_PARAMETERS_WITH_E -e $OPTARG"
922	    if [ "${OPTARG%%:*}" == "mcp" ]
923		then
924		    # Parse information for MCP's benefit
925		    MCP_INFO_OPTION=${OPTARG#*mcp:}
926			if [ "${MCP_INFO_OPTION%%:*}" == "launch_hint" ]
927			then
928			    MCP_LAUNCH_HINT=${MCP_INFO_OPTION#*launch_hint:}
929			fi
930	    elif [ "$OPTARG" == "nopcfs" ]
931        then
932            # This is the designation for PCFSServer to disable PCFS
933            echo "$(basename $0): Emulating PCFS Headless Mode."
934            PCFS_HEADLESS_EMUL="-pcfsdisable"
935	    elif [ "$OPTARG" == "noFFIO" ]
936        then
937            # This is the designation for PCFSServer to disable Fast File IO
938            echo "$(basename $0): Disabling PCFS Fast File IO."
939            PCFSSERVER_PARAMETERS="$PCFSSERVER_PARAMETERS -noFFIO"
940	    elif [ "$OPTARG" == "noCSR" ]
941        then
942            # This is the designation for PCFSServer to disable Combined Send+Recv in MION
943            echo "$(basename $0): Disabling Combined Send+Recv in MION."
944            PCFSSERVER_PARAMETERS="$PCFSSERVER_PARAMETERS -noCSR"
945	    elif [ "$OPTARG" == "sdioasdbgr" ]
946        then
947            USE_EXI_AS_DEBUG_CHANNEL=0
948        elif [ "${OPTARG%%:*}" == "ejectstate" ]
949        then
950            # set the MION eject state (in or out) before launching
951            EJECT_STATE=${OPTARG#*ejectstate:}
952            if [ "$EJECT_STATE" != "in" -a "$EJECT_STATE" != "out" ]
953            then
954                echo "ERROR: invalid ejectstate parameter '$OPTARG'"
955                exit
956            fi
957        elif [ "${OPTARG%%:*}" == "wumad" ]
958        then
959            # set the wumad to the file or directory provided
960            CAFE_WUMAD=${OPTARG#*wumad:}
961            BRIDGE_PARAMETERS="$BRIDGE_PARAMETERS -sata"
962            BRIDGE_PARAMETERS_WITH_E="$BRIDGE_PARAMETERS_WITH_E -e sata"
963            CAFE_RUN_FORCERESTART=1
964            # validation of wumad parameter is done at the time of creating the DLF.
965        elif [ "${OPTARG%%:*}" == "soft_launch_cafe_elf" ]
966        then
967            # This is the CAFE_ELF of the top-level script
968            # that invoked this script to power cafe on. This is used
969            # to create the disk image
970            CAFERUN_OPTION_CALLED_FROM_CAFEDISCRUN=yes
971            SOFT_LAUNCH_CAFE_ELF=${OPTARG#*soft_launch_cafe_elf:}
972        else
973            # Pile up arguments to FSEmul and parse for hdd bank or pcfsport number
974            BRIDGE_PARAMETERS="$BRIDGE_PARAMETERS -$OPTARG"
975            if [ "${OPTARG%%:*}" == "h" ]
976            then
977                # This is the designation of which hard drive to use
978                RUN_FROM_HDD_BANK=${OPTARG#*h:}
979            fi
980            if [ "${OPTARG%%:*}" == "pcfsport" ]
981            then
982                # This is the designation of which pcfs port number to use
983                PCFS_OVER_SATA_PORT=${OPTARG#*pcfsport:}
984            fi
985			if [ "${OPTARG%%:*}" == "sdio" ]
986			then
987				# Make sure we have an appropriate version of FSEmul to use this option
988				# Host Bridge 3.2.4.4 and beyond have this option
989				source hostcheckversion
990				hbver_flat=$(compute_flat_version $CAFERUN_HOSTBRIDGE_VERSION)
991				if [ $hbver_flat -lt 3024004 ]
992				then
993					# remove the sdio parameter
994					BRIDGE_PARAMETERS=${BRIDGE_PARAMETERS/-sdio}
995					BRIDGE_PARAMETERS_WITH_E=${BRIDGE_PARAMETERS_WITH_E/-sdio}
996				fi
997			fi
998		fi
999        ;;
1000    c ) DEBUGGER="cattoucan";;               # flag to cat serial to terminal
1001    f ) CAFESTOP_ONLY_IF_FSEMUL=1;;          # only call cafestop if FSEmul is not running (option for autotest only)
1002    s ) CAFERUN_OPTION_SOFT_LAUNCH=1;;       # use soft launch to run new app
1003    y ) CAFERUN_OPTION_FAST_RELAUNCH=1;;     # use soft launch to run new app
1004    r ) CAFERUN_OPTION_SOFT_RESTART=1;;      # restart current app (also possible with soft launch)
1005    F ) export CAFE_RUN_FORCERESTART=1;;	 # force restart
1006    t ) if [[ (( ${#OPTARG} = 18 && ${OPTARG:0:2} = "0x" )) || ${#OPTARG} = 16 ]]	# Check for correct ID length. 16 characters, 18 with 0x.
1007		then
1008			CAFERUN_OPTION_MLC_EMU_LAUNCH=1
1009			CAFERUN_OPTION_MLC_EMU_TITLEID="0x${OPTARG:(-16)}"	# Take ID and add 0x in front
1010		else
1011			echo "Title ID has incorrect length."
1012			echo "A correct ID is 18 characters plus 0x in the beginning or 16 without 0x."
1013			echo "Ex: 0x1234567812345678 or 1234567812345678"
1014			echo "Found: ${OPTARG}"
1015			exit
1016		fi;;
1017    l ) if [ "${OPTARG:(-4)}" != ".rpl" ]
1018        then
1019            # convert spaces to '|' character so it can be put into a space-delimited list
1020            RPL_DIRS="$RPL_DIRS ${OPTARG// /|}"
1021        else
1022            RPL_FILES="$RPL_FILES ${OPTARG// /|}"
1023        fi;;
1024    h ) usage
1025        exit;;
1026    H ) if [ $OPTARG = "disable" ]
1027        then
1028            HEARTBEAT_DISABLE=$((0x00020000))
1029        elif [ $OPTARG = "enable" ]
1030        then
1031            HEARTBEAT_DISABLE=0
1032        else
1033            usage
1034            exit
1035        fi;;
1036    x ) BRIDGE_PARAMETERS="$BRIDGE_PARAMETERS -sata";; # Tell FSEmul to use sata
1037    z ) if [ ! -e "$CAFE_DATA_DIR" ]
1038        then
1039            echo "Session data directory is missing and needs to sync'd!"
1040            echo "  Please re-run without the '-z' option."
1041            exit
1042        fi
1043        # Suppress the synctool mirroring of the session data directory
1044        export CAFERUN_OPTION_NO_DATA_SYNC=1;;
1045    A ) echo "*** -A option is deprecated and has no effect. ATFS is now default file system. ***";; # No effect now
1046    D ) echo "$(basename "$0") failed: -D option is deprecated. DVDFS is now unsupported" >&2
1047        usage
1048        exit;;
1049	L ) IGNORE_VERSION=TRUE;;
1050    M ) SYSTEM_MODE="$OPTARG";; # System mode, must be "test" or "dev"
1051    \:) echo "$(basename "$0") failed: missing argument" >&2
1052        usage
1053        exit;;
1054    \?) echo "$(basename "$0") failed: invalid option: -$OPTARG" >&2
1055        usage
1056        exit;;
1057  esac
1058done
1059shift $(($OPTIND-1))
1060
1061#if a PCFS over SATA port was not chosen by the command line
1062if [ -z "$PCFS_OVER_SATA_PORT" ]
1063then
1064    # if a PCFS port is specified by the environment
1065    if [ "$USE_PCFS_OVER_SATA" == "1" ]
1066    then
1067        # take the port from the environment
1068        PCFS_OVER_SATA_PORT=$SESSION_PCFS_SATA_PORT
1069        BRIDGE_PARAMETERS="$BRIDGE_PARAMETERS -pcfsport:$SESSION_PCFS_SATA_PORT"
1070
1071        echo "$(basename $0): using PCFS over SATA on port $PCFS_OVER_SATA_PORT."
1072    else
1073        echo "$(basename $0): not using PCFS over SATA"
1074    fi
1075fi
1076
1077if [ ! -z "$PCFS_OVER_SATA_PORT" ]
1078then
1079    PCFSSERVER_PARAMETERS="$PCFSSERVER_PARAMETERS -c $PCFS_OVER_SATA_PORT"
1080else
1081    echo "$(basename $0): PCFS_OVER_SATA_PORT is not set."
1082fi
1083
1084if [ ! -z "$PCFSSERVER_PARAMETERS" ]
1085then
1086    echo "$(basename $0): PCFSServer parameters '$PCFSSERVER_PARAMETERS'"
1087fi
1088
1089# bridge parameters must have -h:  or -em, otherwise
1090# FSEmul will think it is the old, unsupported launch method
1091if [[ ! "$BRIDGE_PARAMETERS" == *-h:* ]]
1092then
1093    if [[ ! "$BRIDGE_PARAMETERS" == *-em* ]]
1094    then
1095        BRIDGE_PARAMETERS="$BRIDGE_PARAMETERS -em"
1096    fi
1097fi
1098
1099
1100# Choose hfio, disc block emulation, WUMAD or HDD mode
1101DISC_EMU_TYPE=hfio
1102if [ "$CAFERUN_OPTION_CALLED_FROM_CAFEDISCRUN" == "yes" ]
1103then
1104    if [ -n "$RUN_FROM_HDD_BANK" ]
1105    then
1106        DISC_EMU_TYPE=hdd
1107        echo "$(basename "$0"): Will launch HDD bank $RUN_FROM_HDD_BANK"
1108    elif [ -n "$CAFE_WUMAD" ]
1109    then
1110        # wumad emulation started from cafediscrun
1111        DISC_EMU_TYPE=hdd
1112    elif [ $CAFERUN_OPTION_SOFT_LAUNCH -eq 1 ]
1113    then
1114        ALLOW_DISCRUN_IN_SOFTLAUNCH=1
1115        DISC_EMU_TYPE=blockemu
1116        BRIDGE_PARAMETERS="$BRIDGE_PARAMETERS -em" # Tell FSEmul to use block emulation explicitly
1117    else
1118        DISC_EMU_TYPE=blockemu
1119
1120        BRIDGE_PARAMETERS="$BRIDGE_PARAMETERS -em" # Tell FSEmul to use block emulation explicitly
1121                                                   # Note that FSEmul may continue previous mode (HDD or EMU)
1122                                                   # if it gets -sata option
1123    fi
1124elif [ -n "$CAFE_WUMAD" ]
1125then
1126    # wumad emulation started from caferun
1127    DISC_EMU_TYPE=hdd
1128else
1129    # default
1130    DISC_EMU_TYPE=hfio
1131    if [ "$CAFE_BOOT_MODE" == "NAND" ]
1132    then
1133        if [ "$SYSTEM_MODE" = "test" ] # User specified test through the option
1134        then
1135            echo "$(basename "$0") Test mode not supported on NAND."
1136            exit 25
1137        fi
1138        echo "$(basename "$0"): Will use NAND file system"
1139    else
1140        echo "$(basename "$0"): Will use PCFS file system emulation"
1141    fi
1142    if [ -n "$RUN_FROM_HDD_BANK" ]
1143    then
1144        echo "$(basename "$0"): HDD bank $RUN_FROM_HDD_BANK will be attached to odd"
1145    fi
1146fi
1147
1148echo "$(basename "$0"): bridge parameters: $BRIDGE_PARAMETERS"
1149# echo "$(basename "$0"): bridge parameters with -e: $BRIDGE_PARAMETERS_WITH_E"
1150
1151CAFERUN_COLDBOOT_OS_VERSION=$(printf %016llx $CAFERUN_COLDBOOT_OS_VERSION)
1152
1153# stop device + previous caferun (unlock files)
1154HOSTSTOP_RVAL=0
1155if [ $CAFESTOP_ONLY_IF_FSEMUL -eq 0 -o "`ps | grep FSEmul`" != "" ]
1156then
1157    source cafestop
1158
1159    # cafestop -> hoststop -> sets HOSTSTOP_RVAL
1160    if [ $HOSTSTOP_RVAL -ne 0 ]
1161    then
1162        echo "$(basename "$0") failed: Please connect device and power on."
1163        exit 5
1164    fi
1165fi
1166
1167# Exits if not correct version within sourced script
1168source hostcheckversion
1169
1170
1171# abort the script when any command returns an error (non-zero value) after cafestop.
1172set -e
1173
1174# with MULTI 5.3.13 it is no longer required to pass OSReport messages
1175# over the debugger connection. MULTI 5.3.13 will by default read
1176# directly from localhost:6001 if the port needs to be changed use:
1177# the options (change localhost and 6001 as needed):
1178# -console_iphost localhost -console_ipport 6001
1179
1180# case "${CONSOLE}" in
1181#   toucan )
1182#     if [ $CATOUTPUT = 1 -a $DEBUGGER != "cattoucan" ]
1183#     then
1184#         DEBUG_FLAGS=$(($DEBUG_FLAGS | 128))
1185#     fi
1186#     ;;
1187#   exi )
1188#     # do nothing
1189#     ;;
1190# esac
1191
1192# use SDIO as the debug channel
1193if [ $USE_EXI_AS_DEBUG_CHANNEL -eq 0 ]
1194then
1195    DEBUG_FLAGS=$(($DEBUG_FLAGS | 256))
1196fi
1197
1198CAFE_SYSLOG_LEVEL=$((CAFE_SYSLOG_LEVEL & 7))
1199PPC_OS_FLAGS=$(($PPC_OS_FLAGS | $HEARTBEAT_DISABLE | $DEBUG_FLAGS | $((CAFE_SYSLOG_LEVEL << 9))))
1200# copy the STOP flags (0x70) and syslog level flags (0xe00)
1201# move the STDOUT_TO_DBG flag from 0x80 to 0x02
1202# set 0x1 if PROC_ID != 0
1203PPC_APP_FLAGS=$(($((PPC_OS_FLAGS & 0x00000e70)) | $(((PPC_OS_FLAGS >> 1) & 0x80)) | $(((PPC_OS_FLAGS >> 6) & 0x02)) | $(((PPC_OS_FLAGS & 0xf) != 0))))
1204
1205SYSTEM_XML="$CAFE_SLC_DIR/sys/config/system.xml"
1206
1207# Find a temporary directory
1208if [ -z "$CAFE_TEMP" ]
1209then
1210    #CAFERUN_WORK_DIR=`cygpath -m "$CYGWIN_PATH/tmp/${SESSION_PATH_PREFIX}caferun"`
1211	print "CAFE_TEMP environment variable is not set."
1212	exit -13
1213else
1214    CAFERUN_WORK_DIR=`cygpath -m "$CAFE_TEMP/${SESSION_PATH_PREFIX}caferun"`
1215fi
1216create_directory_if_noexist "$CAFERUN_WORK_DIR"
1217
1218# Syncronize the session data directory if multisession and not suppressed
1219if [ $SESSION_MANAGER -eq 1 ]
1220then
1221    if [ $CAFERUN_OPTION_NO_DATA_SYNC -eq 0 -a $CAFERUN_OPTION_SOFT_RESTART -eq 0 ]
1222    then
1223        syncsession
1224        export CAFERUN_OPTION_NO_DATA_SYNC=1
1225    fi
1226fi
1227
1228if [ $CAFERUN_OPTION_SOFT_RESTART -eq 0 ]
1229then
1230
1231    # Create SLC emulation directory
1232    check_directory_cygdrive_path "$CAFE_SLC_DIR" CAFE_SLC_DIR
1233    create_directory_if_noexist "$CAFE_SLC_DIR/sys"
1234
1235    # Check MLC emulation directory (cafeinstall will create directories)
1236    check_directory_cygdrive_path "$CAFE_MLC_DIR" CAFE_MLC_DIR
1237    create_directory_if_noexist "$CAFE_MLC_DIR"
1238
1239    if [ -n "$1" ]
1240    then
1241        if [ "$DISC_EMU_TYPE" == "hdd" ]
1242        then
1243            echo "$(basename "$0"): Specified rpx/elf file is used for setting title id from app.xml only"
1244        fi
1245
1246        # Processing below is only for disc emulation application
1247
1248        CAFE_ELF="`cygpath -a "$1"`"
1249
1250        if [ "$SESSION_MANAGER" -eq 1 ]
1251        then
1252            # Check that the RPX exists
1253            if [ ! -e "$CAFE_ELF" ]
1254            then
1255                echo "$(basename "$0") failed: Cannot find rpx application in $CAFE_ELF"
1256                exit 2
1257            fi
1258
1259            TMP_SUB_DIR=`basename "$1" ."${CAFE_ELF##*.}"`
1260
1261            # Check data TMP directory
1262            check_directory_cygdrive_path "$CAFE_DATA_TMP" CAFE_DATA_TMP
1263            create_directory_if_noexist "$CAFE_DATA_TMP/$TMP_SUB_DIR"
1264
1265            CAFE_ELF_SRC_DIR="$(dirname "$CAFE_ELF")"
1266
1267            # Sync CAFE_ELF_SRC_DIR to CAFE_DATA_TMP
1268            CAFE_ELF_DIR_DOS=`cygpath -w "$CAFE_ELF_SRC_DIR"`
1269            CAFE_DATA_TMP_DOS=`cygpath -w "$CAFE_DATA_TMP/$TMP_SUB_DIR"`
1270
1271            if [ "$CAFE_ELF_DIR_DOS" != "$CAFE_DATA_TMP_DOS" ]
1272            then
1273                #
1274                # Don't sync if we are running from the data/tmp folder as this is most-likely
1275                # a restart from the Multi debugger.  If not, the files are still ok as they were
1276                # from a previous sync.
1277                #
1278                SYNCTOOL_CFG=`cygpath -w "$CAFE_ROOT/system/bin/tool/synctool.code.xml"`
1279                SYNCTOOL_LOG=`cygpath -w "$CAFE_DATA_TMP/synctool.log"`
1280
1281                set +e
1282                synctool.exe -cfgxml "$SYNCTOOL_CFG" "$CAFE_ELF_DIR_DOS" "$CAFE_DATA_TMP_DOS" >> "$SYNCTOOL_LOG"
1283                SYNCTOOL_RVAL=$?
1284                set -e
1285
1286                if [ $SYNCTOOL_RVAL -ne 0 ]
1287                then
1288                    # Alert user to the failure and to the log file
1289                    echo "  Session code sync FAILED with exit code $SYNCTOOL_RVAL!"
1290                    echo "    See $SYNCTOOL_LOG for details."
1291                    exit 2
1292                fi
1293            fi
1294
1295            # Repoint the CAFE_ELF to the one in the CAFE_DATA_TMP folder
1296            CAFE_ELF="$CAFE_DATA_TMP/$TMP_SUB_DIR/$(basename "$1")"
1297        fi
1298
1299        case "${CAFE_ELF##*.}" in
1300          elf)
1301            DEBUG_ELF_FILE="${CAFE_ELF}"
1302            if [ -e "${CAFE_ELF%.*}.rpx" ]
1303            then
1304                CAFE_ELF="${CAFE_ELF%.*}.rpx"
1305            fi
1306            ;;
1307          rpx)
1308            if [ -z "$DEBUG_ELF_FILE" ]
1309            then
1310                if [ -e "${CAFE_ELF%.*}.elf" ]
1311                then
1312                    DEBUG_ELF_FILE="${CAFE_ELF%.*}.elf"
1313                fi
1314            fi
1315            ;;
1316        esac
1317
1318        if [ "${CAFE_ELF:(-4)}" != ".rpx" ]
1319        then
1320            echo "$(basename "$0") failed: Please provide rpx application as first argument after run_options"
1321            usage
1322            exit 6
1323        fi
1324
1325        if [ ! -e "$CAFE_ELF" ]
1326        then
1327            echo "$(basename "$0") failed: Cannot find rpx application in $CAFE_ELF"
1328            exit 2
1329        fi
1330
1331        CAFE_ELF_DIR="$(dirname "$CAFE_ELF")"
1332
1333        # Check content root and that it starts with "/cygdrive/"
1334        check_directory_cygdrive_path $CAFE_CONTENT_DIR CAFE_CONTENT_DIR
1335        create_directory_if_noexist "$CAFE_CONTENT_DIR"
1336
1337        # Check meta directory
1338        check_directory_cygdrive_path $CAFE_META_DIR CAFE_META_DIR
1339        create_directory_if_noexist "$CAFE_META_DIR"
1340
1341        # Check save directory
1342        check_directory_cygdrive_path "$CAFE_SAVE_DIR" CAFE_SAVE_DIR
1343        create_directory_if_noexist "$CAFE_SAVE_DIR"
1344
1345        # Set CAFE_CODE_DIR
1346        export CAFE_CODE_DIR=$CAFE_ELF_DIR
1347
1348        # title.xml update for command-line argument processing
1349        # update_app_xml must come before update_system_xml so that disc's os version is set properly
1350        APP_XML_FILE="$CAFE_CODE_DIR/app.xml"
1351        update_app_xml "$APP_XML_FILE"
1352        COS_XML_FILE="$CAFE_CODE_DIR/cos.xml"
1353        update_cos_xml "$COS_XML_FILE" "$PPC_APP_FLAGS"
1354
1355        META_XML_FILE="$CAFE_META_DIR/meta.xml"
1356        update_meta_xml "$META_XML_FILE"
1357        update_arglist "$COS_XML_FILE" "$CAFE_ELF" "$@"
1358        update_boot_logos "$CAFE_META_DIR"
1359
1360        for dir in $RPL_DIRS
1361        do
1362            find "${dir//|/ }" -iname '*.rpl' -exec cp '{}' "$CAFE_CODE_DIR" \;
1363        done
1364        for file in $RPL_FILES
1365        do
1366            cp "${file//|/ }" "$CAFE_CODE_DIR"
1367        done
1368    fi
1369
1370	if [ $CAFERUN_INS == 0 ]
1371	then
1372        # Save CAFE_CODE_DIR for caferun -r
1373        if [ "$CAFERUN_OPTION_MLC_EMU_LAUNCH" -eq 1 ]
1374        then
1375            echo "<?xml version=\"1.0\" encoding = \"utf-8\"?>" > "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1376            echo "<emu_tid type=\"string\" length=\"512\">$CAFERUN_OPTION_MLC_EMU_TITLEID</emu_tid>" >> "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1377        else
1378            echo "<?xml version=\"1.0\" encoding = \"utf-8\"?>" > "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1379            echo "<code_dir type=\"string\" length=\"512\">$CAFE_CODE_DIR</code_dir>" >> "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1380            echo "<disc_emu type=\"string\" length=\"8\">$DISC_EMU_TYPE</disc_emu>" >> "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1381            echo "<hdd_bank type=\"string\" length=\"8\">$RUN_FROM_HDD_BANK</hdd_bank>" >> "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1382		    echo "<disc_emu_tid type=\"string\" length=\"8\">$DISC_EMU_TID</disc_emu_tid>" >> "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1383        fi
1384		echo "<coldboot_os type=\"string\" length=\"8\">$CAFERUN_COLDBOOT_OS_VERSION</coldboot_os>" >> "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1385		echo "<fast_relaunch type=\"string\" length=\"8\">$CAFERUN_OPTION_FAST_RELAUNCH</fast_relaunch>" >> "$CAFERUN_WORK_DIR/previous_launch_info.xml"
1386	fi
1387    update_system_xml "$SYSTEM_XML" "$PPC_OS_FLAGS" "$SYSTEM_MODE" "$MCP_LAUNCH_HINT"
1388
1389else
1390
1391    if [ ! -f "$SYSTEM_XML" ]
1392    then
1393        echo "$(basename "$0") failed: Please $(basename "$0") an rpx application first"
1394        exit 9
1395    fi
1396
1397    # Retrieve previous settings
1398    CAFERUN_OPTION_MLC_EMU_TITLEID=`sed -n 's|.*<emu_tid.*>\(.*\)</emu_tid>|\1|p' "$CAFERUN_WORK_DIR/previous_launch_info.xml"`
1399	CAFERUN_OPTION_FAST_RELAUNCH=`sed -n 's|.*<fast_relaunch.*>\(.*\)</fast_relaunch>|\1|p' "$CAFERUN_WORK_DIR/previous_launch_info.xml"`
1400    if [ "$CAFERUN_OPTION_MLC_EMU_TITLEID" != "" ]
1401    then
1402        CAFERUN_OPTION_MLC_EMU_LAUNCH=1
1403		CAFERUN_COLDBOOT_OS_VERSION=`sed -n 's|.*<default_os_id .*>\(.*\)</default_os_id>|\1|p' "$SYSTEM_XML"`
1404    else
1405        export CAFE_CODE_DIR=`sed -n 's|.*<code_dir.*>\(.*\)</code_dir>|\1|p' "$CAFERUN_WORK_DIR/previous_launch_info.xml"`
1406        DISC_EMU_TYPE=`sed -n 's|.*<disc_emu.*>\(.*\)</disc_emu>|\1|p' "$CAFERUN_WORK_DIR/previous_launch_info.xml"`
1407        RUN_FROM_HDD_BANK=`sed -n 's|.*<hdd_bank.*>\(.*\)</hdd_bank>|\1|p' "$CAFERUN_WORK_DIR/previous_launch_info.xml"`
1408		DISC_EMU_TID=`sed -n 's|.*<disc_emu_tid.*>\(.*\)</disc_emu_tid>|\1|p' "$CAFERUN_WORK_DIR/previous_launch_info.xml"`
1409
1410        PREV_CAFE_ARGSTR=(`sed -n 's|.*<argstr.*>\(.*\)</argstr>|\1|p' "$CAFE_CODE_DIR/cos.xml"`)
1411        CAFE_ELF="$CAFE_CODE_DIR/${PREV_CAFE_ARGSTR[@]:0:1}"
1412
1413		CAFERUN_COLDBOOT_OS_VERSION=`sed -n 's|.*<coldboot_os.*>\(.*\)</coldboot_os>|\1|p' "$CAFERUN_WORK_DIR/previous_launch_info.xml"`
1414        # Serve up correct ios version from cold boot
1415		if [ "$CAFERUN_COLDBOOT_OS_VERSION" == "" ]
1416		then
1417            CAFERUN_COLDBOOT_OS_VERSION=`sed -n 's|.*<default_os_id .*>\(.*\)</default_os_id>|\1|p' "$SYSTEM_XML"`
1418		fi
1419
1420        if [ "$DISC_EMU_TYPE" != "hdd" ]
1421        then
1422            if [ ! -f "$CAFE_ELF" ]
1423            then
1424                echo "$(basename "$0") failed: Could not find $CAFE_ELF"
1425                exit 9
1426            fi
1427
1428            echo "$(basename "$0"): Restarting $CAFE_ELF"
1429        fi
1430    fi
1431fi
1432
1433# Check that os version is built
1434if [ "$CAFE_BOOT_MODE" == "PCFS" ]
1435then
1436if [ ! -d "$CAFE_SLC_DIR/sys/title/${CAFERUN_COLDBOOT_OS_VERSION:0:8}/${CAFERUN_COLDBOOT_OS_VERSION:8:8}/code" ]
1437then
1438    echo "$(basename "$0") failed: Cannot find OS in ${CAFE_SLC_DIR}/sys/title/${CAFERUN_COLDBOOT_OS_VERSION:0:8}/${CAFERUN_COLDBOOT_OS_VERSION:8:8}/code"
1439    exit 8
1440elif [ `find "$CAFE_SLC_DIR/sys/title/${CAFERUN_COLDBOOT_OS_VERSION:0:8}/${CAFERUN_COLDBOOT_OS_VERSION:8:8}/code" -iname '*.rpl' | wc -l` -eq 0 ]
1441then
1442    CAFERUN_OS_VERSION_PARTIAL_UNIQUE_ID=$((0x$CAFERUN_COLDBOOT_OS_VERSION >> 8 & 0xFF))
1443    if [ $CAFERUN_OS_VERSION_PARTIAL_UNIQUE_ID -ge 192 ]   # 0xC0
1444    then
1445        echo "$(basename "$0") failed: Please build FDEBUG os version $CAFERUN_COLDBOOT_OS_VERSION"
1446    elif [ $CAFERUN_OS_VERSION_PARTIAL_UNIQUE_ID -ge 128 ] # 0x80
1447    then
1448        echo "$(basename "$0") failed: Please build DEBUG os version $CAFERUN_COLDBOOT_OS_VERSION"
1449        echo "                or do not use \"$(basename "$0") -b\" to use NDEBUG os version"
1450    elif [ $CAFERUN_OS_VERSION_PARTIAL_UNIQUE_ID -ge 64 ]  # 0x40
1451    then
1452        echo "$(basename "$0") failed: Please build NDEBUG os version $CAFERUN_COLDBOOT_OS_VERSION"
1453        echo "                or use \"$(basename "$0") -b\" to use DEBUG os version"
1454    else
1455        echo "$(basename "$0") failed: Non-standard titleId for os version $CAFERUN_COLDBOOT_OS_VERSION"
1456    fi
1457    exit 8
1458fi
1459fi
1460
1461# Image upload is not performed anymore
1462# if [ ! -z "$RUN_FROM_HDD_BANK" ]
1463# then
1464#     if [ $SKIP_HDD_IMAGE_UPLOAD = 0 ]
1465#     then
1466#         set +e
1467#         preparehdd $RUN_FROM_HDD_BANK "$CAFE_ELF" $BRIDGE_CURRENT_IP_ADDRESS "$CAFERUN_WORK_DIR"
1468#         PREPHDD_STAT=$?
1469#         if [ ! $PREPHDD_STAT = 0 ]; then
1470#             echo "$(basename "$0"): preparehdd found non-mion HDD test to be skipped"
1471#             exit $PREPHDD_STAT
1472#         fi
1473#         set -e
1474#     fi
1475# fi
1476
1477################################################################################
1478#
1479# Set the eject state
1480#
1481# if the command line used '-e ejctstate:in' or '-e ejctstate:out'
1482# call the MION using the CGI to set to eject state
1483#
1484################################################################################
1485if [ ! -z "$EJECT_STATE" ]
1486then
1487    mionurl $BRIDGE_CURRENT_IP_ADDRESS /mion/status.cgi operation=eject disc=$EJECT_STATE
1488	CMD_RESULT=$?
1489	if [ $CMD_RESULT -ne 0 ]
1490	then
1491	    echo "Set ejectstate:'$EJECT_STATE' failed=$CMD_RESULT"
1492	    echo "Continuing execution, Ignoring ejectstate"
1493    fi
1494fi
1495
1496if [ -z "$PCFS_SRV_LOG_DIR" ]
1497then
1498    PCFS_SRV_LOG_OUTPUT=/dev/null
1499else
1500    PCFS_LOG_TIMESTAMP=`date +"%H%M%S"`
1501    PCFS_SRV_LOG_OUTPUT=$PCFS_SRV_LOG_DIR/${SESSION_PATH_PREFIX}pcfs_$PCFS_LOG_TIMESTAMP.txt
1502    echo PCFS output logged to $PCFS_SRV_LOG_OUTPUT
1503fi
1504
1505
1506# Prepare host file io.  Use nohup to prevent shell CTRL-C from stopping PCFSServer.exe
1507if [ "${CAFE_ELF:(-4)}" == ".rpx" -o "$DISC_EMU_TYPE" == "hdd" ]
1508then
1509    if [ "$DISC_EMU_TYPE" == "hfio" ]
1510    then
1511		MAPDIR_MLC="$(cygpath -w "$CAFE_MLC_DIR")/"
1512		MAPDIR_SLC="$(cygpath -w "$CAFE_SLC_DIR")/"
1513		MAPDIR_CODE="$(cygpath -w "$CAFE_CODE_DIR")/"
1514		MAPDIR_META="$(cygpath -w "$CAFE_META_DIR")/"
1515		MAPDIR_CONTENT="$(cygpath -w "$CAFE_CONTENT_DIR")/"
1516		MAPDIR_SAVE="$(cygpath -w "$CAFE_SAVE_DIR")/"
1517
1518        PCFS_DIR_MAPPING+=(-m /%MLC_EMU_DIR/           "$MAPDIR_MLC")
1519        PCFS_DIR_MAPPING+=(-m /%SLC_EMU_DIR/           "$MAPDIR_SLC")
1520        PCFS_DIR_MAPPING+=(-m /%DISC_EMU_DIR/code/     "$MAPDIR_CODE")
1521        PCFS_DIR_MAPPING+=(-m /%DISC_EMU_DIR/meta/     "$MAPDIR_META")
1522        PCFS_DIR_MAPPING+=(-m /%DISC_EMU_DIR/content/  "$MAPDIR_CONTENT")
1523        PCFS_DIR_MAPPING+=(-m /%DISC_EMU_DIR/save/     "$MAPDIR_SAVE")
1524    else
1525
1526		MAPDIR_MLC="$(cygpath -w "$CAFE_MLC_DIR")/"
1527		MAPDIR_SLC="$(cygpath -w "$CAFE_SLC_DIR")/"
1528	    MAPDIR_SAVE="$(cygpath -w "$CAFE_SAVE_DIR")/"
1529
1530        PCFS_DIR_MAPPING+=(-m /%MLC_EMU_DIR/         "$MAPDIR_MLC")
1531        PCFS_DIR_MAPPING+=(-m /%SLC_EMU_DIR/         "$MAPDIR_SLC")
1532        PCFS_DIR_MAPPING+=(-m /%SAVE_EMU_DIR/        "$MAPDIR_SAVE")
1533    fi
1534elif [ "$CAFERUN_OPTION_MLC_EMU_LAUNCH" -eq 1 ]
1535then
1536    MAPDIR_MLC="$(cygpath -w "$CAFE_MLC_DIR")/"
1537    MAPDIR_SLC="$(cygpath -w "$CAFE_SLC_DIR")/"
1538
1539    PCFS_DIR_MAPPING+=(-m /%MLC_EMU_DIR/          "$MAPDIR_MLC")
1540    PCFS_DIR_MAPPING+=(-m /%SLC_EMU_DIR/          "$MAPDIR_SLC")
1541else # includes HDD case
1542    MAPDIR_MLC="$(cygpath -w "$CAFE_MLC_DIR")/"
1543    MAPDIR_SLC="$(cygpath -w "$CAFE_SLC_DIR")/"
1544
1545    PCFS_DIR_MAPPING+=(-m /%MLC_EMU_DIR/          "$MAPDIR_MLC")
1546    PCFS_DIR_MAPPING+=(-m /%SLC_EMU_DIR/          "$MAPDIR_SLC")
1547fi
1548
1549export CAFERUN_INS=1
1550
1551ELF_NEST_OPT=
1552ELF_NEST_VALUE=
1553if [ "$ALLOW_DISCRUN_IN_SOFTLAUNCH" -eq 1 ]
1554then
1555    # the DLF will not be used now - but it has to be made now,
1556    # as this is the point where all input environment variables are set correctly
1557    # for cafedevrun.sh to run
1558    source bootrun -makedlf
1559    if [[ ! "$BRIDGE_PARAMETERS_WITH_E" == *soft_launch_cafe_elf* ]]
1560    then
1561        if [ ! -z "$CAFE_ELF" ]
1562        then
1563            # we didn't get the ELF name from above. So we must to decide what it is.
1564            ELF_NEST_OPT=-e
1565            ELF_NEST_VALUE="soft_launch_cafe_elf:$CAFE_ELF"
1566
1567            # Since there is no way to communicate new DLF contents into an existing FSEmul,
1568            #  we need a forceful restart for this case - even though it is softlaunch
1569            CAFE_RUN_FORCERESTART=1
1570        fi
1571    fi
1572fi
1573
1574if [ "$CAFERUN_OPTION_SOFT_LAUNCH" -eq 1 ]
1575then
1576	if [ "$CAFE_RUN_FORCERESTART" -eq 1 ]
1577	then
1578        echo "**** FORCE REBOOT ****"
1579		cafestop
1580		sleep 1
1581        cafeon -noprompt $BRIDGE_PARAMETERS_WITH_E $ELF_NEST_OPT "$ELF_NEST_VALUE"
1582        sleep 20
1583	fi
1584    set +e
1585    # try this three times
1586    for i in 1 2 3
1587    do
1588	    PCFS_SYNC_DATE=$(date +%F-%H-%M-%S-)$(expr substr $(date +%N), 1 4)
1589
1590		echo "Launching $(basename "$CAFE_ELF") @ sync date [$PCFS_SYNC_DATE]"
1591        PCFSServerSync.exe -comment "$(basename "$0"): ----- [$PCFS_SYNC_DATE] Launching $(basename "$CAFE_ELF") -----" \
1592                           $PCFS_HEADLESS_EMUL -softlaunch -message "${PCFS_DIR_MAPPING[@]}"
1593        CMD_RESULT=$?
1594
1595        if [ $CMD_RESULT -eq 0 ]
1596        then
1597            #if [ $CAFERUN_OPTION_SOFT_LAUNCH -eq 1 -a "$CAFE_BOOT_MODE" == "NAND" ]
1598            #then
1599                set_system_xml_cos_flags "$PPC_OS_FLAGS"
1600                CMD_RESULT=$?
1601            #fi
1602            if [ $CMD_RESULT -eq 0 ]
1603            then
1604                # this is softlaunch, and there is no RPX specified.
1605                # try to see if we can get it from the user - in case it applies
1606                if [ -z "$DISC_EMU_TID" ]
1607                then
1608                    if [ "$CAFERUN_OPTION_MLC_EMU_LAUNCH" -eq 1 ]
1609                    then
1610                        DISC_EMU_TID="0x${CAFERUN_OPTION_MLC_EMU_TITLEID:(-16)}"
1611                        echo "HDD emulation: using command line TID $DISC_EMU_TID"
1612                    fi
1613                fi
1614
1615                # still not set despite our attemtps?
1616                if [ -z "$DISC_EMU_TID" ]
1617                then
1618                    echo "$(basename "$0") failed: Unable to determine title ID, and it was not specified in the command line."
1619                    exit 9
1620                fi
1621
1622                # this is to phase in adoption smoothly into autotest,
1623                # avoiding any changes to tests other than cafediscrun.
1624                # We may disable this check later.
1625                if [ "$ALLOW_DISCRUN_IN_SOFTLAUNCH" -eq 1 ]
1626                then
1627                    CMD_RESULT=0
1628                    if [ "$SYSTEM_MODE" == "prod" -o "$SYSTEM_MODE" == "PROD" ]
1629                    then
1630                        echo "Setting system mode to 0"
1631                        devkitmsg "sys_mode 0"
1632                       	CMD_RESULT=$?
1633                    elif [ "$SYSTEM_MODE" == "dev" -o "$SYSTEM_MODE" == "DEV" ]
1634                    then
1635                        echo "Setting system mode to 1"
1636                        devkitmsg "sys_mode 1"
1637                       	CMD_RESULT=$?
1638                    elif [ "$SYSTEM_MODE" == "test" -o "$SYSTEM_MODE" == "TEST" ]
1639                    then
1640                        echo "Setting system mode to 2"
1641                        devkitmsg "sys_mode 2"
1642                       	CMD_RESULT=$?
1643                    fi
1644                    if [ ! $CMD_RESULT -eq 0 ]
1645                    then
1646                        echo "$(basename "$0") failed: Unable to set system mode to $SYSTEM_MODE"
1647                	    exit 1
1648                    fi
1649                fi
1650
1651				if [ "$CAFERUN_OPTION_FAST_RELAUNCH" -eq 1 ]
1652                then
1653				    if [ "$CAFERUN_OPTION_MLC_EMU_TITLEID" -eq "0xFFFFFFFFFFFFFFFF" ]
1654					then
1655					    COSDEBUG_TID_HI=${DISC_EMU_TITLEID:0:10}
1656                        COSDEBUG_TID_LO=${DISC_EMU_TITLEID:10:8}
1657					else
1658                        COSDEBUG_TID_HI=${CAFERUN_OPTION_MLC_EMU_TITLEID:0:10}
1659                        COSDEBUG_TID_LO=${CAFERUN_OPTION_MLC_EMU_TITLEID:10:8}
1660					fi
1661                    # extract the cos arguments
1662					local COS_ARGS=`sed -n 's|\(<argstr.*>\)\(.*\)\(</argstr.*>\)|\1|p' "$FILE_DEST"`
1663
1664					cosdebug.sh cos launchex 0x$COSDEBUG_TID_HI 0x$COSDEBUG_TID_LO $COS_ARGS
1665                else
1666				    if [ ! -z "$MCP_LAUNCH_HINT" ]
1667				    then
1668					    devkitmsg "title_softlaunch $CAFERUN_COLDBOOT_OS_VERSION $DISC_EMU_TID $MCP_LAUNCH_HINT" -v -p $SESSION_LAUNCH_CTRL_PORT
1669				    else
1670					    devkitmsg "title_softlaunch $CAFERUN_COLDBOOT_OS_VERSION $DISC_EMU_TID" -v -p $SESSION_LAUNCH_CTRL_PORT
1671				    fi
1672				fi
1673            	CMD_RESULT=$?
1674           		if [ $CMD_RESULT -eq 0 ]
1675            	then
1676                	break;
1677                fi
1678            fi
1679        fi
1680        # one of previous commands failed, reboot and try again
1681        echo "**** BOOTING CATDEV ****"
1682        cafestop
1683        sleep 5
1684        cafeon -noprompt $BRIDGE_PARAMETERS_WITH_E  $ELF_NEST_OPT "$ELF_NEST_VALUE"
1685        sleep 20
1686    done
1687    set -e
1688else
1689    PCFS_SYNC_DATE=$(date +%F-%H-%M-%S-)$(expr substr $(date +%N), 1 4)
1690
1691    echo "Starting PCFSServer.exe @ sync date [$PCFS_SYNC_DATE] from $PCFSSERVER_EXE"
1692    nohup "$PCFSSERVER_EXE" -r 100 $PCFSSERVER_PARAMETERS $PCFS_HEADLESS_EMUL \
1693          "${PCFS_DIR_MAPPING[@]}" < /dev/null > $PCFS_SRV_LOG_OUTPUT 2>&1 &
1694
1695    echo "PCFSServer has started"
1696
1697    if [ ! -z "$PCFSSERVER_PARAMETERS" ]
1698    then
1699        echo "Waiting for PCFSServer initialization..."
1700
1701        set +e
1702        PCFSServerSync.exe -wait 25000 $PCFS_HEADLESS_EMUL -comment "$(basename $0): [$PCFS_SYNC_DATE] ----- Hard-launch Startup Complete -----"
1703        PCFSSERVERSYNC_RVAL=$?
1704        set -e
1705
1706        if [ $PCFSSERVERSYNC_RVAL -ne 0 ]
1707        then
1708            echo "PCFSServerSync exited with value $PCFSSERVERSYNC_RVAL!"
1709            exit 30
1710        fi
1711
1712        echo "PCFSServer initialization complete !"
1713    else
1714        echo "PCFSServer started without syncronization."
1715    fi
1716
1717
1718    BOOTRUN_ELF_OPT=
1719    BOOTRUN_ELF_VALUE=
1720    if [ ! -z $SOFT_LAUNCH_CAFE_ELF ]
1721    then
1722        BOOTRUN_ELF_OPT=-usedlf
1723        BOOTRUN_ELF_VALUE="$SOFT_LAUNCH_CAFE_ELF"
1724    fi
1725    source bootrun $BOOTRUN_ELF_OPT "$BOOTRUN_ELF_VALUE"
1726fi
1727
1728connect_serial_or_debugger
1729