New and delete operators

Heap memory, or free storage, allocation and deallocation are provided by the operators new and delete. The new operator takes one argument, the size of the object type, and allocates the amount of memory required by that type, returning the location of the memory allocated. The duration of storage for p and pc is until delete is called to destroy them, thus they will exist outside the block they were defined in. p variable contains the address of allocated heap p out of scope but the...

TwoPhase Construction Critical Information

The following line of code allocates an object of type CExample on the heap and sets the value of foo accordingly The code calls the new operator, which allocates a CExample object on the heap if there is sufficient memory available. Having done so, it calls the constructor of class CExample to initialize the object. As Chapter 5 describes, the cleanup stack can be used to ensure that the CExample object is correctly cleaned up in the event of a leave. But it is not possible to do so inside the...

DLLs in ROM and RAM

DLLs in ROM are not actually loaded into memory either, but execute in place in ROM at their fixed address. DLLs running from RAM are loaded at a particular address and reference counted so they are unloaded only when no longer being used by any component. When a DLL runs from RAM, the address at which the executable code is located is determined only at load time. Loading a DLL from RAM is different from simply storing it on the internal RAM drive, because Symbian OS copies it into the area of...

Reuse advantages and disadvantages

Aggregation, composition and inheritance are primarily used to remove redundancies, in particular the repetition of the same code often implemented differently in different classes or programs. In the analysis of a problem, if a group of concepts share common properties and behavior they are good candidates for abstraction, in this case, the separation of the common functionality. The amount of commonality dictates the degree of code reuse and the purpose of the relationships, that is, whether...

Message queues

In contrast to the connection-oriented nature of client-server IPC, message queues RMsgQueue offer a peer-to-peer, many-to-many communication mechanism. Message queues provide a way to send data messages to interested parties without needing to know whether any thread is listening or the identity of a recipient in effect, messages are sent to the queue rather than to any specific recipient. A single queue can be shared by many readers and writers. A message is an object that is placed into a...

Unique Identifier UID

As discussed in Chapter 10 with respect to DLLs, UIDs are used to uniquely identify a binary file when it executes on Symbian OS. There are three UIDs for any particular executable, which are built into the first 12 bytes of any Symbian OS file to identify it the first UID UID1 is generated automatically by the Symbian OS build tools, according to the targettype of the file stated in the MMP build file, for example, DLL or EXE the second UID UID2 is specified for certain target types, to...

Configuring and connecting sockets

After a socket is open, it is configured differently depending on whether the socket is connectionless or connection-oriented. Connectionless sockets are configured with a local address and then use special versions of I O calls that include the remote socket address. The local address is assigned to a connectionless socket using the RSocket Bind method. Thus, before it is possible to send or receive data over an unconnected or datagram socket, a call to Open followed by Bind must occur. Once...

Shared library and polymorphic interface DLLs

Dynamic link libraries, DLLs, are libraries of compiled C code that may be loaded into a running process in the context of an existing thread. In Symbian OS there are two main types of DLL shared library static-interface DLLs and polymorphic interface plug-in DLLs. A shared library DLL implements library code that may be used by multiple components of any type, that is, other libraries or EXEs. The filename extension of a shared library is .dll - examples of this type on Symbian OS are the user...

Inheritance composition and aggregation

There are fundamentally two kinds of relationship between classes in the C support of OOP is-a or inheritance, and ''has-a'' or composition. Composition can be further divided into strong and weak or aggregation. W950i is a mobile phone and is a music player A Smartphone device has an operating system N91 and W950i are both Smartphones, Nseries is a product line N91 and W950i are both Smartphones, Nseries is a product line The table above contains some examples of these relationships S60 is...

Active object class construction

On construction, classes deriving from CActive must call the protected constructor of the base class, passing in a parameter to set the priority of the active object. Like threads, all active objects have a priority value to determine how they are scheduled. The reason for this is as follows. When the asynchronous service associated with the active object completes, it generates an event. The active scheduler detects events, determines which active object is associated with each event, and...

Caged file paths sys

