Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 54

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 54 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 542018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The category and error willbe reported, and may then be traced back by searching the library’s headerfiles for "CLANGER-ENGINE", located inside ClangerPanic.h. You’llsee I’ve commented each error’s enum value with its associated number,just to make the lookup easier. I’ve tried to give each a descriptive name,though obviously they could be further documented, using in-sourcecomments, for clarity.Of course, if a client programmer has access to the source code forclanger.dll, they can also search it for calls to Panic() which usea particular error value, to track down where a panic originated.15.3Symbian OS Panic CategoriesSymbian OS itself has a series of well-documented panic categoriesand associated error values.

You can find details of platform-specificpanics in your preferred SDK. From Symbian OS v7.0, there is a specialPanics section in the C++ API Reference of each SDK, which contains acomprehensive list of the Symbian OS system panics. Typical values youmay encounter include:• KERN-EXEC 3 – raised by an unhandled exception (such as an accessviolation caused, for example, by dereferencing NULL, memory misalignment or execution of an invalid instruction) inside a system callto the kernel executive; if an unhandled exception occurs insidecode which is instead executing in user mode, the panic is seen asUSER-EXEC 3• E32USER-CBASE 46 – raised by the active scheduler as a result of astray signal (described further in Chapters 8 and 9)• E32USER-CBASE 90 – raised by the cleanup stack when the objectspecified to be popped off is not the next object on the stack.

Thefollowing code illustrates the cause of the panic; this issue is describedmore fully in Chapter 3, which describes the cleanup stack.class CExample; // defined elsewherevoid CauseAPanicL(){TInt val = 1;CExample* ptr1 = new (ELeave) CExample();CleanupStack::PushL(ptr1);CExample* ptr2 = new (ELeave) CExample();CleanupStack::PushL(ptr2);...CleanupStack::Pop(ptr1); // Panics with E32USER-CBASE 90 here...PANICKING ANOTHER THREAD251CleanupStack::Pop(ptr2); // ...so the code never gets here}As a user, if making the chess move you’ve carefully worked outcauses your game to panic and close, you’re probably not interested inthe category or error code.

Such precise details are irrelevant and the”program closed” dialog is more irritating than helpful.Don’t use panics except as a means to eliminate programmingerrors, for example by using them in assertion statements. Panicking cannot be seen as useful functionality for properly debuggedsoftware; a panic is more likely to annoy users than inform them.15.4 Panicking Another ThreadI’ve shown how to call User::Panic() when you want the thread topanic itself. But how, and when, should you use RThread::Panic()?As I described earlier, the RThread::Panic() function can be used tokill another thread and indicate that the thread had a programming error.Typically this is used by a server to panic a client thread when the clientpasses a badly-formed request.

You can think of it as server self-defense;rather than go ahead and attempt to read or write to a bad descriptor, theserver handles the client’s programming error gracefully by panicking theclient thread. It is left in a good state which it would not have been ifit had just attempted to use the bad descriptor. Generally, in a case likethis, the malformed client request has occurred because of a bug in theclient code, but this strategy also protects against more malicious ”denialof service” attacks in which a client may deliberately pass a badly-formedor unrecognized request to a server to try to crash it. The Symbian OSclient–server architecture is discussed in Chapters 11 and 12; the latterchapter includes sample code that illustrates how a server can panicits client.If you have a handle to a thread which has panicked, you candetermine the exit reason and category using ExitReason() and ExitCategory(). This can be useful if you want to write test code to checkthat the appropriate panics occur, say from assertions in your librarycode, to defend it against invalid parameters.

Since you can’t ”catch” apanic, it’s not as straightforward as running the code in the main thread,passing in the parameters and checking that the code panics with thecorrect value. The checking code would never run, because the panicwould terminate the main thread.252PANICSA solution is to run deliberately badly-behaved client code in aseparate test thread, programmatically checking the resulting exit reasonsand categories of the panicked thread against those you would expectto have occurred.

