Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 35

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 35 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 352018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

This gets around a very common problemfor developers of shared components – the need to gain manufacturercapabilities for shared DLLs, even though the DLL itself does not usethem.This variant is very simple to implement. The service providerexports a header file (as for the DLL variant) and supplies a staticLIB which contains objects that are incorporated into the callingexecutable at build time.CLIENT-THREAD SERVICE181• The service provider MMP file specifies the LIB TARGETTYPE:TARGETTYPE lib• The MMP file does not need to specify any capabilities, UIDs,SECUREID or VENDORID, as all of these are inherited from theEXE file used to create the process within which the LIB executesat run time.• The client MMP file specifies the LIB files using the STATICLIBRARY keyword followed by the list of LIBs (both filename andextension are specified):STATICLIBRARY mylib.lib otherlib.lib newlib.libReferences• Chapter 7 explains why a service provided by a DLL cannot securelyverify a client’s identity or its capabilities.• Client–Server (see page 182) is an alternative to this pattern where theservice provider is based in another thread.

It provides the necessaryinfrastructure for sharing and serializing access to resources as well asfor allowing security checks on clients.• Buckle (see page 252) discusses the security issues related to loadingDLL plug-ins; it is closely related to the Dynamically Selected CTSvariant of this pattern.• The following documents provide additional information related tobuilding a CTS:• Symbian Developer Library Symbian OS Tools And UtilitiesBuild tools guide How to build DLLs• Symbian Developer Library Examples Symbian OS fundamentals example code CreateStaticDLL and UseStaticDLL: using astatically linked DLL• Symbian Developer Library Symbian OS guide Essentialidioms Exporting and Importing Classes in Symbian OS182PROVIDING SERVICESClient–ServerIntentSynchronize and securely police access to a shared resource or servicefrom multiple client processes by using the Symbian OS client–serverframework.AKANone knownProblemContextResources and services need to be shared among multiple clients runningin different processes.SummaryMany applications are designed around concurrent objects running indifferent processes to improve quality of service such as performance andreliability.

Often these different objects need to access a shared resource.In this concurrent environment, it is necessary that:• We have a transparent means of inter-process communication.• Access to shared resources is synchronized.• Both synchronous and asynchronous requests from clients can be meteasily.• Where applicable, the access to shared resources, or sensitive data, ispoliced.Description• Inter-process communication should be transparent.The need to protect against memory corruption across process boundaries means that in most cases objects cannot be called passivelyacross this boundary. Such calls must be serialized and passed acrossthe boundary using privileged code. It is impractical for each application developer to do this. So what is needed is an inter-processcommunication mechanism that provides user-friendly support fortransforming the memory representation of an object to or from adata format suitable for storage or transmission, a process known asmarshaling 12 and un-marshaling.12 en.wikipedia.org/wiki/Marshalling(computer science).

See also serializing.CLIENT–SERVER183• Synchronized13 access to shared resources should be simple.Here, synchronization means the coordination of simultaneous threadsor processes to complete a task by correctly ordering them at run timeand avoiding unexpected race conditions. Achieving synchronousaccess to a resource in a collaboration of concurrent objects is noteasy using low-level synchronization mechanisms, such as acquiringand releasing mutual exclusion (mutex) locks. In general, service callsthat are subject to synchronization constraints should be serializedtransparently when an object is accessed by multiple client threads.A common mechanism for doing this is needed.• Both synchronous and asynchronous requests from clients can be meteasily.The actions offered by a service may take any amount of time, fromnegligible to considerable, even excluding the context switching andmessage transfer time.

Where the time is negligible, clients may makea synchronous request on the service that blocks their current threadof execution to simplify their design. Where the time is considerable,an asynchronous request may be needed to guarantee some quality ofservice – such as co-operative multitasking in the client’s own thread.It is necessary that these different requests can be made very simplyby developers of the client code.• Access to shared resources and sensitive data is policed.It is often the case that you may wish to restrict access to the sharedresource or sensitive data from some clients. Such policing necessarilyneeds to be done close to the service and in privileged code wherethe developer of the client code cannot tamper with, or bypass, asecurity policy check.ExampleOne example of this problem is the file system.