The sys bin directory is where all program binaries executables reside. Executables built into the mobile phone ROM run from z sys bin, while installed software is written into the sys bin directory of the c drive or the equivalent directory on removable media. To check for tampering of executables installed on removable media, since the binaries could potentially be modified by removing the card from the phone, c sys hash is used to store secure hashes of the binaries. Only code within the TCB...

Versions of Symbian OS which support writable static data

Symbian OS supports global writable static data in EXEs on all versions and handsets. However, writable static data cannot be used in DLLs built for target hardware for Symbian OS versions 8.1a, 8.0a or earlier, that is, those versions of Symbian OS which contain EKA1. This is because, on that version of the platform, DLLs have separate areas for program code and read-only data but do not have an area for writable data. Symbian OS versions 8.0b, 8.1b, 9.0 and beyond do now support the use of...

Blocked thread

A thread can block, and thus prevent an application's UI from remaining responsive, for a variety of reasons including the following A call to User After , which blocks a thread until the time specified as a parameter has elapsed Incorrect use of the active scheduler. Before the active scheduler is started, there must be at least one asynchronous request issued, via an active object, so that the thread's request semaphore is signaled and the call to User WaitForAnyRequest completes. If no...

Untrusted software

The trustworthiness of software that is not signed, or is ''self-signed'' that is signed, but not by one of the Symbian Trusted Authorities , cannot be determined. This means that it must be considered untrusted by Symbian OS. It does not mean that the software is necessarily malicious or worthless, however. There are many useful operations that can be performed on a phone without calling system services which would require a certain level of privilege. Symbian OS only makes security checks...

Creating and installing the active scheduler

Most threads running on Symbian OS have an active scheduler, which is usually created and started implicitly by a framework for example CONE for the GUI framework . However, server code must create and start an active scheduler explicitly before active objects can be used. Likewise, console-based test code may not use active objects directly itself, but must create an active scheduler in its main thread if it depends on components which use active objects. The code to do this is as follows...

File server session class

The file server provides the basic services that allow calling code to manipulate drives, directories and files. In order to use the file server, a caller must first create a file server session, represented by an instance of the RFs class. The general pattern for connecting to the file server, using the session to create and use an RFile subsession described in more detail below , and then releasing both, is shown in the following code example. User LeaveIfError fs.Connect Connect the session...

What causes a leave

A typical leaving function is one that performs an operation that is not guaranteed to succeed, such as allocation of memory, which may fail under low memory conditions, or creation of a file when there is insufficient disk space. A leave may occur when a leaving function is called, or by an explicit call to a system function that causes a leave. A function may leave if it Calls code that may leave without surrounding that call with a TRAP harness functions which may leave must be named to...

What is a leave

Rather like C exceptions, a leave suspends code execution at the point the leave occurs and resumes execution where the leave is trapped. The trap harness in Symbian is a TRAP macro - the leave sets the stack pointer to the context of the TRAP and jumps to that location, restoring the register values. It does not terminate the flow of execution. The use of TRAP is described in more detail in Section 5.4. The TRAP harness and the system function which causes the leave User Leave may be...

Multiple inheritance and abstract base classes

The use of multiple inheritance is seen as controversial in general C and is definitely not encouraged in Symbian OS C except under specific circumstances. When a derived class derives from two bases, member name ambiguities can arise in the case of diamond inheritance, where the base classes both derive from a common base, there is a complete duplication of data. The class now has two versions of B iVal. Symbian OS C uses multiple inheritance purely as an interface inheritance mechanism. These...

Preprocessor

The preprocessor parses through the source file scanning for the directives. A directive starts with the hash sign, . Includes another file, usually header files . h Allows the user to define a macro. e32def.h contains the most commonly used Symbian OS macros. May be used to turn code on and off, typically in conditional compilation The preprocessor will expand all the macros in the code. This also entails expanding the include directive which adds the specified file to the current source file...

Exporting functions from a DLL

A shared library DLL provides access to its APIs by exporting its functions so that separate executables that is, DLL or EXE code compiled into a separate binary component can call them. This makes the functions public to other modules by creating a .lib file, which contains the export table to be linked against by the calling code. On Symbian OS, every function to be exported should be marked in the class definition in the header file with the macro import_c. The client code will include the...

LIT macro