You should disable just-in-time debugging for theduration of the test, so that only the test thread, rather than the emulator,is terminated. For example:enum TChilliStrength{ESweetPepper,EJalapeno,EScotchBonnet};void EatChilli(TChilliStrength aStrength){_LIT(KTooStrong, "Too Strong!");__ASSERT_ALWAYS(EScotchBonnet!=aStrength,User::Panic(KTooStrong, KErrAbort);... // Omitted for clarity}// Thread functionTInt TestPanics(TAny* /*aData*/){// A panic occurs if code is called incorrectlyEatChilli(EScotchBonnet);return (KErrNone);}void TestDefence(){// Save current just-in-time statusTBool jitEnabled = User::JustInTime();// Disable just-in-time debugging for this testUser::SetJustInTime(EFalse);_LIT(KPanicThread, "PanicThread");// Create a separate thread in which to run the panic testingRThread testThread;TInt r = testThread.Create(KPanicThread, TestPanics,KDefaultStackSize, NULL, NULL);ASSERT(KErrNone==r);// Request notification of testThread’s death (see Chapter 10)TRequestStatus tStatus;testThread.Logon(tStatus);testThread.Resume();User::WaitForRequest(tStatus); // Wait until the thread diesASSERT(testThread.ExitType()==EExitPanic);// Test the panic reason is as expectedASSERT(testThread.ExitReason()==KErrAbort);testThread.Close();// Set just-in-time back to previous settingUser::SetJustInTime(jitEnabled);}SUMMARY25315.5 Faults, Leaves and PanicsA fault is raised if a critical error occurs such that the operating systemcannot continue normal operation.

On hardware, this results in a reboot.A fault can only occur in kernel-side code or a thread which is essential tothe system, for example the file server, so typically you will not encounterthem unless you are writing device drivers or uncover a bug in the OS. Ineffect, a fault is another name for a serious system panic.Chapter 2 discusses leaves in more detail, but, in essence, they occurunder exceptional conditions such as out of memory or the absence of acommunications link. Unlike a panic, a leave should always be caught(”trapped”) by code somewhere in the call stack, because there shouldalways be a top-level TRAP.

However, if a leave is not caught, this impliesthat the top-level TRAP is absent (a programming error) and the threadwill be panicked and terminate.15.6 SummaryThis chapter discussed the use of panics to terminate the flow of executionof a thread. Panics cannot be ”caught” like an exception and are severe,resulting in a poor user experience. For that reason, panics are only usefulto track down programming errors and, on Symbian OS, are typicallycombined with an assertion statement, as discussed in the next chapter.This chapter described the best way to identify panics and illustratedhow to test the panics that you’ve added to your own code for defensiveprogramming.

It gave a few examples of commonly-encountered systempanics and directed you to the Panics section of the system documentationfor a detailed listing of Symbian OS system panics.16Bug Detection Using AssertionsOn the contrary!As Ibsen lay dying, his nurse brought him some visitors.

”Our patient isfeeling much better today,” she told them. Ibsen woke up, made theexclamation above, and died.In C++, assertions are used to check that assumptions made about codeare correct and that the state, for example, of objects, function parametersor return values, is as expected. Typically, an assertion evaluates astatement and, if it is false, halts execution of the code and perhapsprints out a message indicating what failed the test, or where in code thefailure occurred.On Symbian OS, you’ll find the definition of two assertion macros1 ine32def.h:#define __ASSERT_ALWAYS(c,p) (void)((c)||(p,0))...#if defined(_DEBUG)#define __ASSERT_DEBUG(c,p) (void)((c)||(p,0))#endifAs you can see from the definition, if the assertion of condition c isfalse, procedure p is called; this should always halt the flow of execution,typically by panicking (panics are described in detail in Chapter 15).

Youcan apply the assertion either in debug code only or in both debug andrelease builds. I’ll discuss how you decide which is appropriate later inthe chapter.1At first sight, these definitions seem more complex than they need to be, when thefollowing simpler definition could be used:#define __ASSERT_ALWAYS(c,p) ((c)||(p))The reason for the (p,0) expression is for cases where the type returned from p is void(the case when p is a typical Panic() function) or a value that can’t be converted to aninteger type for evaluation. The cast to void is present to prevent the return value of theexpression being used inadvertently.256BUG DETECTION USING ASSERTIONSYou’ll notice that the assertion macros do not panic by default, butallow you to specify what procedure to call should the assertion fail.This gives you more control, but you should always terminate the runningcode and flag up the failure, rather than return an error or leave.

Assertionshelp you detect invalid states or bad program logic so you can fix yourcode as early as possible. It makes sense to stop the code at the pointof error, thus forcing you to fix the problem (or remove the assertionstatement if your assumption is invalid). If the assertion simply returns anerror on failure, not only does it alter the program flow, but it also makesit harder to track down the bug.You should always raise a panic when an assertion statementfails.16.1−−−ASSERT− DEBUGHere’s one example of how to use the debug assertion macro:void CTestClass::TestValue(TInt aValue){#ifdef _DEBUG_LIT(KPanicDescriptor, "TestValue"); // Literal descriptor#endif__ASSERT_DEBUG((aValue>=0), User::Panic(KMyPanicDescriptor,KErrArgument));...}Of course, this is somewhat awkward, especially if you expect to usea number of assertions to validate your code, so you’ll probably define apanic utility function for your module, with its own panic category stringand a set of panic enumerators specific to the class.

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

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

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

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