Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 58

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 58 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 582018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 58)

It can also be used in the S60 emulator text shell.Using the D EXC toolThe D EXC tool traps panics and exceptions occurring in programs, andlogs the information for later analysis. It can be started by running theeshell program and is invoked by:Start d_excAn indicator, displayed on the screen, shows when the tool starts running. When a panic occurs, a dialog pops up showing basic informationabout the panic and prompts the user as to whether they wish to log thecrash or not.If the user chooses to grab the stack data, the tool creates two files inthe root of the C: drive on the device: d exc %d.txt reports the basicinformation about registers, DLLs, etc. and d exc %d.stk contains a302DEBUGGING AND THE EMULATORbinary dump of the user stack.

%d is the id of the thread that has crashed.Figure 10.10 shows an example of the TXT file created by the D EXCtool.Name of owning processThird UIDGeneration numberThread namePanic categoryand reasonProgramcounterRegistersStack base addressStack end addressSize of stackStack pointerFigure 10.10 D EXC tool outputFigure 10.11 shows the D EXC register information and a binary dumpof the user stack using Carbide.c++ v1.1 with a UIQ SDK.Figure 10.11 D EXC tool output on UIQ SDKEMULATOR DEBUGGING303In this example, a USER 84 panic has been produced via RTest::Panic() and the user can choose either to debug on the panic or not.After the panic happens, you can switch to the Task Panel (by pressingCtrl+Alt+Shift+T). Using QFileMan, you can see d exc 152.txt andd exc 152.stk on the C: drive (see Figure 10.12).

The generatedd exc 152.txt is shown in Figure 10.13.Figure 10.12 QFileMan showing files produced by D EXC on UIQ SDKFigure 10.13 An example d exc 152.txt304DEBUGGING AND THE EMULATORMemory TestsWhen writing code that will run on a mobile phone, it is important to bearin mind the limited resources available on a phone (especially memory)and to ensure that your programs handle any related memory allocationfailures correctly.Due to the limited resources on a phone, requests for memory mayoccasionally fail. If your code is in this situation, it must inform the userthat there is not enough memory to perform the operation or provide theservice; certainly the code must not panic without returning meaningfulinformation and should not lose any existing data.One common error is for programs to allocate memory for objects butto fail to delete the objects, and hence fail to free the memory.

This iscalled ‘leaking’ memory. There are tools available to help catch theseerrors.Heap-Management MacrosEach thread has a chunk of memory which contains that thread’s programstack. For the main thread of a process, this chunk also contains thethread’s heap. A program’s requests for memory are allocated from thisheap.A set of heap-management macros are provided in e32def.h toUHEAP MARK ishelp to check for memory leaks in debug builds.used to mark the start of a new level of heap-cell checking. Every callUHEAP MARK should be matched by a later call toUHEAPtoMARKENDC, which verifies that the number of heap cells allocated at thecurrent nested level is as expected.

If there is a memory leak (becausemore or fewer heap cells are allocated), a panic is raised with informationabout the first leaked memory allocation on the heap.UIQ SDK 3 provides a heap allocator called RQikAllocator thatcan be used by including the following libraries in your MMP file:LIBRARY QikAllocDll.libSTATICLIBRARY QikAlloc.libMemory leaks in code can usually be detected on the emulator byusing the above macros and examining the panic code.

If is not obviouswhere a leak occurs, then you may find HookLogger more helpful.HookLoggerHookLogger is a Microsoft Windows GUI-based tool which provides easyjournaling facilities for logging memory allocations, processes, threadcreation and leaves when executing an application under the SymbianEMULATOR DEBUGGING305OS emulator. The main use for most developers is to find the source of aleaked heap cell. The application works by replacing EUSER.DLL fromthe target Symbian OS SDK with a version that allows the attachmentof ‘hooks’ that are used by HookLogger.

After the test execution sessionis finished, the user can issue the same command to restore the originalversion of EUSER.DLL.Figure 10.14 HookLogger Configuration1. Download HookLogger from developer.symbian.com\main\downloads\files\HookLogger Setup.zip and install it in a directoryon your development drive (e.g. X:\HookLogger\).2. Attach the hooks to EUSER.DLL by starting a command promptin the HookLogger directory and typing ‘hookeuser winscw’. (Typeonly ‘hookeuser’ at the command prompt to get more options.) Thisreplaces the EUSER.DLL of the target Symbian OS SDK with aversion used by the HookLogger tool.3. Run HookLogger.EXE and configure it to monitor heap allocations.4. To find the memory leak, start the emulator and execute the failingprograms to reproduce the memory leak.