The _LIT macro is preferred for Symbian OS literals, since it is the more efficient type. It has been used in the sample code throughout this chapter, typically as follows _LIT KFieldMarshalTait, Field Marshal Tait KFieldMarshalTait can then be used as a constant descriptor, for example to write to a file or display to a user. The _LIT macro builds a named object KFieldMarshalTait of type TLitC16 into the program binary, storing the appropriate string in this case, Field Marshal Tait . The...

Overloading

Overloading allows a developer to provide more than one version of a function or operator within the same scope. Operator overloading allows user-defined types to behave in the same manner as integral types. Arguably, overloading provides a loose ad-hoc form of polymorphism via the same method having different types, but it has no claim to true OO polymorphism and is seen as a notational convenience. Constructor Foo int n 0 iVal n int Get const return iVal Differentiate on parameter void Get...

When to leave a pointer on the cleanup stack

In a function, if a pointer to an object is pushed onto the cleanup stack and remains on it when that function returns, the Symbian OS convention is to append a C to the function name. This indicates to the caller that, when the function returns successfully, the cleanup stack has additional pointers on it. This approach is typically used by CBase-derived classes which define static functions to instantiate an instance of the class and leave a pointer to it on the cleanup stack, as described in...

Constructors

A constructor is a member function that is automatically called when a class object is created. Its purpose is to initialize the state of the object. Constructors have the same name as the class itself and are usually public. Constructors can take arguments and may be overloaded, that is, more than one constructor may be defined with different parameter lists see Section 3.3 . A constructor that has no arguments, or only arguments with default values, is called a default constructor. A...

Packaging objects in descriptors

Flat data objects can be stored conveniently within descriptors using the package buffer TPckgBuf and package pointer TPckg and TPckgC classes. This is useful for inter-thread or inter-process data transfer when making a client-server request see Chapter 11 . In effect, a T-class object may be packaged whole into a descriptor descriptorized so it may be passed easily in a type-safe way between threads or processes. The TPckgBuf, TPckg and TPckgC classes are thin template classes see Chapter 3...

Stackbased buffer descriptors TBufC and TBuf

The stack-based buffer descriptors may be modifiable or non-modifiable. The string data forms part of the descriptor object, located after the length word in a non-modifiable descriptor and after the maximum-length word in a modifiable buffer descriptor. Figure 7.2 compares the memory layouts of TBuf and TBufC. These descriptors are useful for fixed-size, relatively small strings, since they are stack-based. They may be considered equivalent to char in C, but with the benefit of overflow...

Fundamentals of Symbian OS

Jehad Al-Ansari, Rosanna Ashworth-Jones, Warren Day, Ioannis Douros, Graeme Duncan, Adrian Issot, Ashvin Lad, Rick Martin, Lorin McKay, Chris Notton, John Pagonis, Antony Pranata, William Roberts, Rahul Singh, Attila Vamos, Jonathan Yu Head of Symbian Press Philip Northam Copyright 2006 by John Wiley amp Sons, Ltd The Atrium, Southern Gate, Chichester, West Sussex PO19 8SQ, England Email for orders and customer service enquiries cs-books wiley.co.uk Visit our Home Page on www.wiley.com All...

Tcb capability

The Tcb capability is possessed only by members of the Trusted Computing Base the kernel, device drivers, file system and, on open Symbian OS phones, the software installer. As described in Section 15.1, the TCB runs with maximum privilege. For this reason, any code running inside the TCB will be assigned all system and user capabilities. Because there are some things that only TCB code can do such as loading program code , there is one additional capability given only to the TCB. This, the...

Stray signal panics

The most commonly encountered problem when writing active object code is the infamous ''stray signal'' panic E32USER-CBASE 46 , which occurs when the active scheduler receives a completion event but cannot find an active object to handle it one which is currently active and has a completed iStatus result, indicated by a value other than KRequestPending . Stray signals can arise for the following reasons CActiveScheduler Add was not called when the active object was constructed SetActive was not...

UIDs used by DLLs