Symbian OS has amicrokernel architecture [Buschmann et al., 1996], so its file system isn’tpart of the kernel facilities. Instead, it manages one or more storage mediathat are used by a large number of client applications. It needs to be ableto control the access to each individual file by a number of clients toguarantee its integrity.The file system also polices the data cages required by the PlatformSecurity architecture so that only trusted clients with specific securitytokens, such as a capability or a SID, may access the restricted directories/sys, /private or /resource.

For instance, a client must have theTCB capability to be allowed write access to /sys.13 en.wikipedia.org/wiki/Synchronization.184PROVIDING SERVICESSince both security checks on clients and a way of mediating accessto a shared resource are required, Client-Thread Service (see page 171)doesn’t provide a solution to this problem.SolutionThe solution to this problem is to have the resource managed by a serverrunning in its own process. Clients communicate with the server usingmessages to request operations on the resource. The communication isbound by a strict protocol that the server defines and is mediated by theKernel.As a minimum, this pattern builds on the following Symbian OSpatterns with which you should be familiar before continuing:• Active Objects (see page 133) is used to efficiently handle servicerequests from multiple clients.• Request Completion (see page 104) is used by the server to informclients of when their requests have been completed.• Escalate Errors (see page 32) is extended so that errors which occurin the server when handling a client’s request are passed back to theclient.To help you understand this solution, we describe it in terms of a serverthat shares a TInt with its clients and offers the following actions:• Get the value synchronously.• Request notifications of when the value changes.• Ask the server to perform a long-running activity that updates thevalue.

This request is completed only when the entire activity hascompleted.StructureHere we describe a model of the static relationship between the elementsin this architectural pattern. We also define the core responsibility of eachelement with regards to this pattern.In this pattern (see Figure 6.8), a server provides some shared service.Clients use a Proxy which conveniently serves as the interface to theserver. The connection between a particular Proxy object and the serverconstitutes a session.

A server session object represents the server-sideend-point of this connection and may be used to encapsulate any specificinformation that a server cares to maintain about the client. The clientend-point of the connection is encapsulated by the client session.The client session marshals client requests into request messagesthat are queued within the server. The server uses Active Objects (seeCLIENT–SERVER185RMessage2−iStatus: TRequestStatus+++Function()ReadL()WriteL()createsservicesClient ThreadServer ThreadCActiveCActiveCClientActive++RunL()DoCancel()RSessionBaseCSession2«Proxy»RMyClientSession«Proxy»CMyServerSession+++++Connect()GetValueL()Observe()DoActivity()CancelActivity()Figure 6.8IPC mediated bythe Kernel+CMyServerServiceL()0..*−iValue: Tlnt++++++++Start()ReStart()NewSession()RunL()GetValueL()ObserveL()DoActivityL()CancelActivity()Structure of the Client–Server patternpage 133) to schedule the handling of the request messages.

When therequests have been serviced, the client is notified via Request Completion(see page 104). These participating objects are described in more detailbelow:• Client (CClientActive): As the user of a service, the client connectsto the server and initiates requests to the server. It waits for and receivesa response for each request sent to the server. A client is typically anactive object so that it can handle any asynchronous responses fromthe server without polling or waiting for the request.• Server (CMyServer): The server encapsulates the shared resource, orsensitive data, to be managed.

In effect, it is a Singleton14 from theperspective of the whole software system. It accepts connections fromone or more clients. It waits for a request from a client and servicesit when it arrives. When the client’s request is completed, it sendsa response. The server object is driven as an active object by theSymbian OS client–server framework which manages the queue ofmessages15 waiting for it and feeds the server one request at a time.• Client Session (RMyClientSession): This session provides the interface that allows clients to invoke the publicly accessible methods ona server. The client session, when required, runs in the same threadas the client and acts as a Proxy to the server.

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

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

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

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