Go to the Threads tabin HookLogger, find the application that leaks and untick all otherthreads. (The processes can be filtered by settings on the Filter tab.)306DEBUGGING AND THE EMULATOROn the Heap tab, list All allocs to display the current memoryallocations.10.35.Selecting an allocation and click Alloc details to see additionalinformation that should allow you to track down the source filewhere a leak is occurring.6.You can use the radio buttons on the General tab to get additionalinformation.7.Restore the original version of EUSER.DLL by typing ‘hookeuser -rwinscw’.Debugging on a PhoneAfter debugging on the emulator has been completed, the next stage isto focus on how your application runs on the target device – a mobilephone.The first stage is to compile your code for the ARM platform bychanging the target platform in the IDE to ARM. (You do this in theBuild Configuration tab in Carbide.c++ and the Project window inCodeWarrior.) There are two ARM target options: debug (UDEB) andrelease (UREL).

The difference is that debug versions contain unoptimizedcode, making debugging easier: the release versions are optimized andare usually without debugging code (this can be generated, but theoptimizations make debugging more difficult). As a result, the size ofthe final binary components from release build is generally smaller thandebug versions, which is a benefit for such devices.It’s probably best to do your on-target debugging using a release build,as it is possible that some errors may only manifest themselves on releasebuilds, due to compiler optimizations or differences in memory layout orinitialization.On-Target Debugging AgentsOn-target debugging requires ‘debug agent’ software to be running on thedevice, to communicate with the IDE.

For Symbian OS v9, the supporteddebugger is Metrowerks Target Resident Kernel (MetroTRK).MetroTRK is a Symbian OS application that runs inside the operatingsystem and provides debug services over serial communications (a cable,Bluetooth or infrared, for example) to the Carbide.c++ Developer andProfessional or CodeWarrior Professional debuggers. MetroTRK lets youdownload an application and its supporting files to the target device anddebug it using the IDE. Not all phones support hardware debugging – fora list of those supported and to download MetroTRK itself, see the CodeWarrior product descriptions at www.forum.nokia.com\codewarrior.DEBUGGING ON A PHONE307Emulator versus On-Target DebuggingDebugging can be carried out both on an emulator and on target hardware. Initially you use an emulator, proceeding to target hardware lateron.

There are a number of differences between emulator debugging andon-target debugging.• On the emulator, it is possible to write and modify things on the Z:drive; on target hardware, the Z: drive is the ROM drive and cannotbe written to or modified in any way.• On the emulator, stacks can automatically grow to be very large;on target hardware, the stacks are fixed in size and much smaller(typically 8 KB but configurable using the epocstacksize keywordin the MMP file).

They have to be used very carefully to prevent stackoverflow.• On target hardware, misaligned word access often leads to KERNEXEC 3 panics (equivalent to an access violation). On ARM processors,you can only access words on aligned boundaries. On the emulator,this is not a problem because it uses x86 architecture processors.• On target hardware, certain system files are locked – some processesthat run on boot can lock files that you may want to overwrite. Forexample, the way you generate and edit the Comms Database ontarget hardware can be completely different and is not consistentacross different products.• Floating-point exceptions can occur on target hardware but not whenusing the emulator. Symbian OS provides a complete software emulation of the IEEE-754 64-bit floating point processor using the TReal64class.

The IEEE floating point raises an exception when certain thingshappen, for example division by zero. Applications can elect tohandle these exceptions or accept IEEE default behavior. MicrosoftWindows programs have the floating-point exceptions disabled, sothese exceptions never occur on the emulator; some ARM processorsdo not have floating-point hardware and so all arithmetic is doneusing the Symbian OS emulated floating point processor.• On target hardware, a file may be missing, present (when it shouldnot be there) or wrongly named in the ROM.• Process errors: On the emulator, it is possible for a process to accessthe address space of other processes because all Symbian OS threadsare part of a single Microsoft Windows process; on target hardware,this is not the case.• Timing differences may occur between emulator and target hardware,leading to programs succeeding on the emulator but failing on thetarget hardware.308DEBUGGING AND THE EMULATOR• The order in which code is called can be different on the emulatorthan on the target device.

Характеристики

Тип файла
PDF-файл
Размер
6,45 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6529
Авторов
на СтудИзбе
301
Средний доход
с одного платного файла
Обучение Подробнее