A Symbian OS UID is a 32-bit, globally unique identifier value used to identify a file type, both for running executable code and for associating data files with the appropriate application. Symbian OS uses a combination of up to three UIDs to uniquely identify a binary executable. For DLLs, the three UID values are used as follows UID1 is a system-level identifier which distinguishes between EXEs and DLLs. This value is never stated explicitly but is determined by the Symbian build tools from...

Compiling and linking

After preprocessing, the compiler stage is executed. This is separated out into lexical analysis, syntax analysis, symbol-table generation and code generation. For the most part the source file is treated as a stream which is tokenized a recursive syntax tree is built and validated and the target code is generated. The compiler may be instructed to generate additional symbolic data binding the object code to the source code and associated symbols. This is used by a debugger to halt and step...

The active scheduler wait loop

When an asynchronous request is complete, the asynchronous service provider calls User RequestComplete if the service provider and requestor are in the same thread, or RThread RequestComplete if not. It passes to these functions the TRequestStatus associated with the request and a completion result, typically one of the standard error codes such as KErrNone or KErrNotFound, to indicate the success or otherwise of the request. The function called sets the value of TRequestStatus to the given...

Member variables are leavesafe

While heap variables referenced only by local variables may be orphaned if a leave occurs, member variables will not suffer a similar fate unless their destructor neglects to delete them when it is called at some later point . Thus the following code is safe iMember CCatClass NewL Allocates a heap member FunctionMayLeaveL Safe for iMember The CTestClass object pointed to by the this pointer in CTest-Class SafeFunctionL is not deleted in the event of a leave. The heap-based iMember is stored...

Referencing HBufC through TDesC

The HBufC class derives from TDesC and an HBufC pointer can simply be dereferenced when a reference to a non-modifiable descriptor TDesC amp is required. A common mistake is to call the Des method on the heap descriptor, creating a separate TPtr referencing the descriptor data. This is not incorrect it returns a TDes amp , but it is clearer and more efficient simply to return the HBufC object directly. const TDesC amp CSampleClass AccidentalComplexity could be replaced more efficiently with

File handle class

The RFile class is a subsession of an RFs client session to the file server. An RFile object represents access to a named, individual file, providing functions to open, create or replace the file, or to open a temporary file, and to read from and write to it. RFile Open can be used to open an existing file an error is returned if it does not already exist RFile Create is used to create and open a new file an error KErrAlreadyExists is returned if the file already exists RFile Replace creates a...

Build processing

Symbian OS has its own platform-independent build file format used by bld.inf to specify how a program is built. The bldmake tool processes the bld.inf component description file to generate a batch file, abld.bat, associated with the project definition files specified by bld.inf. The bldmake tool can be called with the following options bldmake bldfiles generates abld.bat and associated .make files bldmake clean removes all files generated by bldmake bldfiles bldmake inf displays the basic...

Character size

The descriptors in early releases of Symbian OS, up to and including Symbian OS v5, had 8-bit native characters. Since that release, Symbian OS has been built to support Unicode character sets with wide 16-bit characters by default. The character width of descriptor classes can be identified from their names. If the class name ends in 8 for example TPtr8 it has narrow 8-bit characters, while a descriptor class name ending with 16 for example TPtr16 manipulates 16-bit character strings. There is...

The Inheritance Hierarchy of the Descriptor Classes 1

Figure 7.4 shows the inheritance hierarchy of the descriptor classes. The TDesC and TDes base classes provide the descriptor manipulation methods, and must know the type of derived class they are operating on in order to correctly locate the data area. However, each subclass does not implement its own data access method using virtual function overriding, because this would add an extra 4 bytes to each derived descriptor object for a virtual pointer vptr to access the virtual function table....

Submitting an asynchronous service request

An active object class supplies public ''request issuer'' methods for callers to initiate requests. These will submit requests to the asynchronous service provider associated with the active object, using a well-established pattern, as follows 1. Check for previous outstanding requests. Request methods should check that there is no request already submitted before attempting to submit another. Each active object must only ever have one outstanding request. Depending on the implementation, the...

Pointer descriptors TPtrC and TPtr

