The target server acts as a broker for the communication path to the target and provides services commonly required by the Tornado tools. In order to support new CPU architectures, new object-module formats, and new communications back ends with minimum programming effort, the corresponding parts of the target server are structured as shared libraries on UNIX or dynamically linked libraries (DLLs) on Windows.1 The remainder of the target server, known as the target server core, is independent of the target architecture, the target operating system, and of the communications transport layer.
This chapter examines the communications back end. It shows how a back end fits into the architecture of the target server, how the back end is implemented in Tornado, and how to implement new back ends, either for the WDB agent or for non-WDB agents such as emulators. For an overview of the target server and its components, see 1.3 The Target Server and the WTX Protocol. To add a new object-module-format loader, see 3. Object-Module Loader. This chapter gives an overall orientation; for details, see the online reference material under Tornado API Reference>Target Server Back End Interface.
% tgtsvr -V -B mybkend ... &
c:> tgtsvr -V -B mybkend ...
The portion of the Tornado target server that communicates with the target is called the back end. Many back ends are supported, each dedicated to an alternative host-target connection. All back ends share a single purpose: to provide a set of primitive services for the target server core. Depending on the back end, executing these routines can be as simple as forwarding a request to the target agent (the WDB RPC back end) or as complex as translating the request to an entirely different protocol (an emulator back end).
Some back ends (WDB back ends) are designed to communicate with the target agent supplied with VxWorks, which is called the WDB agent. (See Figure 2-1.) The WDB agent uses the Wind DeBug (WDB) protocol to communicate between the host and target operating system. The key advantage of this protocol, from a programming perspective, is that it corresponds one-to-one with the target server back-end API. There is a back-end function corresponding to each WDB protocol request. When using the WDB agent, the back end manages the mechanics of transmitting the request to the target over whatever hardware medium provides host-target communication. Creating a new back end is a matter of writing the necessary host and target code to transport WDB protocol messages.2
Other back ends (non-WDB back ends) are designed to communicate with alternative agents, such as an emulator that serves as a hardware debug agent. (See Figure 2-2). If a back end does not use the WDB agent, the back end itself must provide the requested service. The underlying service could be provided by another software agent (for example, a ROM monitor) or by a hardware agent (for example, an in-circuit emulator or ICE). Virtually any cross-development framework can be supported in a back end because the back-end API is general. It is also possible, if necessary, to return a "service not available" error or to fill in the TGT_OPS table with a NULL pointer if it is impossible to implement the service as requested by the target server.
This chapter provides background information on the structure of a target server back end, followed by descriptions of how to write new back ends for the WDB agent and for a non-WDB agent. Writing a new back end allows you to use a different communication protocol or to use a new method for providing services to the Tornado tools; none of the tools needs to be modified because the tools communicate only with the target server. Our discussion provides an overall orientation; throughout this chapter, refer to the reference entries in Part 2 for details.
This section discusses several aspects of back-end implementation that are similar for both WDB and non-WDB back ends.
A target server can only use one back end at a time. The back end is attached when the target server is started. The -B option specifies which back end to attach. For example, to use the back end named wdbserial, select wdbserial in the target server initialization window, which invokes the target server with the following command:
% tgtsvr ... -B wdbserial ...
Back ends are linked with the target server dynamically using DLLs. At run time, the target server searches installDir/host/hostType/lib/backend, which contains a DLL for each available back end, and loads the specified back end.3 The back end can have any name, but we recommend you choose names that are short, lower case, and suggest the connection strategy to which they refer. If the requested back end is not found, the attachment fails and the target server abandons its start-up sequence, exiting with an error condition.
Once the correct DLL is found, the target server asks if the back end handles special flags with the bkendFlagsGet( ) routine. If the back end exports this routine, the target server calls the routine and appends the returned flags array to its own array. When it finishes parsing the command line, the target server calls an initialization routine that attaches the back end. Besides initializing the back end, this routine fills in a table of function pointers (the TGT_OPS structure) used by the target server to call the back-end functions and a structure (the BKEND_INFO structure) which describes how the back end notifies the target server of asynchronous events. Finally, the initialization routine calls bkendTgtConnect( ) to attach the target server to a specified target.
|
|
|||||||||||||||||||
A back end can export a flag-parsing routine to handle any back-end specific command line parameters. if the loaded back end exports such a routine, the target server runs the routine to get a list of the parameters the back end needs to access. The parameters are contained in the FLAG_DESC structure (defined in installDir/host/include/flagutil.h). The target server adds the flags to its own array of recognized flags and parses its entire command line.
|
|
|||||||||||||||||||
The name of the flag-parsing routine is standardized so that the target server can find it. It is composed of the back-end file name (without extension) plus the word FlagsGet. For our example back end, called mybkend, the flag-parsing routine is mybkendFlagsGet( ), which is defined in mybkend.c.
The back-end flag-parsing routine must match the following prototype:
FLAG_DESC * mybkendFlagsGet (void)
The returned value is a null-terminated FLAG_DESC structure array. This structure describes the arguments handled by the back end and is composed of five fields:
typedef struct flag_desc /* target server flag descriptions */
{
char * flagName, /* verbose flag name */
char * flagTerseName, /* abbreviated name of flag (or NULL) */
PARSE_RTN parseRoutine; /* flag processing routine */
int outputPtr; /* where to store the output result */
char * flagHelp; /* flag help string */
} FLAG_DESC;
When the target server parses its command line, it tries to match the current argument to the flagname or flagtersename field of each FLAG_DESC structure array element. If an element matches the command line argument, the target server executes the parseRoutine field of the matching element, giving three arguments: the remaining arguments number, the command line argument vector starting with the argument which caused the call to the routine, and the value stored in the outputPtr field. The provided routine interprets as many arguments as necessary, fills the provided location with the parsed value(s), and returns the number of parsed command line arguments. The parsing routine must match the following prototype:
/* flag processing routine definition */ typedef int (*PARSE_RTN) (int argc, char **argv, void * outputPtr)
Store your flagInt( ) routine in the libwpwr shared library and declared it in installDir/host/include/flagutil.h.
|
|
|||||||||||||||||||
Example 2-1: Flag-parsing Routine
Suppose you want to define a back end which can take a serial line speed argument. This argument will be coded with -speed value on the command line. Your code includes declarations and mybkendFlagsGet( ) as follows:
static int mySpeed = 9600; /* mybackend default speed */
static FLAG_DESC mybkendFlags/* my flags descriptions */
{
{"-speed", "-sp", flagInt, (void *) &mySpeed,
"-sp[eed] myBkend Speed definition (default 9600)."},
{NULL, NULL, NULL, 0, NULL} /* End Of Record delimiter */
};
...
FLAG_DESC * mybkendFlagsGet (void)
{
return (FLAG_DESC *) mybkendFlags;
}
Now, suppose you launch the target server with the following command line:
tgtsvr -B mybackend -speed 19200 targetName
When the target server loads mybkend, it calls mybkendFlagsGet( ), appends the mybkendFlags array to its own FLAG_DESC array, and parses the command line. When it parses the -speed argument, it calls flagInt( ) with the first argument set to 3, the second argument pointing to the array "-speed 19200 targetName", and the last argument set to &mySpeed.
This routine interprets the 19200 string as an integer and stores that value at the &mySpeed location. Thus, the back end speed is modified by the command line parameter.
When the target server attaches a back end, it calls the initialization routine of the named back end. The main purpose of this routine is to fill in the TGT_OPS structure defined in installDir/host/include/tgtlib.h, and the BKEND_INFO structure defined in installDir/host/include/bkendlib.h. It also performs whatever back-end initialization is appropriate.
The TGT_OPS structure, whose location is passed as an argument to the back-end initialization routine, is a collection of function pointers. The initialization routine fills this structure with pointers to functions that provide the back-end services. The implementation of the services is entirely back-end dependent. By virtue of the coupling, it is possible to support many back ends, each providing the same service in its own way. Once the TGT_OPS structure is filled in and returned, the target server is ready to start communicating with the target.
The BKEND_INFO structure, whose location is also passed as an argument to the back-end initialization routine, contains information about the newly loaded back end. This information consists of the back-end version and the asynchronous events notification. Once the BKEND_INFO structure is filled, the target server launches a thread which handles the asynchronous events according to the given method.
The name of the initialization routine is standardized so that the target server can find and attach the back end chosen by the user. It is composed of the back-end file name (without extension) plus the word Initialize. For our example back end, called mybkend, the initialization routine is mybkendInitialize( ), which is defined in mybkend.c. This name indicates the DLL that the target server loads as well as the back-end initialization routine to call. The back-end name is passed to the target server by the -B option when the target server is started.
The back-end initialization routine must match the following prototype:
STATUS mybkendInitialize
(
char * tgtName, /* network unique target name to connect */
TGT_OPS * pTgtOps /* vector of back end functions to fill */
BKEND_INFO * pBkendInfo /* Backend notification method */
)
The first parameter, tgtName, passed to the back-end initialization routine from the target server specifies the target name. The meaning of the parameter is completely back-end dependent. For example, the wdbrpc back end uses the tgtName as the target's IP address while the wdbserial back end doesn't use tgtName. The only restriction is that tgtName must be unique for each target server.
The second parameter passed to the back-end initialization routine, pTgtOps, is a pointer to the TGT_OPS structure (defined in installDir/host/include/tgtlib.h), which declares the target server back-end interface. The initialization routine must fill this structure with the appropriate information and function pointers so that the target server understands what the back end can do. When the target server needs to perform a service, it calls the appropriate back-end function.
typedef struct tgt_ops /* target server back end operations */
{
BOOL tgtConnected; /* TRUE if connected to Target */
TGT_LINK_DESC tgtLink; /* link descriptor */
u_int tgtSupInfo; /* additional information */
int tgtEventFd; /* not used. Use BKEND_INFO structure*/
/* back end routines pointers */
UINT32 (*tgtPingRtn) (void);
UINT32 (*tgtConnectRtn) (WDB_TGT_INFO *);
UINT32 (*tgtDisconnectRtn) (void);
UINT32 (*tgtModeSetRtn) (UINT32 *);
...
} TGT_OPS;
The tgtConnected field is a boolean variable that is TRUE if the target board is connected to the target server by the back end. This boolean must be set to FALSE by the initialization routine because the board is not yet connected. It is set to TRUE by the target server if the target-board connection succeeds.
The tgtLink field is a TGT_LINK_DESC structure also defined in installDir/host/include/tgtlib.h. This structure describes the communication link with the board and is composed of three fields:
typedef struct
{
char * name; /* target/host link name */
u_int type; /* target/host link type */
u_int speed; /* target/host link speed in bps */
} TGT_LINK_DESC;
The tgtSupInfo field is a target server spare field.
The tgtEventFd field obsolete. The file descriptor that the back end uses to wake up the target server when an asynchronous event arrives from the target system is now stored in the BKEND_INFO structure. The back end should set tgtEventFd to NONE.
|
|
|||||||||||||||||||
The tgtPingRtn field is the first of many back-end function pointers. Each function is a service provided by the back end. The complete description of each function is given in the online reference material under Tornado API Reference>Target Server Back End Interface. (Note that the function names are similar to the pointer names, but are prefixed with bkend. All function pointers of this structure must be filled in. If a back-end service is not provided, set the pointer to NULL.
The last parameter passed to the back-end initialization routine, pbkendInfo, is a pointer to a BKEND_INFO structure (defined in installDir/host/include/bkendlib.h). This structure describes information related to the currently attached back end. The key item is the asynchronous notification method provided by the back end.
typedef struct bkEndInfo
{
int tgtBkInfoSize; /* size of this structure */
int tgtBkVersion; /* Version of BackEnd Hiword = Major;
Loword = Minor*/
union
{
struct _pollingMethod
{
int bkEndPollingMethod, /* polling method used :
* POLL_NONE_MODE
* POLL_SELECT_MODE
* POLL_BKROUTINE_MODE
*/
union _bkEndNotifMethod
{
int pollingFd; /* polling file desc for POLL_SELECT_MODE */
int (*bkEndSelectRtn)(int timeout) /* bkEnd select routine */
} BKEND_NOTIF_METHOD;
} POLLING_METHOD;
} INFO;
} BKEND_INFO;
The target server initializes BKEND_INFO with the following values:
bkendinfo.tgtBkInfoSize = sizeof (bkend_info); bkendinfo.tgtBkVersion = BKEND_VERSION_2
The tgtBkInfoSize field is set by the target server to the size of its BKEND_INFO structure. The tgtBkVersion field is set to BKEND_VERSION_2 (defined in installDir/host/include/ bkendlib.h) for the current version. The back end should check these values and reset tgtBkVersion if necessary.
During the initialization phase, the back end fills in the structure with its method of notifying the target server of asynchronous events. An excerpt from the WDB serial back-end initialization routine is as follows:
... pbkInfo->tgtBkVersion = BKEND_VERSION_2; /* Backend version 2 */ /* we'll provide our polling method ( on NT ) */ #ifdef WIN32 pbkInfo->INFO.POLLING_METHOD.bkEndPollingMethod = POLL_BKROUTINE_MODE; pbkInfo->INFO.POLLING_METHOD.BKEND_NOTIF_METHOD.bkEndSelectRtn = win32SerialSelect; #else /* on UNIX we give the tty file desc */ pbkInfo->INFO.POLLING_METHOD.bkEndPollingMethod = POLL_SELECT_MODE; pbkInfo->INFO.POLLING_METHOD.BKEND_NOTIF_METHOD.pollingFd = EventFd; #endif return (OK);
After attaching and initializing the back end, the target server is able to perform actions on the connected board by calling back-end functions. The syntax of all back-end functions is similar. Functions usually take two pointers as arguments: the first points to a structure that contains parameters specifying the service input data; the second points to a structure that is filled in with the data returned by the service. One or both structure pointers may be omitted when a service requires no input or output data. Each function must return a WDB status code: either WDB_OK on success, or an appropriate WDB error code describing the error encountered during the service call. The complete error code list is located in the file installDir/share/src/agents/wdb/wdb.h.
Because the connection to the back-end interface is indirect, through a table of function pointers initialized when the back end is attached, there are no naming restrictions on back-end functions. Their scope is local to the back end, as all other modules access the back end through the function table. A complete description of the function interface is provided in the online reference material under Tornado API Reference>Target Server Back End Interface.
The target server not only sends requests and information to the target, it also needs feedback from the target about what is occurring there. When a target event (such as hitting a breakpoint or an exception) occurs, the target server must be notified. The back-end interface provides two notification methods, synchronous and asynchronous. The notification method is provided to the target server by the BKEND_INFO structure pointer.
With the two asynchronous methods, the target server calls the back end bkendEventGet( ) function only to get the event information. Those methods are more efficient because no polling for events is required.
After issuing a bkendEventGet( ) command, the target server calls bkendEvtPending( ) to see if other events are pending, and calls bkendEventGet( ) again if bkendEvtPending( ) indicates that other events are available to be read. This method allows the target server to upload multiple target events without having to enter the select loop each time.
The target server is a multi-threaded application. This allows a back end to export its own select-like routine instead of being limited to a selectable file descriptor. This is particularly useful on WIN32 hosts where select( ) addresses only sockets and not other handles such as serial lines or files. The select-like routine can be expanded to address such devices. It allows the target server back-end thread to sleep (thus not consuming CPU cycles) until events arrive. This routine must match the following prototype:
int bkendSelect (int timeout);
The timeout given by the target server is always WAIT_FOREVER (-1).
It is possible that two threads may use the back ends routines at the same time: a synchronous thread (the one servicing a WTX request), which can call all the routines given in the TGT_OPS structure, and the asynchronous thread (the one which is pending on the given select-like routine). You will have to handle the race condition here. The simplest way is to make the back-end thread return from the select-like routine with a 0 status. This causes the target server to wait until the other thread completes its transaction before asking if there are pending events.
For a discussion of how to inform the target server that a select-like routine is used, see 2.2.1 Attachment and Initialization.
If the target server does not exit gracefully, which usually occurs because there is an error in the back end, it leaves its name in the registry. This prevents you from reusing the same name when you restart the target server. On UNIX, clean up the registry using the "unregister" button of the Tornado launcher. On Windows, select Target Server>Manage on the Tools menu and select Unregister. On either host you can create a wtxtcl script, unreg, like the following:
#!/bin/sh
#
# unreg - remove a name from the registery
#
# Syntax: unreg <targetServerName>
#
echo -n Unregistering $1 ...
wtxtcl << EOF
set seekName $1
set allNames [wtxInfo]
set pos [lsearch -glob \$allNames \*\$seekName\* ]
if { \$pos < 0} {
puts "invalid name"
exit
}
set fullName [lindex [lindex \$allNames \$pos ] 0 ]
wtxUnregister \$fullName
EOF
echo ` done.'
This is an example of the helpful utilities you can create with the wtxtcl shell. For more information on WTX Tcl, see 4. The WTX Protocol, the Tornado User's Guide: Tcl Appendix, and the online reference material under Tornado API Reference>WTX TCL Library.
A message logging facility exists for all WDB back ends. This facility logs all transactions between the back end and the target agent to a file or terminal. Message logging simplifies diagnosing connection problems between the host and target because one can look at the sequence of transactions that led to the problem. This facility can also be used to help new back-end designers understand requests exchanged between existing back ends and the target.
All back ends that connect to the WDB agent send requests to the target using the library installDir/ host/src/tgtsvr/backend/share/rpccore.c, which contains the logging calls. This logging mechanism is back-end-specific, and is only provided for WDB back ends.
Message logging is enabled when the target server is started with the -Bd fileName option. For example, to save log information in the file named /tmp/WDB.log, invoke the target server with a command like the following:
% tgtsvr ... -Bd /tmp/tgtDebug.log ...
The file name must be specified; otherwise message logging is not enabled. If the file already exists, log information is added at the end of the file. Each time a request is logged to the file, output is flushed to assure that the last request written in the log file is actually the last request sent even if the target server hangs.
The length of the debug file can be controlled by the -Bm logMaxSize option. With this flag, a file is created, or reset if it already exists, and is written as a circular file: when the file length reaches logMaxSize, the file is rewritten from the beginning, overriding the existing data. If this flag is not set or set with a 0 value, a file is created, or opened in append mode if it already exists, and is truncated.
Each log file starts with a header, followed by records of transactions with the back end. The header provides:
The following is an example of this header:
User Name : wrs Started : Wed Jun 17 16:38:19 1998 Target Server Name : target@couesnon Target Name : target Target Server Options : tgtsvr -V target -Bd /tmp/WDB.log Timeout value : 1 second(s) Request re-send Max : 3
Each request log is made of two parts: the service requested and the reply. The service-requested information includes the request number, the service name, and the input-structure name with the name and value of each field. The request number is a 16-bit integer assigned to distinguish each request. When the upper limit is reached, the request number restarts from zero. The input-structure name and values are omitted when the service does not require input arguments. A service input structure is signaled by the word In placed before its name.
The reply log consists of three parts: the number of times the request was resent, the service status, and the reply-structure name with the name and value of each field. The service status value is one of the WDB error codes. The file wdb.h located in the installDir/share/src/agents/wdb directory provides the complete error code list. As in the input case, the output structure is signaled by the word Out before its name and it is omitted when the reply has no return value.
An example of a request log is given below. In this example the target server performs a checksum on a block of 49788 bytes of target memory starting at address 0x2000. The return status is OK and the checksum value is 0xffff34de.
2 2 WDB_MEM_CHECKSUM Wed Jun 17 16:38:19 1998
In WDB_MEM_REGION
baseAddr 0x20000
numBytes 49788
param 0
3 Out status: 0k
UINT32 0xffff34de
To make a new back end accessible to the Configure pop-up window under the target server option of the Tools menu, add your backend DLL to installDir/host/x86-win32/lib/backend.
Back-end-specific flags must be supplied in the target server launch command edit box, since Tornado cannot automatically know how many and what kind of arguments the back end supports. To do so, add necessary code to handle backend specific flags to:
installDir/host/resource/tcl/app-config/Tornado/01TgtSvrConfigure.win32.tcl and installDir/host/resource/tcl/app-config/Tornado/01TgtSvrManage.win32.tcl.
This section describes the Wind DeBug (WDB) version 1.0 protocol. It is the protocol used by the Tornado target server back ends that communicate with the WDB agent (WDB RPC, WDB Serial, and NetROM). See Figure 2-1 for a diagram of how these back ends connect to the WDB agent.
|
|
NOTE:
This section is provided for completeness only. If you want to create a new back end for Tornado, knowledge of the WDB protocol is not needed because the support libraries handle all aspects of the protocol not related to transport. In fact, in order to assure that your back end is not affected by changes in WDB, you should gain access to WDB facilities through the support libraries as shown in the example back ends. To create a non-WDB back end that communicates with a device such as an ICE or a ROM monitor, you also need to implement all the target services required. For details, refer to 2.4 Writing a Non-WDB Back End.
|
||||||||||||||||||
A WDB request packet sent to the agent contains the following parts, as shown in Figure 2-3:
The WDB parameter wrapper contains three 4-byte words. The first word is a checksum over the whole RPC packet (RPC header plus XDR stream). The second word is the packet size. These two words enable the agent to determine if a corrupted packet has arrived. The third word is a sequence number. The low order two bytes of the sequence number are used to allow the agent to ignore old or duplicated requests (which can occur with UDP transport). The high order two bytes are the host ID. When a host issues a WDB_TARGET_CONNECT request, the host ID portion of the sequence number is recorded. If a request arrives from a non-connected host, the RPC fails with the RPC error status PROG_UNAVAIL or SYSTEM_ERR, depending on whether the agent is already connected to another target server or not. The WDB_TARGET_CONNECT request always establishes a new connection, if necessary by dropping the old one. If the host wants to test whether or not the agent is already connected before trying to establish a connection, it should first issue a WDB_TARGET_PING request and see if the RPC fails with error status PROG_UNAVAIL. If so the connection is busy.
The routine xdr_WDB_PARAM_WRAPPER is used to encode or decode the entire XDR stream (the procedure parameters plus the 12-byte parameter wrapper). The following example is a code stub from the host routine rpcCoreClntCall( ):
seqNumber++ ; ... wdbParamWrapper.xdr = inProc; /* xdr func for proc params */ wdbParamWrapper.pParams = in; /* pointer to proc params */ wdbParamWrapper.seqNum = processId | seqNumber; /* seq nb */ ... clntStatus = clnt_call (pWdbClnt, procNum, xdr_WDB_PARAM_WRAPPER, &wdbParamWrapper,...);
A WDB reply packet sent by the agent contains the following parts, as shown in Figure 2-4:
Like the WDB parameter wrapper, the WDB reply wrapper contains three 4-byte words. The first word is a checksum over the whole RPC packet (RPC header plus XDR stream). The second word is the packet size. These two words enable the host to determine if a corrupted reply was returned (and, if so, to reissue the request). The third word is the WDB error status. The high order bit is set if there are events pending on the target, in which case the host can issue a WDB_EVENT_GET request to upload the event. The rest of the word is the actual error status.
After a remote procedure is called, the program should perform error checking. Error status can be communicated in one of two ways: in the RPC header or in the reply wrapper. If the failure is reported in the third word of the RPC header, then the host's clnt_call returns an RPC error status. These have conventional meanings according to the RPC specification. In addition, the WDB agent uses a couple of special codes:
Even if the RPC call succeeds (meaning that the agent tries to execute your command), the command may still fail. The errCode field in the reply wrapper can be checked; if the lower 31 bits are zero, the command succeeded. (Remember that the high order bit is set if there are events pending on the target.) If the value is non-zero, then the procedure failed and the word contains the error code. Error codes have the format WDB_ERR_XXX. The error-code definitions are located in installDir/share/src/agents/wdb/wdb.h.
The routine xdr_WDB_REPLY_WRAPPER is used to encode or decode the entire XDR stream (the reply data plus the 12-byte reply wrapper). The following pseudo code shows how it works:
wdbReplyWrapper.xdr = outProc; /* reply xdr function */
wdbReplyWrapper.pReply = out; /* where to decode reply */
wdbReplyWrapper.errCode = OK; /* just to clear this field */
...
clntStatus = clnt_call (pWdbClnt, procNum, xdr_WDB_PARAM_WRAPPER,
&wdbParamWrapper, xdr_WDB_REPLY_WRAPPER,
&wdbReplyWrapper, timeout);
check (clntStatus)
{
if (RPC_TIMEDOUT or RPC_CANTDECODERES or RPC_CANTDECODEARGS)
try again
if (RPC_SYSTEMERROR)
if we were previously connected, then target must have rebooted so resync
and reconnect.
if (RPC_PROCUNAVAIL)
procedure not configured into agent. Try to rebuild the agent with that
facility included (e.g., virtual I/O is an optional agent facility).
if (RPC_SUCCESS)
agent tried to execute the routine.
check high order bit of wdbReplyWrapper.errCode to see if events are
pending on the target. If so, execute a WDB_EVENT_GET request after
finishing processing this reply.
mask off the high order bit of wdbReplyWrapper.errCode.
if (wdbReplyWrapper.errCode == 0)
success! In this case wdbReplyWrapper.xdr decoded the reply and put
it in wdbReplyWrapper.pReply.
else
wdbReplyWrapper.errCode contains the reason for procedure failure.
The error codes are defined in wdb.h.
}
Asynchronous events can be generated on the target. These include exceptions, breakpoints, and task exiting. These events are queued on the target until the host uploads them with the WDB_EVENT_GET service. In order to prevent the host from polling for events, the agent has two ways to notify the host that events are pending: (1) by setting the high order bit in the errCode status of the reply wrapper; (2) by sending a notify packet.
Normally the agent only sends data to the host in response to RPC requests. The convention is that if the host receives data when it is not waiting for a reply, it means that an event is pending on the target. This allows the target server to select( ) on file descriptors associated with the host tools which are connected as well as with the target. If the target file descriptor becomes active, the host issues a WDB_EVENT_GET request to upload the event (and keeps uploading events until the high order bit in the errCode field is clear). The actual notify packet sent by the agent is a packet that can not be confused with an RPC reply (in case it sends the notify packet just as the host issues an RPC request). In fact, it sends a bogus RPC request.
To provide the necessary host-side support for a new communication pathway, you must write a new back-end DLL to transport WDB protocol messages. Fortunately, most of the back-end code is generic RPC4 code to transport WDB protocol messages; thus you can reuse Wind River's rpccore library5 . Consequently, you can only need to write the back end's initialization code and, if necessary, the client-side RPC implementation.
A WDB back end consists of three parts: (1) the initialization routine, which initializes the back end; (2) the RPC core which manages WDB RPC requests, including XDR; and (3) the client-side RPC implementation, which sends and receives the RPC messages over the network medium. (See Figure 2-5.)
The bkendInit( ) routine is the back-end DLL's entry point and must initialize the back end. To do this, it performs the following services:
In the following sections, we examine the wdbserial back end to demonstrate how to write a new WDB back end. The wdbserial back end consists of two main modules, the wdbserial.c module, which implements the back-end initialization routine, and clnt_tty.c, which provides the client-side RPC implementation for a serial device (see Client-Side RPC Implementation).
The wdbserial.c module consists of one routine, wdbserialInit( ). The target server invokes wdbserialInit( ) after it loads the back end in order to initialize it. The wdbserialInit( ) call creates an RPC CLIENT structure for communicating over a serial device and establishes a link, initializes the generic RPC core library to operate the target agent using the WDB (Wind DeBug) protocol, and initializes a data structure describing the back-end link with the agent. The wdbserial.c code shows how these steps are carried out.
/* wdbserial.c - Remote Procedure Call (RPC) backend library */
After the usual preamble of comments, copyright notice, and inclusion of system header files, wdbserial.c includes the Tornado host header files from the installDir/host/include directory:
... /* includes */ /* system header files go here */ ... #include "tgtlib.h" #include "tgtsvr.h" #include "tssvcmgt.h" #include "host.h" #include "wdb.h" #include "wdbP.h" #include "wpwrutil.h" #include "bkendlib.h" #include "bkendlog.h"
#ifdef WIN32 #include "backend.h" extern int dbg_on; #endif /* WIN32 */
Next, wdbserial.c imports the prototypes to rpcCoreInit( ), which initializes the RPC core library, and clnttty_creat ( ), which creates an RPC connection over a serial link.
extern STATUS rpcCoreInit (CLIENT *, u_int, u_int, TGT_OPS *);
extern CLIENT * clnttty_create (char *, int, u_long, u_long,
struct timeval);
When the target server calls wdbserialInitialize( ), it passes pointers to the TGT_OPS and BKEND_INFO structures. (For more information on these structures, see The TGT_OPS Structure and The BKEND_INFO Structure.)
STATUS wdbserialInitialize
(
char * tgtName, /* target name to connect to (unused) */
TGT_OPS * pTgtOps /* back-end function */
BKEND_INFO * pBkendInfo /* Backend notification method */
)
Windows hosts optionally enable logging of debugging messages from the lower-level serial support:
#ifdef WIN32
dbg_on = GetDebugFlag();
#endif /* WIN32 */
Next, the back end must enable RPC communications over a serial link by creating the CLIENT data structure. If your back end uses an unsupported link type you will need to implement a clntXXX_create( ) call for your communication medium. Wind River implemented clnttty_create( ) for the wdbserial back end.
The back end initializes the RPC client-side transport to the WDB agent: first, struct timeval is initialized with the user's specified timeout; then clnttty_create( ) is called to create the RPC link to the target. Note that the clntty_create( ) call is retried until it succeeds or exceeds the user-specified number of retries.
/* set the connection timeout to the current value */
tv.tv_sec = timeout;
tv.tv_usec = 0;
...
resendCnt = recallNum;
do
{
/* create the backend client and connect the target deamon */
pClnt = clnttty_create (pTtyDevName, baudRate, WDBPROG, WDBVERS, tv);
}
while ((pClnt == NULL) && (--resendCnt > 0));
...
If the RPC client-side initialization fails, the back end sets errno to the appropriate error number, logs an error message, and returns ERROR to indicate that the called routine failed.
if (pClnt == NULL)
{
...
errno = WTX_ERR_SVR_INVALID_DEVICE;
WPWR_LOG_ERR ("%s\n",
clnt_spcreateerror ("wdbserial backend client create"));
return (ERROR);
}
If the RPC client initialization succeeds, the back end calls rpcCoreInit( ) to initialize the rpccore library for use over the serial device. The rpccore library provides all the support necessary to operate the WDB target agent in response to target server requests. In particular, rpcCoreInit( ) initializes the TGT_OPS structure, specifying that the target server should call rpccore routines to perform the various back-end operations.
rpcCoreInit (pClnt, timeout, recallNum, pTgtOps); ...
Finally, the back end describes the target link type. If your back end uses a new link type, define a TGT_LINK_XXX macro in installDir/host/h/tgtlib.h.
pTgtOps->tgtLink.name = "WDB Agent across serial line"; pTgtOps->tgtLink.type = TGT_LINK_SERIAL_RPC; pTgtOps->tgtLink.speed = baudRate; return (OK); }
If your back end must communicate over an unsupported network medium, you must provide a client-side RPC implementation. As a starting point, you should use the clnt_udp.c which is part of Sun Microsystem's public domain RPC distribution and is provided in installDir/target/unsupported/rpc4.0/rpc.
|
|
NOTE:
The client-side RPC implementation must transmit datagrams in a UDP-like manner. In other words, the client-side RPC must reliably transmit an entire datagram. If data is lost, the back end can drop the datagram and RPC repeats the request. Consequently, if the network medium is character-oriented, like a serial device, the back end must packetize datagrams on both the host and target sides (see 2.3.4 Target-Side Code). One way of doing this is to use the SLIP protocol, as Wind River does in the wdbserial back end.
|
||||||||||||||||||
By including the generic makefile templates provided with Tornado, it is easy to write a makefile for a back end.
# Makefile - for WDB serial backend
After the modification history, specify the suffixes of the shared library that will be built:
.SUFFIXES: .so .sl
Next, include the makefile templates provided by the Tornado development environment. These fragments make it easy to build a portable makefile.
include $(WIND_BASE)/host/include/make/generic.mh include $(WIND_BASE)/host/include/make/$(HOST).mh
Set the INCLUDES macro to specify that the compiler can find header files in the installDir/host/include and the installDir/share/src/agents/wdb directories. Specify any other directories that the compiler needs to search to find your back-end header files:
INCLUDES = $(WIND_INC) $(WIND_SHARE_INC)
Specify which modules should be linked to create the back end. List both the back end modules and the rpccore modules (the modules in ../share):
BKEND_OBJS = clnt_tty.o wdbserial.o
BKEND_XDR_OBJS = ../share/ctx.o ../share/ctxcreat.o \
../share/ctxstep.o ../share/evtdata.o \
../share/evtpoint.o ../share/memory.o \
../share/regs.o ../share/rpccksum.o \
../share/rpccore.o ../share/tgtinfo.o \
../share/wrapper.o ../share/xdrcore.o
State the name of the back end:
SH_BKEND_OBJS = wdbserial.$(SHLIB_EXT)
Next, specify any extra compiler flags you need:
LOCAL_CFLAGS = -DPORTABLE -DHOST $(DYN_LK_FLAGS) ... default: lib $(SH_BKEND_OBJS)
Finally, an inference rule states that the back end is built from C source modules that are linked into the shared library. If you need to link the back end with other libraries or are using C++, you must modify this rule.
.c.$(SHLIB_EXT):$(BKEND_OBJS) $(BKEND_XDR_OBJS)
$(SHARED_LD) $(SHARED_LDFLAGS) -o $(SH_BKEND_LIB)/$*.$(SHLIB_EXT) \
$(BKEND_OBJS) $(BKEND_XDR_OBJS)
...
include $(WIND_BASE)/host/include/make/generic2.mh
To build a back end for Windows hosts, you need to create a project for the back end using Microsoft's Visual C++. Because the target server was built with Visual C++ 5.0, we recommend that developers also use Visual C++ 5.0 to avoid incompatibilities between different versions of the standard libraries. Remember to address the following build issues:
The WDB target agent needs a means to send and receive UDP/IP datagrams over the physical network connection. There are two protocol stacks that can be used, the full VxWorks network protocol stack and a lightweight UDP/IP interpreter. The full network protocol stack provides a rich set of functionality, while the lightweight UDP/IP interpreter requires much less target memory. The choice of protocol stacks affects the type of driver that must be written for the physical device.
Drivers that interface with the VxWorks TCP/IP network stack are called network interface drivers. Details of how to write a network interface driver are covered in The BSP Porting Kit (an optional product). The advantage of creating such a driver is that, in addition to being used as a debug communication path, it can also be used for application network communication. To use a network interface driver, configure the target agent for network communication (the default configuration).
Drivers that interface with the target agent's UDP/IP interpreter are called WDB packet drivers. Such drivers have the advantage that they do not require the TCP/IP stack to be present on the target. This can save space on resource-constrained targets. The agent's UDP/IP interpreter has the advantage of small size (only 800 bytes) but it also has limited functionality.
To create a WDB packet driver, start with the template driver in installDir/target/src/drv/wdb/wdbTemplatePktDrv.c. Use of the template is documented in the source file.
You must also modify the agent's startup code to initialize the new communication pathway. The target agent configuration code is provided in installDir/target/src/config/usrWdb.c. To initialize your custom packet driver, add initialization code to usrWdb.c similar to the section bracketed with
#if (WDB_COMM_TYPE == WDB_COMM_TYPE_CUSTOM).
To build the packet driver, copy it into your BSP directory and use the standard techniques described in the Tornado User's Guide: Projects or the VxWorks Programmer's Guide: Configuration and Build. The makefile templates provided in installDir/target/h/make assist in developing a portable makefile. Modify the makefile in your BSP directory so that these modules are built and linked into your VxWorks image.
This section addresses the task of writing a back end that communicates with an agent (such as an emulator) other than the WDB agent. In this case, your back end methods must service back-end API requests directly, in other words, by way of a proprietary emulator API. For a general approach highlighting some of the issues involved in this process, see 2.4.1 Overview of Writing a Non-WDB Back End. The remainder of this chapter presents an example implementation. The complete source code for the acecpu32 example back end plus a back-end development class library, which implements the back-end framework as a C++ abstract base class, are provided in the Back-End Developer's Kit.
The initialization routine is the entry point of the back end. It performs the back-end initialization and attachment. Even before the rest of the back-end functions are implemented, this routine can be called to test correct attachment between the back end and the target server.
Once the attachment and initialization procedures have been carried out successfully, you are ready to begin the major task of writing, documenting, and testing the back-end functions. The remainder of this section outlines the key development issues and suggests one approach to implementing a back end.
The first step in your implementation is to determine what functions your back end must provide. The easiest way to establish this is by using the Back-End Developer's Kit as a basis. It contains a sample back end, the acecpu32, which is an implementation for the fictitious ACE C API. It operates an emulator supporting Motorola CPU32 microprocessors through BDM. It provides a structure and an implementation of common back-end services, including Gopher and checksum, which are emulator independent. You will need to support memory and register accesses, event handling on the target, communication with the emulator or other agent, state handling, and other emulator-dependent services.
Figure 2-7 shows the structure of the acecpu32 implementation.
Figure 2-8 shows how the Event_T class, which manages target event information, is implemented to queue WDB_EVT_DATA.
The recommended plan for implementing the back end is to add support incrementally for the desired services, exercising them with the wtxtcl shell at each stage. (For more information on wtxtcl, see 4.4 WTX Tcl API.) Initially, you should write enough of the framework so that the target server can load your skeleton back end. Then you can add the key functions, testing them to make sure that you are on the right track. If you plan to support both UNIX and Windows hosts, we recommend that you build and test on both hosts in parallel.
The interface between the target server and the back end is documented in 2.2 Back-End Implementation. In addition, 2.2.1 Attachment and Initialization describes the WDB data structures used to pass information into and out of the back end. Your back end methods must also use the WDB error codes. Both the error codes and the data structures are declared in installDir/share/src/agents/wdb/wdb.h.
The Wind River C coding conventions are documented in the Tornado User's Guide: C and C++ Coding Conventions. The following additional conventions have been adopted for C++ and the Back-End Developer's Kit:
Back-end testing relies on the wtxtcl shell provided with Tornado. This shell allows you to send WTX protocol requests to the target server, the same kinds of requests the tools send. Using wtxtcl, you can interactively invoke the back-end methods to verify that they work correctly. Program wtxtcl in Tcl, which Wind River has extended to support the WTX protocol.
The Back-End Developer's Kit consists of a class library that provides the basic back-end framework, an example back end for acecpu32, sample test scripts, and this document. The library also implements common back-end methods, including Gopher and checksum, which are emulator-independent. By integrating this back-end framework into a new back end, you will not have to spend time developing and debugging these back-end services. To take advantage of this framework, derive a vendor-specific back-end class from the abstract base class Backend_T, declared in backend.h as shown in the following example:
...
#include "backend.h"
...
// Declaration of Vendor-specific back end class
class Ace_T : public Backend_T
{
// Backend_T methods which you are overriding go here
...
// Your vendor-specific methods and data go here
};
Once you have derived your vendor-specific class, determine what other classes and objects you need in your system. If you are integrating an existing C API for operating the emulator, you may find that the acecpu32 example back end can be modified.
Some of the classes and objects you may need include the following:
Figure 2-9 shows the architecture of the acecpu32 back end.
After installing the libraries supplied with the Back-End Developer's Kit, follow the implementation procedure laid out in 2.4.1 Overview of Writing a Non-WDB Back End. When you begin tuning performance, if your emulator can perform an operation more efficiently than the default implementation (for example, a memory scan) override Backend_T's methods.
For an example of how to use WDB data structures and error codes, look at the acecpu32 example code in installDir/host/src/tgtsvr/backend/acecpu32.
The Back-End Developer's Kit's class library is supported only on Solaris 2.5.1 and 2.6, Windows NT, and Windows 95 hosts. The source code for this library is provided and can be readily ported to other hosts because of the limited use of operating system calls. Furthermore, the Tornado development environment provides generic makefile stubs which abstract most of the host-dependent build issues.
First, create acecpu32.cpp and define the routine acecpu32Initialize( ), which initializes the back end. Excerpts from acecpu32.cpp are annotated throughout this section.
Tornado provides header files for the development of host tools in installDir/host/include. The first Tornado header file included must be host.h. Declare the interface for the vendor-specific back end, Ace_T, by including acecpu32Backend.h as shown:
/* acecpu32.cpp - back end for ACE's CPU32 BDM emulator */ ... /* includes */ #ifdef WIN32 /* fix clash between Wind River's ERROR and Microsoft's ERROR macros */ #ifdef ERROR #undef ERROR #endif #include <windows.h> #endif /* #ifdef WIN32 */ #include "host.h" #include "tgtlib.h" #include "wpwrutil.h" #include "windll.h" #include "acecpu32Backend.h"
|
|
|||||||||||||||||||
Next, define the back-end initialization routine, acecpu32Initialize( ). For a complete discussion, see 2.2.1 Attachment and Initialization.
The back end must initialize the TGT_OPS and BKEND_INFO structures with the information needed by the target server to operate the back end; in particular, the addresses of the back-end methods must be stored in TGT_OPS and the asynchronous notification method must be stored in BKEND_INFO. In order for the target server, which is a C application, to call the back-end methods, the Backend_T class uses static member functions to provide an interface that supports C calling conventions; these static functions then invoke normal member functions on the actual back end. For more information on the static wrapper and Backend_T architecture, see the documentation in provided in installDir/host/src/tgtsvr/backend/bedk/backend.h.
STATUS acecpu32Initialize
(
char * tgtName, /* network unique target name to connect */
TGT_OPS * pTgtOps /* vector of back end functions to fill */
BKEND_INFO * pBkendInfo /* Backend notification method */
)
|
|
|||||||||||||||||||
The final step is to allocate the actual back end by calling new and to perform error logging. The constructor of Backend_T, the back-end abstract base class, will initialize the back-end function pointers in the TGT_OPS structure. Ace_T's constructor initializes the back-end-specific part of the TGT_OPS structure.
The initialization routine must return OK on success or ERROR on failure, as defined in host.h. The Tornado' wpwrutil library provides several functions for error logging, including the function WPWR_LOG_MSG used in our example. Message logging is enabled by starting the target server with the option -V. For more information on the wpwrutil library, see the online reference material under Tornado API Reference>Target Server Back End Interface.
// Create Backend
pTheBkEnd = new Ace_T (tgtName, timeout, recallNum, pTtyDevName,
baudRate, pTgtOps);
if (pTheBkEnd == NULL)
{
WPWR_LOG_MSG ("acecpu32Init(): new() failed.\n");
return (ERROR);
}
if (! pTheBkEnd->isValid_m())
{
WPWR_LOG_MSG ("acecpu32Init(): back end initialization failed.\n")
return (ERROR);
}
return (OK);
}
Next, declare the skeleton of the vendor-specific back-end class, Ace_T. Derive Ace_T from Backend_T and declare all the mandatory methods in acecpu32Backend.h. The examples in this section show the declaration of the Ace_T class in acecpu32Backend.h.
After the usual preamble of comments and modification history, give the header file the standard macro #ifndef/#define construction to prevent multiple inclusions of the header file. Next, provide the #include statements for the other necessary header files.
/* acecpu32Backend.h - header file for ACE SuperBDM BDM back end */ ... #ifndef __INCacecpu32Backendh #define __INCacecpu32Backendh /* includes */
First, include the Rogue Wave header file.
#include "rw/queuecol.h" #ifdef WIN32 #ifdef ERROR #undef ERROR #endif #endif
Next, include the header file for the ACE C API, ace/api.h. Include it at this point rather than later, with the other BEDK header files, because it includes Windows header files, and they must be included before the system headers. The undefining and redefining of ERROR is required when Windows header files are included because Windows uses a non-standard ERROR definition.
#include "ace/api.h" // ACE's API header file #ifdef WIN32 #ifdef ERROR #undef ERROR #endif #define ERROR (-1) #endif
Next, include Tornado header files; wdb.h defines the WDB data structures used to pass information between the back end and the target server.
#include "host.h" #include "tgtlib.h" #include "wpwrutil.h" #include "wdb.h"
Finally, include backend.h, which pulls in the declaration of Backend_T (the back-end abstract base class) and other back-end-specific header files.
#include "backend.h" #include "event.h" #include "bdmExcLib.h"
Next, create a new link ID to identify your back end as a unique target-link type. This should be done by defining a macro TGT_LINK_BDM_ACE in tgtlib.h. You should choose an unused number in the 0x200 range.
#ifndef TGT_LINK_BDM_ACE // Should be defined in tgtlib.h #define TGT_LINK_BDM_ACE (0x201) /* ACE BDM support */ #endif
Now, declare the Ace_T back-end class as shown below. To reuse the back-end framework and services implemented in Backend_T, you must derive your vendor-specific back end from it. It is declared in installDir/host/src/tgtsvr/backend/bedk/backend.h. The Ace_T constructor has the same arguments as the acecpu32Init( ) routine. It is automatically called when the actual Ace_T back-end object is allocated. The destructor must be declared virtual because Ace_T has virtual functions.
class Ace_T : public Backend_T
{
public:
// Constructors and Destructors.
Ace_T (char * tgtName, u_int timeout, u_int retryNum, char * devName,
u_int param, TGT_OPS * pTgtOps, BKEND_INFO * pBkendInfo);
virtual ~Ace_T ();
Once the constructor and destructor have been declared, declare the mandatory back-end methods. These methods are listed in backend.h.
/////////////////////////////////////////////////////////////////
// Declare back end member functions which need to be over-ridden in
// the vendor-specific back end.
// Declaration of mandatory member functions.
UINT32 tgtPing_m (void);
UINT32 tgtConnect_m (WDB_TGT_INFO * pTgtInfo);
UINT32 tgtDisconnect_m (void);
...
For the present, ignore the optional member functions. If your emulator supports a faster way of performing these operations than the generic implementation provided by the Backend_T class, you may decide to implement them later. Typically, Backend_T implements these methods by reading or writing a block of target memory. If your emulator supports an operation (for example, memory fill) directly, you will gain performance by using your emulator's primitive.
// optional member functions
...
Now declare the mandatory helper methods. Ace_T::fdGet_m( ) should return the event file descriptor, whose activity indicates that an event has occurred on the target. Ace_T::halt_m( ) and Ace_T::unhalt_m( ) are used by Backend_T whenever it needs to suspend the target's system context or return the target to the state it was in before suspension. Typically, these primitives are used before performing a memory operation like Gopher or checksum.
// mandatory helper methods
virtual int fdGet_m ();
// State management
virtual UINT32 halt_m ();
virtual UINT32 unhalt_m ();
Eventually, you will provide whatever vendor-specific helper methods and data are needed to implement your back-end class, such as Ace_T::eventCallBack( ), which is used to handle target events.
...
// handles asynchronous events in the ACE API
static void eventCallBack (ACE_ConnectionHandle, ACE_Event *,
void *);
...
};
// End of class Ace_T
/////////////////////////////////////////////////////////////////////////
#endif /* #ifndef __INCacecpu32Backendh */
The back-end methods are implemented in acecpu32Backend.cpp. Initially, provide stubs for these methods that log a message to the console when they return successfully. This allows you to validate that the Tornado framework can successfully invoke methods in the new back end before you have coded all the methods. For a discussion of how to implement the mandatory and optional methods, see 2.4.4 Implementing Mandatory Member Functions and 2.4.5 Implementing Optional Member Functions.
/* acecpu32Backend.cpp - implements back end for ACE's SuperBDM */ /* includes */ ...
The constructor call has the same prototype as the acecpu32Init( ) routine and the Backend_T constructor.
Ace_T::Ace_T
(
char * tgtName,
TGT_OPS * pTgtOps,
BKEND_INFO * pBkendInfo
)
Because Ace_T is derived from Backend_T, whenever an Ace_T object is allocated, Backend_T's constructor is called first. It is a good idea to include the call to Backend_T's constructor in an initializer list as a reminder of this fact, to improve performance, and to make sure the correct Backend_T constructor is called. Also, include any aggregate objects used in Ace_T, such as event queues and flags.
:
Backend_T (tgtName, pTgtOps, pBkendInfo)
{
Backend_T's constructor initializes the generic information in the TGT_OPS structure. It also initializes BKEND_INFO. In other words, it defines what functions the target server should invoke to perform the various back-end operations. (See The BKEND_INFO Structure and 2.2.2 Back-End Functions.) See installDir/host/src/tgtsvr/backend/bedk/backend.cpp for functions Backend_T initializes.
Ace_T must initialize the other information in the TGT_OPS structure. Note that when event handling is implemented, the constructor calls Ace_T::fdGet_m( ) to determine which event file descriptor the target server should monitor for events on the target. Initially, since event handling has not yet been implemented, you should store NONE in tgtEventFd. A new Tornado back-end type was specified by defining TGT_LINK_BDM_ACE in tgtlib.h.
...
pTgtOps->tgtConnected = FALSE;
pTgtOps->tgtEventFd = NONE; // Record event fd.
pTgtOps->tgtLink.name = "ACE SuperBDM BDM Mode 1.0.1";
pTgtOps->tgtLink.type = TGT_LINK_BDM_ACE;
pTgtOps->tgtLink.speed = param;
// Log diagnostic message
WPWR_LOG_MSG ("Ace_T::Ace_T( ) : succeeded!\n");
}
Ace_T::~Ace_T ()
{
// Log diagnostic message
WPWR_LOG_MSG ("Ace_T::~Ace_T( ) : succeeded!\n");
}
Finally, you need to provide stubs for the mandatory back-end methods. To validate the back-end framework, it is helpful if these methods log a message and return the appropriate value to indicate success. Back-end methods have three possible return values. You may find it helpful to implement the three functions shown below so that you can see the return value and which method was invoked.
LOCAL UINT32 stubUINT32 (const char * pMethod)
{
WPWR_LOG_MSG ("Ace_T: - method %s.\n", pMethod);
return (WDB_OK);
}
LOCAL BOOL stubBOOL (const char * pMethod)
{
WPWR_LOG_MSG ("Ace_T: - method %s.\n", pMethod);
return (TRUE);
}
LOCAL void stubVOID (const char * pMethod)
{
WPWR_LOG_MSG ("Ace_T: - method %s.\n", pMethod);
}
|
|
|||||||||||||||||||
Use the appropriate stub function for each method's return type to implement the remaining mandatory methods. For example, Ace_T::tgtPing( ) would be implemented as follows:
UINT32 Ace_T::tgtPing_m (void)
{
return (stubUINT32 ("tgtPing_m ( )"));
}
The only function besides Ace_T's constructor you should implement without the stub functions is the Ace_T::tgtConnect_m( ) method. This method initializes WDB_TGT_INFO, which describes the target's configuration.
UINT32 Ace_T::tgtConnect_m (WDB_TGT_INFO * pWdbTgtInfo)
{
WPWR_LOG_MSG ("Establishing ACE SuperBDM connection... ");
// XXX - this information should be read from the $WIND_TGT_INFO
// file. Using hard-coded literals for now.
First, record information about the debug agent, in this case the new emulator back end. agentInfo.mtu specifies the maximum amount of data that can be sent or received by the agent. agentInfo.mode is always set to WDB_MODE_EXTERN for a system-level debug agent like our emulator; this value is defined in wdb.h.
pWdbTgtInfo->agentInfo.agentVersion = "ACE BDM 1.0.1";
pWdbTgtInfo->agentInfo.mtu = Ace_T::MaxMtu; // XXX
pWdbTgtInfo->agentInfo.mode = WDB_MODE_EXTERN;
|
|
|||||||||||||||||||
Next, describe the real-time operating system supported. At present only VxWorks is supported. Possible values for rtInfo.cpuType are defined in installDir/host/include/cputypes.h. Set the value of rtInfo.endian to 1234 or 4321 for big-Endian or little-Endian targets, respectively.
pWdbTgtInfo->rtInfo.rtType = WDB_RT_VXWORKS;
pWdbTgtInfo->rtInfo.rtVersion = "5.3";
pWdbTgtInfo->rtInfo.cpuType = CPU32;
pWdbTgtInfo->rtInfo.hasFpp = FALSE;
pWdbTgtInfo->rtInfo.hasWriteProtect = 0;
pWdbTgtInfo->rtInfo.pageSize = 0xffffffff;
/* The CPU32 target is always Big Endian */
pWdbTgtInfo->rtInfo.endian = 1234;
pWdbTgtInfo->rtInfo.bspName = "ACE SuperBDM BDM Emulator";
pWdbTgtInfo->rtInfo.bootline = NULL;
|
|
|||||||||||||||||||
The target server invokes Backend_T::tgtConnect_m( ) to perform any generic target connection work which may be needed. This function parses the target information configuration file by invoking Backend_T::tgtInfoGet_m( ). See the source code in backend.cpp for more information on Backend_T::tgtInfoGet_m( ).
if (Backend_T::tgtConnect_m (pWdbTgtInfo) != WDB_OK)
{
WPWR_LOG_ERR ("Backend_T::tgtConnect_m () failed.\n");
return (WDB_ERR_PROC_FAILED);
}
WPWR_LOG_MSG ("succeeded.\n");
return (WDB_OK);
}
In order to use the BEDK library you must build this library before building the back end. A makefile and source code for the BEDK are provided in the BEDK directory, installDir/host/src/tgtsvr/backend/bedk. The makefile is designed to be host-independent to facilitate porting the BEDK to hosts that are not SunOS 4.1.3.
Once the BEDK library is built, create a makefile to build the new back end. Use the makefile provided for acecpu32 as an example. After the usual comments, define the necessary suffixes to build a back-end DLL on your host platform from C++. Inference rules are already defined in the makefile fragments provided by Tornado, but you should define any extra macros which are needed for the back end. The ACE_XXX macros specify the location of the ACE C API library and header files.
# Makefile - for acecpu32 backend ... .SUFFIXES: .cpp .so .sl ACE_BASE = /folk/bss/sig/bdm/ace/api/aceapi_1.1 ACE_LD_FLAGS = -L$(ACE_BASE)/SunOS/lib -lACE68K ACE_INC = -I$(ACE_BASE)/include
EXTRA_CFLAGS is a macro provided by the Tornado environment; it is used to specify extra options for the compiler. In this example, the extra option is used to define a macro to specify the CPU type used by the ACE emulator. Also include the makefile stubs provided by Tornado, which define standard macros and rules for building host applications:
EXTRA_CFLAGS = -DACETARGET_68K ... include $(WIND_BASE)/host/include/make/generic.mh include $(WIND_BASE)/host/include/make/$(HOST).mh
Because the BEDK library uses Rogue Wave's Tools.h++ library, you must define the following macros which specify where Tools.h++ is installed:
RW_ROOT = /vobs/devtools/rogue/$(HOST) RW_INC = -I$(RW_ROOT) RW_LIB = $(RW_ROOT)/lib/librwtool.a RW_LD_FLAGS = -L/vobs/devtools/rogue/$(HOST)/lib -lrwtool
Next, define INCLUDES to specify the include files location. Define BKEND_OBJS to be the list of objects that should be built and linked into the new back end:
INCLUDES = $(WIND_INC) $(WIND_SHARE_INC) $(ACE_INC) $(RW_INC) \
-I$(WIND_BASE)/share/src/agents/bedk \
-I$(GNU_ROOT)/lib/g++include
...
BKEND_OBJS = acecpu32.o acecpu32Backend.o event.o
FULL_BKD_OBJS = $(patsubst %.o, $(HOST)/%.o, $(BKEND_OBJS))
...
FULL_BKD_OBJS causes the object files to be placed in a subdirectory named after your hostType (on UNIX, the WIND_HOST_TYPE environment variable, for example, sun4-sunos4).
Specify the libraries to be linked with the back end, including their path names. The Tornado makefile stub defines a macro gnu_ROOT, which specifies the root of the tree containing the GNU ToolKit used to build the back end. You may need to redefine it for your configuration. If you forget to link a required library with the back end, the target server will crash when it loads the back end. An error message will state which symbol was unresolved. Run c++filt or an equivalent tool to demangle the symbol; you can then use nm to determine which library contains that symbol and link the library with the back end.
BKEND_LIB_EXTRA = \
-L../bedk \
-lbedk \
$(ACE_LD_FLAGS) \
$(RW_LD_FLAGS) \
-L$(gnu_ROOT)/lib \
-lg++ \
-liostream \
-L$(gnu_ROOT)/lib/gcc-lib/sparc-sun-sunos4.1.3_U1/2.6.3/ \
-ldl -lc -lgcc
Specify the name of the back end using SH_BKEND_OBJS. Then use LOCAL_CFLAGS to define the local compiler options: -DPORTABLE specifies portable versions of host libraries, -DHOST specifies host versions of header files, and $(DYN_LK_FLAGS) sets the options for compiling a DLL.
SH_BKEND_OBJS = acecpu32.$(SHLIB_EXT)
...
LOCAL_CFLAGS = -DPORTABLE -DHOST $(DYN_LK_FLAGS) -fno-builtin \
-g -fno-inline
...
Finally, there is a target rule and an inference rule to build the back-end DLL:
default:lib objdircre $(SH_BKEND_OBJS)
%.$(SHLIB_EXT):$(FULL_BKD_OBJS)
$(SHARED_LD) $(SHARED_LDFLAGS) -o$(SH_BKEND_LIB)/$*.$(SHLIB_EXT) \
$(BKEND_OBJS) $(BKEND_LIB_EXTRA) $(BKEND_XDR_OBJS)
...
include $(WIND_BASE)/host/include/make/generic2.mh
...
Once your makefile is complete, build the skeleton back end with make.
After you have built the back end, the next step is to invoke the target server. Invoke the target server using Tornado's Launch tool, or enter:
% tgtsvr -V -B acecpu32 \ -core $WIND_BASE/target/config/ace360/vxWorks -A hostNameOfEmulator
where -V enables verbose diagnostic output, -B specifies which back end to use, -core specifies the path to the VxWorks image loaded on the target, -A causes all of VxWorks' symbols to be loaded into the target server symbol table (this flag is optional), and hostNameOfEmulator is the emulator's host name.
If you do not have a VxWorks image for the target board, you can use the following instead:
% tgtsvr -V -B acecpu32 -f a.out hostNameOfEmulator
where -f specifies the object module format (OMF) to use. Use the same OMF which Wind River uses for your target architecture. For more information on the target server and its options see the reference pages and the Tornado User's Guide: Getting Started.
If you are using UNIX and fail to link all the necessary libraries into the back end, the target server crashes. (This problem will not occur under Windows because Microsoft Visual C++ will generate error messages for unresolved externals during the link phase.) The UNIX error message is similar to the following:
% tgtsvr -V -B acecpu32 \
-core $WIND_BASE/target/config/est360/vxWorks -A myTarget
tgtsvr (myTarget@acheron): Tue May 7 12:26:10 1996
Attaching backend... ld.so: Undefined symbol: ___builtin_new
To solve this problem, you need to determine which library implements the undefined symbol, ___builtin_new. You will find nm invaluable for solving this problem, because it displays the symbols in a module. If the undefined symbol is a mangled name, use c++filt to convert the name to an unmangled name to make your search easier.
A side effect of the target server's crash is that the target server does not unregister with the registry daemon, wtxregd. You can confirm this using the registry status command, wtxreg:
% wtxreg
Registry for acheron:
Name Arch Mb #tools User Idle
-------------------- ------------- ------ ------ --------- ------
myTarget@acheron DOWN
You cannot restart a target server with the same name until you clean up the registry. To do so, use the wtxtcl script unreg, shown in Shutting Down the Target Server on p. 17, or use Launch.
When the back end is correctly linked, invoking the target server should produce the following messages:
tgtsvr (myTarget@acheron): Tue May 7 12:37:27 1996
Attaching backend... succeeded.
Establishing ACE SuperBDM connection... succeeded.
Attaching C++ interface... succeeded.
Attached a.out OMF reader.
Warning: Core file checksums do not match.
Note that the acecpu32 back end does not perform the checksum because it would take too long, given this emulator's low bandwidth memory-read capability. Consequently, the target server logs a warning. This warning will not appear if your back end can perform a checksum, and if it matches the target server checksum of VxWorks' text segment.
Once you have built a back end that the target server can load, use wtxtcl to invoke back-end methods. This validates that tools can use the Tornado framework to invoke back-end methods. A typical test session involves starting the wtxtcl shell, attaching the target server and testing various back-end methods by issuing wtxtcl commands:
% wtxtcl wtxtcl>wtxToolAttach myTarget myTarget@acheron wtxtcl>wtxMemRead 0x0 16 mblk0 ... wtxtcl>exit
If your implementation is successful, the back end logs appropriate messages when you invoke a back-end method. Most WTX Tcl procedures, like wtxMemRead, directly map onto a corresponding back-end method. The first WTX Tcl command which you enter is always wtxToolAttach to connect wtxtcl to a specific target server. Then invoke appropriate WTX Tcl procedures to test the back-end framework.
If a wtxtcl method fails, use installDir/host/include/wtxerr.h to convert the error code into a meaningful message. For example:
wtxtcl>wtxVioWrite 1 -string "asdf" Error: WTX Error 0x100d4
To convert 0x1000d4 into a meaningful value, convert 0xd4 to a decimal value. You should find a corresponding entry in wtxerr.h. You may find it helpful to create a script to do this using grep and bc. Once you have converted the value, you find:
WTX_ERR_AGENT_NO_AGENT_PROC = (WTXERR_BASE_NUM | 212)
Once the back-end framework is validated, you can implement the mandatory member functions. First implement memory and register read and write methods. Once this milestone is achieved, implement the remaining mandatory back-end functions including state management and event handling. Studying the acecpu32 back-end example in parallel with this section will be helpful, especially in understanding the use of the WDB data structures. The required back-end methods are shown in Table 2-1.
|
|
|||||||||||||||||||
|
|
|||||||||||||||||||
|
|
|||||||||||||||||||
The first back-end methods to implement are the methods for reading and writing memory. This section presents a detailed example for the memory-read method. The memory-write method is similar.
When the target server calls Ace_T::memRead_m( ), it passes a pointer to a WDB_MEM_REGION structure describing the region of target memory to be read, and a pointer to a WDB_MEM_XFER structure describing where the data read from the target should be returned.
UINT32 Ace_T::memRead_m
(
WDB_MEM_REGION * pMemRegion,
WDB_MEM_XFER * pMemXfer
)
{
int status;
ACE_OperatingMode oldState;
To check that an access request is for a valid address, Ace_T::memRead_m( ) compares the request to the bounds of target memory, which are stored in the WDB_TGT_INFO structure parsed by Backend_T::tgtInfoGet_m( ).
// Check that memory access is valid
UINT32 aceMemBase = wdbTgtInfo_.rtInfo.memBase;
UINT32 aceMemSize = wdbTgtInfo_.rtInfo.memSize;
if (
((UINT32) pMemRegion->baseAddr < aceMemBase) ||
((UINT32) pMemRegion->baseAddr + pMemRegion->numBytes) >
(aceMemBase + aceMemSize)
)
{
::wpwrLogWarn ("Invalid memory access of %#x bytes at %#x.\n",
pMemRegion->numBytes, pMemRegion->baseAddr);
}
Next, the WDB_MEM_XFER structure, which will hold the result of the memory read, is initialized. The param field is used in a request-dependent manner. In this example, param contains the address of the buffer to store the data in.
// Book keeping for WTX protocol
pMemXfer->source = (WDB_OPQ_DATA_T) pMemRegion->baseAddr;
pMemXfer->numBytes = pMemRegion->numBytes;
pMemXfer->destination = (TGT_ADDR_T) pMemRegion->param;
The target server will not break a memory read request up into several small requests if the initial request is larger than the agentInfo.mtu value specified in the WDB_TGT_INFO data returned by the Ace_T::tgtConnect_m( ) request. Consequently, the back end needs to break up the request if necessary.
// The target server does not break up requests which
// exceed the back end's MTU, so we need to do that here.
TGT_INT_T numLeft; // num bytes left to read.
TGT_INT_T numToRead; // num bytes to read in this iteration.
UINT8 * pTgtAddr; // address to start next read.
UINT8 * pDestAddr; // where to put result of read.
pTgtAddr = (UINT8 *) pMemRegion->baseAddr;
pDestAddr = (UINT8 *) pMemRegion->param;
for
(
numLeft = pMemRegion->numBytes;
numLeft > 0;
numLeft -= Ace_T::MaxMtu
)
{
numToRead = ((numLeft > Ace_T::MaxMtu) ?
(TGT_INT_T) Ace_T::MaxMtu : numLeft);
Next, the back end uses a function in the ACE C API to read memory from the target via the emulator:
status = ::ACE_ReadTargetMemory
(
emulator_,
(ACE_TargetAddress) pTgtAddr,
(void *) pDestAddr,
(uint32) numToRead
);
If the ACE C API request fails, the back end calls Ace_T::wdbErrFigure_m( ) to convert the ACE error code into a WDB error code and log an appropriate error message. If the method's return type is UINT32, the back-end methods must return WDB_OK or a suitable WDB error code, defined in wdb.h.
if (status != ACE_SUCCESS)
{
(void) stateRestore_m (oldState);
return (wdbErrFigure_m ("ACE_ReadTargetMemory ()",
status, WDB_ERR_MEM_ACCES));
}
pTgtAddr += numToRead;
pDestAddr += numToRead;
}
return (WDB_OK);
}
The next step is to rebuild the back end, start the target server, and test the memory-read method. In this example, wtxtcl is used to attach to the target server, read target memory, and display the result. wtxMemRead returns a memory block handle (mblk0 in the example) to provide more efficient memory manipulation. For more information, see the 4. The WTX Protocol.
% wtxtcl wtxtcl> wtxToolAttach myTarget myTarget@acheron-1 wtxtcl> wtxMemRead targetAddress 16 mblk0 wtxtcl> memBlockGet -l mblk0 0xdeadbeef 0xdeadbeef 0xdeadbeef 0xdeadbeef wtxtcl> exit
You may find it useful to create a library of scripts to exercise simple back-end requests. See installDir/host/src/tgtsvr/backend/bedk for examples of such scripts. You can invoke them from wtxtcl with the source command.
The implementation of the methods to read and write registers is analogous to the memory read method. There are three possible sources of confusion about register operations. First, the WDB protocol allows just part of a register set to be accessed. Second, you should use the Wind River-defined register-set structure. Third, register information must be handled in opaque format; in other words, it must have the same byte ordering and alignment as the target. The definition of the register set is in installDir/target/h/arch/archType/regsArchType.h, where archType is the target architecture type.
UINT32 Ace_T::regsSet_m (WDB_REG_WRITE_DESC * pRegWrite)
{
ACE_AllRegisters aceRegSet;
ACE_OperatingMode oldState;
int status; // ACE API return value
Register access is one of the least portable parts of the back end. To handle the register set for your target architecture, you need to define a register-set structure which mimics the definition in regsArchType.h. The ACE emulator supports CPU32 targets, so a 68k register-set type, REG_SET_68K, is declared in acecpu32Backend.h and shown here:
REG_SET_68K wrsRegSet;
char * pWrsRegBuf; // pointer to treat reg set as opaque
Having established the correct register-set structure, perform some sanity checking on the arguments. Note the use of WDB error codes.
if (pRegWrite->context.contextType != WDB_CTX_SYSTEM)
{
return (WDB_ERR_INVALID_CONTEXT);
}
if (pRegWrite->regSetType != WTX_REG_SET_IU)
{
return (WDB_ERR_INVALID_PARAMS);
}
...
CrossWind, the GDB-based source-level debugger, accesses only one register at a time. Consequently, it is important to optimize for the case of reading and writing only one register. The back end API also requires support for reading and writing the complete register set, so acecpu32 includes both cases.
if (pRegWrite->memXfer.numBytes <= 4)
{
uint32 aceRegSize;
ACE_Register whichAceReg; // which register to read.
Next, the register-set method converts the Wind River register identifier, which is a byte offset into the register set, into an ACE register identifier, which is an enumerated type. The Wind River byte offset is stored in memXfer.destination.
status = whichAceRegGet_m (pRegWrite->memXfer.destination,
&whichAceReg, &aceRegSize);
if (status != WDB_OK)
{
return (status);
}
if (whichAceReg == ACE_REG_A7)
{
whichAceReg = ACE_REG_SSP;
}
CrossWind treats the status register as 32 bits: 16 bits of padding plus 16 bits of data. The ACE API treats the status register as 16 bits of data. The appropriate conversion is performed here:
if ((whichAceReg == ACE_REG_SR) &&
(pRegWrite->memXfer.numBytes == 4))
{
UINT8 * pRegWriteVal = (UINT8 *) pRegWrite->memXfer.source;
pRegWriteVal += 2; // Skip padding in WRS's REG_SET.
// memXfer.source contains register information
// in the same representation it would appear in
// target memory (i.e., it is opaque). The
// ACE API expects this information in host byte
// ordering, so we must convert the register value.
*(UINT16 *) pRegWriteVal = FIX_16 (*(UINT16 *) pRegWriteVal);
status = regSetOne_m (whichAceReg, pRegWriteVal);
}
else
{
// memXfer.source contains register information
// in the same representation it would appear in
// target memory (i.e., it is opaque). The
// ACE API expects this information in host byte
// ordering, so we must convert the register value.
UINT32 aceRegBuf = FIX_32 (*(UINT32 *)
pRegWrite->memXfer.source);
A special vendor-specific helper function, Ace_T::regSetOne_m( ), efficiently writes just one register, returning a WDB error code:
status = regSetOne_m (whichAceReg, (UINT8 *) &aceRegBuf);
}
if (status != WDB_OK)
{
return (status);
}
return (stateRestore_m (oldState));
}
// End of writing only one register
Having dealt with the special case of accessing only one register, the Ace_T::regsSet_m( ) now performs the more general case by reading the target's entire register set, modifying the desired registers, and re-writing the register set.
// Read all target registers
status = ::ACE_ReadAllTargetRegisters (emulator_, &aceRegSet);
if (status != ACE_SUCCESS)
{
...
return (wdbErrFigure_m ("ACE_ReadAllTargetRegisters ()",
status, WDB_ERR_PROC_FAILED));
}
// Force ACE register info into WRS data structures (defined in
// $WIND_BASE/target/h/arch/mc68k/regsMc68k.h)
::memset (&wrsRegSet, 0x00, sizeof (wrsRegSet));
// memXfer.source contains register information
// in the same representation it would appear in
// target memory (i.e., it is opaque). The
// ACE API expects this information in host byte
// ordering, so we must convert the register value.
wrsRegSet.dataReg[0] = FIX_32 (aceRegSet.Dx[0]); /* data registers */
wrsRegSet.dataReg[1] = FIX_32 (aceRegSet.Dx[1]);
wrsRegSet.dataReg[2] = FIX_32 (aceRegSet.Dx[2]);
wrsRegSet.dataReg[3] = FIX_32 (aceRegSet.Dx[3]);
wrsRegSet.dataReg[4] = FIX_32 (aceRegSet.Dx[4]);
wrsRegSet.dataReg[5] = FIX_32 (aceRegSet.Dx[5]);
wrsRegSet.dataReg[6] = FIX_32 (aceRegSet.Dx[6]);
wrsRegSet.dataReg[7] = FIX_32 (aceRegSet.Dx[7]);
wrsRegSet.addrReg[0] = FIX_32 (aceRegSet.Ax[0]); /* address registers */
wrsRegSet.addrReg[1] = FIX_32 (aceRegSet.Ax[1]);
wrsRegSet.addrReg[2] = FIX_32 (aceRegSet.Ax[2]);
wrsRegSet.addrReg[3] = FIX_32 (aceRegSet.Ax[3]);
wrsRegSet.addrReg[4] = FIX_32 (aceRegSet.Ax[4]);
wrsRegSet.addrReg[5] = FIX_32 (aceRegSet.Ax[5]);
wrsRegSet.addrReg[6] = FIX_32 (aceRegSet.Ax[6]);
wrsRegSet.addrReg[7] = FIX_32 (aceRegSet.Ax[7]);
wrsRegSet.sr = FIX_16 (aceRegSet.SR);
wrsRegSet.pc = (INSTR *) FIX_32 (aceRegSet.PC);
|
|
|||||||||||||||||||
In the example below, note how memXfer specifies which part of the register set to modify: memXfer.destination specifies the byte offset into the target register set where the new data should be stored; and memXfer.source contains a pointer to an opaque chunk of register data, formatted like the corresponding part of a Wind River register-set structure. For example, if the byte offset is 64 bytes, memXfer.source points to two bytes of padding, followed by two bytes of status-register information, and so on for a CPU32 register set.
// Modify desired registers
pWrsRegBuf = (char *) &wrsRegSet;
::memcpy ((void *) (pWrsRegBuf + pRegWrite->memXfer.destination),
(void *) pRegWrite->memXfer.source,
pRegWrite->memXfer.numBytes);
// Store in ACE's reg set.
aceRegSet.Dx[0] = FIX_32 (wrsRegSet.dataReg[0]); /* data registers */
aceRegSet.Dx[1] = FIX_32 (wrsRegSet.dataReg[1]);
aceRegSet.Dx[2] = FIX_32 (wrsRegSet.dataReg[2]);
aceRegSet.Dx[3] = FIX_32 (wrsRegSet.dataReg[3]);
aceRegSet.Dx[4] = FIX_32 (wrsRegSet.dataReg[4]);
aceRegSet.Dx[5] = FIX_32 (wrsRegSet.dataReg[5]);
aceRegSet.Dx[6] = FIX_32 (wrsRegSet.dataReg[6]);
aceRegSet.Dx[7] = FIX_32 (wrsRegSet.dataReg[7]);
aceRegSet.Ax[0] = FIX_32 (wrsRegSet.addrReg[0]); /* address regs */
aceRegSet.Ax[1] = FIX_32 (wrsRegSet.addrReg[1]);
aceRegSet.Ax[2] = FIX_32 (wrsRegSet.addrReg[2]);
aceRegSet.Ax[3] = FIX_32 (wrsRegSet.addrReg[3]);
aceRegSet.Ax[4] = FIX_32 (wrsRegSet.addrReg[4]);
aceRegSet.Ax[5] = FIX_32 (wrsRegSet.addrReg[5]);
aceRegSet.Ax[6] = FIX_32 (wrsRegSet.addrReg[6]);
aceRegSet.Ax[7] = FIX_32 (wrsRegSet.addrReg[7]); // Ignored in ACE API
// Must set SSP instead
aceRegSet.SSP = FIX_32 (wrsRegSet.addrReg[7]); // This assumes use
// of vxWorks!
aceRegSet.SR = FIX_16 (wrsRegSet.sr);
aceRegSet.PC = FIX_32 ((uint32) wrsRegSet.pc);
status = ::ACE_WriteAllTargetRegisters (emulator_, &aceRegSet);
if (status != ACE_SUCCESS)
{
...
return (wdbErrFigure_m ("ACE_WriteAllTargetRegisters ()",
status, WDB_ERR_PROC_FAILED));
}
else
{
return (WDB_OK);
}
}
Tornado expects to receive event information (including exception information) and register information in target byte order. Register contents should be transferred in opaque fashion (in other words, bit for bit as they appear in the registers).
Finish implementing and testing the methods for reading and writing memory and registers. Use your emulator's tools to verify that wtxtcl commands correctly operate the emulator.
By implementing the read and write memory and register methods, you demonstrated that the new back end can actually operate the emulator. The next step is to add support for basic context management: setting breakpoints, suspending and resuming the system, and so on. Follow the same process of adding functionality and testing it with wtxtcl and your emulator's tools.
The key difference in this step is that you need to manage state: is the target running? do you need to stop it to perform the operation? We first examine the methods for acecpu32 back-end state management in detail. Then we discuss caveats for the other context management methods.
The ACE back end uses Ace_T::stateBDM_m( ) and Ace_T::stateRestore_m( ) to manage the target state. The first method is used to halt the system by putting the target in background debug mode or BDM6 . The second method is used to return the system to the state it was in before it was halted. Once these methods are implemented, the functionality must be made available to the Backend_T class by implementing the mandatory member functions halt_m( ) and unhalt_m( ); this allows the methods implemented in Backend_T to manage target state.
The examples step through Ace_T::stateBDM_m( ) in detail. When this method is called, it is passed a variable where it can record the old state. This variable is passed to Ace_T::stateRestore_m( ), which restores the system to that state. This implementation supports nested calls of these state management methods. (Note: the argument to Ace_T::stateBDM_m( ) is a reference!)
UINT32 Ace_T::stateBDM_m (ACE_OperatingMode & oldState)
{
int status;
An ACE C API method is used to determine the target state. Based on this state, Ace_T::stateBDM_m( ) performs the appropriate operation.
oldState = (ACE_OperatingMode) ::ACE_GetOperatingMode (emulator_);
switch (oldState)
{
case ACE_MODE_BDM:
status = ACE_SUCCESS;
break;
case ACE_MODE_RUN: /* Running */
case ACE_MODE_TRC: /* Non-realtime trace */
status = ::ACE_StopTarget (emulator_);
if (status != ACE_SUCCESS)
{
return wdbErrFigure_m ("ACE_StopTarget ()",
status, WDB_ERR_PROC_FAILED);
}
break;
case ACE_MODE_ERR: /* Error */
status = ::ACE_Initialize (emulator_, ACE_INN_COMMAND);
if (status != ACE_SUCCESS)
{
return wdbErrFigure_m ("ACE_Initialize ()",
status, WDB_ERR_PROC_FAILED);
}
break;
case ACE_MODE_NOCONNECT: /* Not connected... */
case ACE_MODE_SIM: /* Simulation mode */
case ACE_MODE_PFA: /* Performance */
status = ACE_FAILURE;
WPWR_LOG_ERR ("Ace_T::stateBDM_m () : invalid state %s.\n",
::ACE_OperatingModeImage (oldState));
break;
default:
status = ACE_FAILURE;
WPWR_LOG_ERR ("Ace_T::stateBDM_m () : invalid mode %d.\n",
oldState);
break;
}
return (wdbErrFigure_m ("Ace_T::stateBDM_m ()", status,
WDB_ERR_AGENT_MODE));
}
The function Ace_T::stateRestore_m( ) returns the system to its previous state by following a similar pattern.
You must also implement halt_m( ) and unhalt_m( ), which wrap stateBDM_m( ) and stateRestore_m( ). Note that oldTgtState_ is a data member of Ace_T:
UINT32 Ace_T::halt_m ()
{
UINT32 status;
status = stateBDM_m (oldTgtState_);
return (status);
}
Now that you have implemented state management, you can implement the other context-management methods. Remember to add state management to the memory and register methods you have already written! Here are the key considerations to be aware of when implementing these methods:
See acecpu32Backend.cpp for a sample implementation.
Again, use wtxtcl to test the context-management methods. Download some code to the target; if possible, download VxWorks using existing emulator tools. Otherwise, download code which performs a process such as spinning in a loop incrementing a counter. Try setting breakpoints, continuing, stepping, etc. Make sure that the program counter changes appropriately.
The target server is notified of events asynchronously by activity on the event file descriptor specified in the TGT_OPS structure's tgtEventFd field. The target server monitors this file descriptor via select( ). When the file descriptor becomes active, the target server invokes eventGet_m( ) to get the WDB_EVT_DATA structure describing the event. It then clears the event by calling eventPendingClear_m( ). Typically, the event file descriptor is the socket file descriptor associated with a network connection to the emulator. In any case, the back end must implement the fdGet_m( ) method which returns an event file descriptor for the target server to monitor.
When an event occurs, the back end needs to capture the WDB_EVT_DATA information associated with the event and store it on a queue, because more than one event could occur before the target server handles them. The target server retrieves this data by calling eventGet_m( ).
When necessary, the target server will explicitly query the back end to determine if an event has occurred by calling evtPending_m( ). This method should return TRUE if an event has occurred and has not yet been processed by the target server.
Whenever an event occurs, the back end should capture the event's information in a WDB_EVT_DATA structure and store this information for the target server. The acecpu32 back end manages target information by using a call-back provided by the ACE C API to capture event information and put it on the event queue, Ace_T::eventQueue_. When a target event occurs, the ACE API invokes the call-back. The call-back constructs an Event_T object, which maintains the WDB_EVT_DATA information for the event, and puts it on the event queue. Note that Ace_T::eventCallBack( ) is a static member function so that the ACE C API can call it.
void Ace_T::eventCallBack
(
ACE_ConnectionHandle emulator,
ACE_Event * pEvent,
void * pData
)
{
Ace_T::pTheAceBkEnd_s( ) provides a safe way to get a pointer to the Ace_T back end, without needing to pass the this pointer around.
// Get a back end pointer
Ace_T * pBackend = pTheAceBkEnd_s ();
The Event_T constructor, shown below, captures the event information and creates the right kind of event.
// Create an appropriate Event_T object
Event_T * pWdbEvent = new Event_T (pEvent);
// Queue the event
pBackend->eventQueuePut_m (pWdbEvent);
}
The Rogue Wave Tools.h++ library makes the implementation of the queue mechanism easy. The event queue is a RWSlistCollectablesQueue and Event_T is derived from RWCollectable, so it is not necessary to write any code to implement and debug the event queue. (See Figure 2-7 and Figure 2-8.)
The Event_T constructor captures the event information by determining what kind of event occurred, gathering the necessary event data, and storing it:
Event_T::Event_T (ACE_Event * pEvent)
:
RWCollectable ()
{
// Transfer pEvent into WDB_EVT_DESC
switch (pEvent->any.type)
{
case ACE_BREAKPOINT:
bpEventMake_m (pEvent);
break;
case ACE_SIGNAL:
signalEventMake_m (pEvent);
break;
case ACE_MODECHANGE:
modeChangeEventMake_m (pEvent);
break;
default:
wdbEvent_.evtType = WDB_EVT_NONE;
WPWR_LOG_ERR ("Invalid ACE event type %#x.\n",
pEvent->any.type);
break;
}
}
|
|
|||||||||||||||||||
Exception events are more complicated to handle than other types, because it is necessary to provide information about the exception stack frame in the event data. The easiest way to gather exception information is to install an exception hook on the target to capture the data, notify the host, and suspend the system. For CPU32 microprocessors, this can be implemented using the special bgnd instruction which puts the target in background mode. If a similar notification scheme is not available on your host, you can set a breakpoint on your exception hook and, on every breakpoint event, check to see if it was triggered by the breakpoint in the exception hook.
The acecpu32 back end uses an approach based on the bgnd instruction. First, a special library, bdmExcLib, is linked with VxWorks; in the usrInit( ) startup code, bdmExcLibInit( ) is called to initialize the library and install the exception hook. When the bgnd instruction is executed, the ACE API generates an ACE_SIGNAL event, and the back end builds the appropriate exception event.
A global variable, bdmExcInfo, is used to store information about the exception so that the back end can easily locate this information and upload it to the host for processing.
BDM_EXC_INFO bdmExcInfo = {0, 0, 0, FALSE};
...
STATUS bdmExcLibInit (void)
{
if (bdmIsInitialized)
return (ERROR);
if (_func_excBaseHook != NULL)
return (ERROR);
_func_excBaseHook is a hook to allow a developer to run code whenever an exception occurs. Whatever function's address is stored in it will be invoked by VxWorks' exception handler whenever the exception occurs. With the acecpu32 back end, the VxWorks exception-handling code invokes bdmExcHook( ) whenever an exception occurs, which gathers the necessary information about the exception for the back end.
/* Install exception hook */
_func_excBaseHook = bdmExcHook;
bdmIsInitialized = TRUE;
return (OK);
}
LOCAL int bdmExcHook
(
int vec,
char * pESF,
WDB_IU_REGS * pRegs
)
bdmExcInfo.bdmIsException is equal to TRUE only if the bgnd instruction is executed by the hook for gathering exception information. We gather the other necessary information about the exception, suspend the system, and notify the back end of the exception by executing the bgnd instruction. When we resume the system, we clear the bdmExcInfo.bdmIsException flag so that an exception can be differentiated from the execution of a user's bgnd instruction:
{
bdmExcInfo.bdmIsException = TRUE;
bdmExcInfo.excVector = vec;
bdmExcInfo.pESF = pESF;
bdmExcInfo.pIuRegs = pRegs;
__asm__ (".word 0x4afa"); /* `BGND' */
bdmExcInfo.bdmIsException = FALSE;
/* Return FALSE so that VxWorks' exception handler will continue */
/* processing the exception. */
return (FALSE);
}
Once an exception has occurred, until execution is resumed on the target, requests for register information should return the register information pointed to by pRegs rather than the current CPU register values. For an example, see Ace_T::regsGet_m( ) in acecpu32.cpp.
Once event handling has been implemented, CrossWind, Tornado's source-level debugger, should operate with the new back end. First test the back end's new functionality using wtxtcl. (Note: to register wtxtcl for an event use the wtxRegisterForEvent command. For more information, see 4. The WTX Protocol.) Then bring up CrossWind.
|
|
|||||||||||||||||||
(gdb) target wtx targetServerName
(gdb) tcl wtxTimeout 6000
The tcl command causes CrossWind to pass the remainder of the line to the wtxtcl interpreter. 60 is the default timeout.
(gdb) attach system
(gdb) set $pc=sysInit
(gdb) b usrInit (gdb) b sysHwInit (gdb) ...
Example 2-2: Spawning a Demo Task
/* usrConfig.c - user-defined system configuration library */
...
extern void usrLoop (int arg1, ...);
usrRoot
(
char * pMemPoolStart, /* start of system memory partition */
unsigned memPoolSize /* initial size of mem pool */
)
{
...
#ifdef INCLUDE_SHELL
...
#endif /* INCLUDE_SHELL */
/* XXX - for BDM testing */
taskSpawn ("uLoop", 200, 0, 10000, (FUNCPTR) usrLoop,
0,0,0,0,0,0,0,0,0,0);
}
/* XXX - for BDM testing */
SEM_ID loopSemId;
int loopCntGlobal;
char * loopString = "XXXThis is a string!\n";
int loopDelay = 1;
BOOL causeExc = FALSE;
void usrCauseExc (void)
{
volatile int top = 1;
volatile int bottom = 0;
top = top / bottom; /* generate exception */
}
void usrLoop (int arg1, ...)
{
static int loopCnt = 0;
volatile int ix = 0;
loopString++;
loopString++;
if (loopSemId == NULL)
loopSemId = semCCreate (SEM_Q_PRIORITY, 1);
FOREVER
{
taskDelay (loopDelay);
printf ("\n...I am alive...Count = %d\n", ix);
ix++;
loopCnt = ix;
loopCntGlobal = ix;
semGive (loopSemId);
if (causeExc)
{
usrCauseExc ();
}
}
}
Do not forget to compile VxWorks with the -g flag to generate debugging symbols for the system startup code.
Since VxWorks is a fully linked module, the default load flags for the CrossWind load command are not appropriate for loading it. The correct command from the CrossWind command line is:
(gdb) wtx-obj-module-load LOAD_GLOBAL_SYMBOLS|LOAD_FULLY_LINKED vxWorks
To simplify the process, you can create a new gdb command by placing the following file in $HOME/.wind/gdb.tcl:
# gdb.tcl - User customizations to CrossWind's GDB engine
#
# modification history
# --------------------
#
# 01a,07nov96,bss written.
#
#
# loadf - load a fully linked object module
#
proc loadf (file) {
wtxObjModuleLoad LOAD_GLOBAL_SYMBOLS|LOAD_FULLY_LINKED $file
}
# register the new command with GDB
gdb tclproc loadf loadf
The basic back-end functionality is now operational. If you have the resources, you may decide to support the optional methods serviceCall_m( ), directCall_m( ), contextCreate_m( ), contextKill_m( ), and funcCall( ). You may also decide to implement some of the memory operations provided by Backend_T, such as memScan_m( ) or memChecksum_m( ), particularly if your emulator provides a faster way of performing these operations than Backend_T's generic implementation.
Dynamic loading of object modules onto the target requires, in addition to a high bandwidth memory access capability, support for cacheTxtUpdate_m( ) and directCall_m( ). The required emulator support for cacheTxtUpdate_m( ) may not be available. Implementing directCall_m( ) is complex: it involves saving the processor's state, setting up a stack for the call, performing the call, notifying the host that the call has completed, and then returning the system to its previous state. Consequently, most emulator back ends do not support dynamic loading.
Memory access is usually the biggest performance bottleneck. Everything possible should be done to optimize the speed of memory reads and writes. Also, optimize the register read and write operations for the case of a single register. Finally, if your emulator supports primitives for performing common memory operations such as checksum, scanning for a pattern, and filling a block of memory with a pattern, over-ride Backend_T's implementation and use methods optimized for your emulator.
1: The Tornado implementation is designed to work in both UNIX and Windows environments; thus, in most cases the terms can be used interchangeably. In this chapter, DLL refers to both Windows DLLs and UNIX shared libraries unless an explicit distinction is made.
2: The current implementation of this protocol is based on Sun Microsystems RPC 4.0, which can be implemented on virtually any transport layer.
3: On UNIX hosts and on Windows host when you use the command line, the environment variable WIND_HOST_TYPE records the host type. (For example, on a Sun-4 running Solaris 2.5.1, WIND_HOST_TYPE is sun4-solaris2; see the Tornado User's Guide: Getting Started.)
4: For more information on RPC, please see the O'Reilley book, Power Programming with RPC.
5: The rpccore library can be obtained when you request the Back-End Developer's Kit.
6: Many microprocessors provide a special debug state which allows a debugging tool to take advantage of on-chip debug functionality. For the CPU32 this mode is called BDM. The microprocessor is halted and put into a special state so that you can perform debug operations.