The string data of a pointer descriptor is separate from the descriptor object itself and can be stored in ROM, on the heap or on the stack. The memory that holds the data is not owned by the descriptor and pointer descriptors are agnostic about where the memory they point to is actually stored. The pointer descriptors themselves are usually stack-based, but they can be used on the heap, for example as a member variable of a CBase-derived class. In a non-modifiable pointer descriptor TPtrC ,...

Synchronous and asynchronous requests

When program code makes a function call to request a service, the service can be performed either synchronously or asynchronously. When a synchronous function is called, it performs a service to completion and returns directly to its caller, usually returning an indication of its success or failure or leaving, as discussed in Chapter 5 . Examples of typical synchronous calls include descriptor-data manipulation methods see Chapter 7 , for example to convert an 8-bit descriptor to 16-bit...

Trusted Computing Base TCB

The TCB is the most trusted part of Symbian OS, because it controls the lowest level of the security mechanisms and has responsibility for maintaining the integrity of the system. Code within the TCB runs at the highest level of privilege of any on Symbian OS. To enable verification of the trustworthiness of the TCB, for example through line-by-line code examination, the TCB is kept as small and simple as possible. The Symbian OS TCB has been carefully checked to ensure that the code within it...

Scope namespaces and logical groupings

As introduced in Section 1.2, an identifier has scope or visibility to other identifiers and expressions. C has introduced some sophisticated language mechanisms for extending the scope rules inherited from C to support object-oriented principles of data abstraction, hiding and encapsulation. Consider the following problem of two functions with the same name Consider the following problem of two functions with the same name There are two MusicPlayer function definitions in two separate library...

Array Sorting and Searching Critical Information

For the CArrayX classes, an array key can be used to define a property of an array element by which the entire array can be sorted and searched. For example, for an array of task elements, which have an integer priority value and a string name, a key based on the priority may be used to sort the array into priority order. Alternatively, a key based on the name may be used to search for a task of a particular name. The abstract base class for the array key is TKey. The following TKey-derived...

Creating a persistent store

The following code illustrates how to create a persistent store. The example creates a direct file store, but creating a permanent file store follows a similar pattern. void CreateDirectFileStoreL RFs amp aFs, TDesC amp aFileName, TUid aAppUid CFileStore store CDirectFileStore ReplaceLC aFs, aFileName, CStreamDictionary dictionary CStreamDictionary NewLC TStreamId id stream.CreateLC store CleanupStack PopAndDestroy stream dictionary- gt AssignL aAppUid,id RStoreWriteStream rootStream TStreamId...

CArrayX classes

The number of CArrayX classes makes this array family very flexible, although they have a significant performance overhead see Section 8.2 . The naming scheme works as follows. For each class, the CArray prefix is followed by Fix for elements which have the same length and are copied so they may be contained in the array buffer Var where the elements are of different lengths each element is contained within its own heap cell and the array buffer contains pointers to the elements Pak for a...

SIS file creation package files MakeSIS Makekeys SignSIS and CreateSIS

Unlike the Windows emulator, where binaries can simply be copied for testing, on phone hardware the only legitimate way to install and test code is for the software installer to read it from an installation package, known as a SIS file. Symbian OS developers use a Symbian OS package file .pkg to specify to the SIS file creation tool MakeSIS the files and metadata associated with an application. The package file contains a list of the files, rules, options and dependencies required for the...

HBufC construction and usage

HBufC can be spawned from existing descriptors using the Alloc or AllocL overloads implemented by TDesC. Here is a contrived example which shows how to replace inefficient code with use of TDesC AllocL void CSampleClass UnnecessaryCodeL const TDesC amp aDes iHeapBuffer HBufC NewL aDes.Length TPtr ptr iHeapBuffer- gt Des ptr.Copy aDes could be replaced by a single line An HBufC object can also be instantiated using the static NewL factory methods specified for the class. For HBufC16, the methods...

RBuf construction and usage

While there is a non-modifiable heap descriptor class, HBufC, there is no corresponding modifiable HBuf class, which might have been expected in order to make heap buffers symmetrical with TBuf stack buffers. However, since Symbian OS v8.1, the RBuf class has been available for use as a modifiable heap-based buffer class. RBuf objects can be instantiated using Create , CreateMax or CreateL to specify the maximum length of descriptor data that can be stored. It's also possible to instantiate an...