mozilla
검색 결과

    Firefox OS architecture

    초안
    이 문서는 작성중입니다.

    이 (게시)글은 Firefox OS platform의 구조(architecture)에 대한 고차원적인 개요이며, 주요 개념을 소개하고 구성요소들이 기본레벨에서 어떻게 상호동작 하는지를 설명합니다. 기술적인 레벨에서 어떻게 동작하는지의 복잡한 사항을 알려주지는 않습니다; 각각의 See also 섹션으로부터 참조된 글들을 보시기 바랍니다.

    Note: Firefox OS는 이직 정식배포 전의 상품임을 유념해 주십시오. 여기에 설명된 구조(architecture)는 반드시 최종이라 할 수 없으며 변경될 수 있습니다.

    용어

    이 문서를 이해하기 전에 알 필요가 있는 몇 가지 용어가 있습니다.

    B2G
    Boot to Gecko의 약어.
    Boot to Gecko
    전체적인 Firefox OS 프로젝트에 대한 코드명입니다. 프로젝트가 공식명칭을 갖기 오래 전 부터 사용되었기 때문에, Firefox OS를 나타내는 용어로 이 용어가 사용되는 것을 볼 수 있습니다.
    Gaia
    Firefox OS platform의 사용자 인터페이스. Firefox OS가 구동된 후에 화면에 표시되는 것들은 Gaia 층에서 생성된 것 입니다. Gaia는 최신의 스마트폰에서 기대할 수 있는 잠금 화면, 홈 화면, 그리고 모든 표준화된 어플리케이션들을 구현하고 있습니다. Gaia는 전적으로 HTML, CSS와 JavaScript로 구현되었습니다. 내부의 OS와의 유일한 인터페이스는 개방된 Web API들을 통해 이루어 집니다. 이는 Gecko 층(layer)에 구현되어 있습니다. 제 3자가 개발한 어플리케이션들은 Gaia 층에 나란히 설치될 수 있습니다.
    Gecko
    Firefox OS 어플리케이션 런타임; 즉, 공개된 표준의 3가지 펙터(HTML, CSS, JavaScript)에 대한 모든 지원을 제공합니다. Gecko가 지원하는 모든 운영체제상에서 관련 API들이 제대로 동작하는 것을 보장합니다. 이는 Gecko가 다른 여러가지 중에서도, 네트워킹 스택, 그래픽 스펙,  배치(layout) 엔진, JavaScript 버추얼 머신과 포팅 레이어들을 포함하고 있다는 것을 의미합니다.
    Gonk
    Gonk는 Firefox OS 플랫폼의 더 낮은 레벨의 운영체제로, (안드로이드 오픈 소스 프로젝트, Android Open Source Project (AOSP)를 기반으로 하는)리눅스 커널과 유저공간의 하드웨어 추상 계층(Userspace Hardware adstraction layer:HAL)로 구성되어 있습니다. 커널과 여러개의 라이브러리들은 일반적인 오픈 소스 프로젝트들(리눅스, libusb, bluz 등)입니다. HAL의 또 다른 부분들은 안드로이드 프로젝트(GPS, camera 등)과도 공유됩니다. Gonk는 아주 간단한 리눅스라 할 수 있습니다. Gecko는 Gonk에 포팅됩니다; 마치, Gecko가 Mac OS X, Windows와 Android에 포팅되듯이 Gecko는 Gonk에 포팅됩니다. Firefox OS 프로젝트는 Gonk에 대한 전반적인 통제를 가지고, 다른 운영체제에 대한 노출되지 않는 Gecko에 대한 인터페이스들을 노출시킬 수 있습니다. 예를 들어, Gecko는 전반적인 텔레포니 스택과 Gonk상의 디스플레이 프레임 버퍼에 대한 직접적인 접근이 가능하지만, 다른 운영체제로의 이러한 접근은 가능하지 않습니다.  
     
    Firefox OS Architecture

    부트스트래핑 프로세스

     맨 처음, Firefox OS를 구동하면, 첫 번째 부트로더부터 실행 하기 시작 합니다. 여기서부터, 일반적인 방법으로 주 운영체제를 불러오는 과정을 진행 합니다.  점진적으로 높은 레벨의 부트로더들을 연속으로 두어서 다음 로더를 연속적으로 부트스트래핑 합니다. 이 단계의 마지막에서, Linux Kernel로 실행이 넘어갑니다.

     부팅 프로세스에 대해 별 의미 없는 몇 가지 사항이 있습니다.

    • 부트로더들은 보통 장치를 시작 할 때 유저에게 첫 번째로 보이는 시작 화면(splash screen)이 있습니다. 이 시작 화면은 일반적으로 제조사의 로고 입니다.
    • 부트로더들은 장치로 이미지를 플래싱(flashing) 합니다. 각각 다른 장치들은 각각 다른 프로토콜을 사용 합니다. 대부분의 휴대폰은 fastboot protocol을 사용하지만, 삼성의 갤럭시 S II는 odin 프로토콜을 사용 합니다.
    • 부트스트래핑 과정이 종료되면서, 대개 모뎀 이미지를 로드하고 모뎀 프로세서에서 실행 합니다. 이런 과정은 굉장히 장치에 특화 되어 있고, 누군가가 소유권(proprietary)을 가지고 있을 수도 있습니다.

    리눅스 커널

    Gonk가 사용하는 리눅스 커널(들)은 리누스 토발즈와 세계의 해커들이 함께 개발하고 있는 업스트림의 리눅스로부터 만들어졌으며, 거의 똑같습니다. 다만 안드로이드 오픈 소스 프로젝트 로부터 만들어지고 아직 업스트림에 들어가지 않은 변경사항들을 가지고 있습니다. 또한, vendor들이 가끔 커널을 수정하며, 이 경우 그들은 그들 자체적 스케쥴로 업스트림에 변경 사항을 올립니다. 그렇지만 일반적으로 말하면 Gonk가 사용하는 리눅스 커널은 오리지날 리눅스와 거의 같다고 이야기 할 수 있습니다.

    리눅스 구동 시작 과정 은 인터넷 상에 잘 문서화 되어 있으므로, 이 글에서는 그것까지 다루지는 않겠습니다. 구동 시작 과정의 마지막에, 대부분의 UNIX류 운영체제가 그러하듯이 userspace의 init 프로세스가 시작됩니다. 이 시점에서 마운트된 "disk"는 RAM disk 뿐입니다. 이 RAM disk는 Firefox OS 빌드 과정에서 만들어 졌으며, init나 시작 과정 스크립트들이나 로드할 수 있는 커널 모듈들과 같은 중요한 유틸리티들을 가지고 있습니다.

    일단 init 프로세스가 시작되면, 리눅스 커널은 userspace 공간으로부터의 시스템 콜, 인터럽트, 하드웨어 기기로부터의 비슷한 요청들을 처리합니다. 많은 하드웨어 기능이 userspace에 sysfs를 통해 노출됩니다. 예를 들어, 다음 코드 조각은 Gecko에서 배터리 상태를 읽기 위해 사용됩니다:

    FILE *capacityFile = fopen("/sys/class/power_supply/battery/capacity", "r");
    double capacity = dom::battery::kDefaultLevel * 100;
    if (capacityFile) {
      fscanf(capacityFile, "%lf", &capacity);
      fclose(capacityFile);
    }

    init 프로세스

    Gonk의 init 프로세스는 필요한 파일 시스템들을 마운트 하고 시스템 서비스들을 시작하는 일을 처리합니다. 이 일들의 처리 후에는 프로세스 매니저로 역할하게 됩니다. 이것은 다른 UNIX류 운영체제들에서의 init와 매우 비슷합니다. 먼저 다양한 서비스들을 시작시키기 위해서 필요한 명령들을 가지고 있는 스크립트들(init*.rc 파일들)을 수행합니다. Firefox OS의 init.rc 는 오리지날 안드로이드의 init.rc 에서 Firefox OS를 시작하는데 필요한 것들을 좀 추가한 형태이며, 기기에 따라 조금씩 다를 수 있습니다.

    init 프로세스가 하는 가장 중요한 작업 중 하나는 b2g 프로세스를 시작시키는 것입니다; 이게 Firefox OS 운영체제의 중심입니다.

    b2g를 시작시키는 init.rc의 코드는 다음과 같은 식입니다:

    service b2g /system/bin/b2g.sh
        class main
        onrestart restart media

    안드로이드의 init.rc에서 b2g 프로세스를 시작시키기 위한 코드가 추가된 init.b2g.rc 파일을 보는 것도 좋을 겁니다.

    Note: 정확히 init.rc 가 안드로이드 버전과 얼마나 다른가는 실제 기기마다 다릅니다; 어떤 기기의 경우는 단지 init.b2g.rc 가 추가되어 있을 뿐이고, 어떤 기기는 그보다 더 많은 변경이 있을 수 있습니다.

    The userspace process architecture

    Now it's useful to take a high-level look at how the various components of Firefox OS fit together and interact with one another. This diagram shows the primary userspace processes in Firefox OS.

    Userspace diagram

    Note: Keep in mind that since Firefox OS is under active development, this diagram is subject to change, and may not be entirely accurate.

    The b2g process is the primary system process. It runs with high privileges; it has access to most hardware devices. b2g communicates with the modem, draws to the display framebuffer, and talks to GPS, cameras, and other hardware features. Internally, b2g runs the Gecko layer (implemented by libxul.so). See Gecko for details on how the Gecko layer works, and how b2g communicates with it.

    b2g

    The b2g process may, in turn, spawn a number of low-rights content processes. These processes are where web applications and other web content are loaded. These processes communicate with the main Gecko server process through IPDL, a message-passing system.

    rild

    The rild process is the interface to the modem processor. rild is the daemon that implements the Radio Interface Layer (RIL). It's a proprietary piece of code that's implemented by the hardware vendor to talk to their modem hardware. rild makes it possible for client code to connect to a UNIX-domain socket to which it binds. It's started up by code like this in the init script:

    service ril-daemon /system/bin/rild
        socket rild stream 660 root radio

    rilproxy

    In Firefox OS, the rild client is the rilproxy process. This acts as a dumb forwarding proxy between rild and b2g. This proxy is needed is an implementation detail; suffice it to say, it is indeed necessary. The rilproxy code can be found on GitHub.

    mediaserver

    The mediaserver process controls audio and video playback. Gecko talks to it through an Android Remote Procedure Call (RPC) mechanism. Some of the media that Gecko can play (OGG Vorbis audio, OGG Theora video, and WebM video) are decoded by Gecko and sent directly to the mediaserver process. Other media files are decoded by libstagefright, which is capable of accessing proprietary codecs and hardware encoders.

    Note: The mediaserver process is a "temporary" component of Firefox OS; it's there to aid in our initial development work, but is expected to go away eventually. This will most likely not happen until Firefox OS 2.0 at the earliest, however.

    netd

    The netd process is used to configure network interfaces.

    wpa_supplicant

    The wpa_supplicant process is the standard UNIX-style daemon that handles connectivity with WiFi access points.

    dbus-daemon

    The dbus-daemon implements D-Bus, a message bus system that Firefox OS uses for Bluetooth communication.

    Gecko

    Gecko, as previously mentioned, is the implementation of web standards (HTML, CSS, and JavaScript) that is used to implement everything the user sees on Firefox OS.

    Processing input events

    Most action inside Gecko is triggered by user actions. These actions are represented by input events (such as button presses, touches to a touch screen device, and so forth). These events enter Gecko through the Gonk implementation of nsIAppShell, a Gecko interface that is used to represent the primary entrance points for a Gecko application; that is, the input device driver calls methods on the nsAppShell object that represents the Gecko subsystem in order to send events to the user interface.

    For example:

    void GeckoInputDispatcher::notifyKey(nsecs_t eventTime,
                                         int32_t deviceId,
                                         int32_t source,
                                         uint32_t policyFlags,
                                         int32_t action,
                                         int32_t flags,
                                         int32_t keyCode,
                                         int32_t scanCode,
                                         int32_t metaState,
                                         nsecs_t downTime) {
      UserInputData data;
      data.timeMs = nanosecsToMillisecs(eventTime);
      data.type = UserInputData::KEY_DATA;
      data.action = action;
      data.flags = flags;
      data.metaState = metaState;
      data.key.keyCode = keyCode;
      data.key.scanCode = scanCode;
      {
        MutexAutoLock lock(mQueueLock);
        mEventQueue.push(data);
      }
      gAppShell->NotifyNativeEvent();
    }

    These events come from the standard Linux input_event system. Firefox OS uses a light abstraction layer over that; this provides some nice features like event filtering. You can see the code that creates input events in the EventHub::getEvents() method in widget/gonk/libui/EventHub.cpp.

    Once the events are received by Gecko, they're dispatched into the DOM by nsAppShell:

    static nsEventStatus sendKeyEventWithMsg(uint32_t keyCode,
                                             uint32_t msg,
                                             uint64_t timeMs,
                                             uint32_t flags) {
        nsKeyEvent event(true, msg, NULL);
        event.keyCode = keyCode;
        event.location = nsIDOMKeyEvent::DOM_KEY_LOCATION_MOBILE;
        event.time = timeMs;
        event.flags |= flags;
        return nsWindow::DispatchInputEvent(event);
    }
    

    After that, the events are either consumed by Gecko itself or are dispatched to Web applications as DOM events for further processing.

    Graphics

    At the very lowest level, Gecko uses OpenGL ES 2.0 to draw to an GL context that wraps the hardware frame buffers. This is done in the Gonk implementation of nsWindow by code similar to this:

    gNativeWindow = new android::FramebufferNativeWindow();
    sGLContext = GLContextProvider::CreateForWindow(this);

    The FramebufferNativeWindow class is brought in directly from Android; see FramebufferNativeWindow.cpp. This uses the gralloc API to access the graphics driver in order to map buffers from the framebuffer device into memory.

    Gecko uses its Layers system to composite drawn content to the screen. In summary, what happens is this:

    1. Gecko draws separate regions of pages into memory buffers. Sometimes these buffers are in system memory; other times, they're textures mapped into Gecko's address space, which means that Gecko is drawing directly into video memory. This is typically done in the method BasicThebesLayer::PaintThebes().
    2. Gecko then composites all of these textures to the screen using OpenGL commands. This composition occurs in ThebesLayerOGL::RenderTo().

    The details of how Gecko handles the rendering of web content is outside the scope of this document.

    Hardware Abstraction Layer (HAL)

    The Gecko hardware abstraction layer is one of the porting layers of Gecko. It handles low-level access to system interfaces across multiple platforms using a C++ API that's accessible to the higher levels of Gecko. These APIs are implemented on a per-platform basis inside the Gecko HAL itself. This hardware abstraction layer is not exposed directly to JavaScript code in Gecko.

    How the HAL works

    Let's consider the Vibration API as an example. The Gecko HAL for this API is defined in hal/Hal.h. In essence (simplifying the method signature for clarity's sake), you have this function:

    void Vibrate(const nsTArray<uint32> &pattern);

    This is the function called by Gecko code to turn on vibration of the device according to the specified pattern; a corresponding function exists to cancel any ongoing vibration. The Gonk implementation of this method is in hal/conk/GonkHal.cpp:

    void Vibrate(const nsTArray<uint32_t> &pattern) {
      EnsureVibratorThreadInitialized();
      sVibratorRunnable->Vibrate(pattern);
    }
    

    This code sends the request to start vibrating the device to another thread, which is implemented in VibratorRunnable::Run(). This thread's main loop looks like this:

    while (!mShuttingDown) {
      if (mIndex < mPattern.Length()) {
        uint32_t duration = mPattern[mIndex];
        if (mIndex % 2 == 0) {
          vibrator_on(duration);
        }
        mIndex++;
        mMonitor.Wait(PR_MillisecondsToInterval(duration));
      }
      else {
        mMonitor.Wait();
      }
    }
    

    vibrator_on() is the Gonk HAL API that turns on the vibrator motor. Internally, this method sends a message to the kernel driver by writing a value to a kernel object using sysfs.

    Fallback HAL API implementations

    The Gecko HAL APIs are supported across all platforms. When Gecko is built for a platform that doesn't expose an interface to vibration motors (such as a desktop computer), then a fallback implementation of the HAL API is used. For vibration, this is implemented in hal/fallback/FallbackVibration.cpp.

    void Vibrate(const nsTArray<uint32_t> &pattern) {
    }

    Sandbox implementations

    Because most web content runs in content processes with low privileges, we can't assume those processes have the privileges needed to be able to (for example), turn on and off the vibration motor. In addition, we want to have a central location for handling potential race conditions. In the Gecko HAL, this is done through a "sandbox" implementation of the HAL. This sandbox implementation simply proxies requests made by content processes and forwards them to the "Gecko server" process. The proxy requests are sent using IPDL.

    For vibration, this is handled by the Vibrate() function implemented in hal/sandbox/SandboxHal.cpp:

    void Vibrate(const nsTArray<uint32_t>& pattern, const WindowIdentifier &id) {
      AutoInfallibleTArray<uint32_t, 8> p(pattern);
    
      WindowIdentifier newID(id);
      newID.AppendProcessID();
      Hal()->SendVibrate(p, newID.AsArray(), GetTabChildFrom(newID.GetWindow()));
    }

    This sends a message defined by the PHal interface, described by IPDL in hal/sandbox/PHal.ipdl. This method is described more or less as follows:

    Vibrate(uint32_t[] pattern);

    The receiver of this message is the HalParent::RecvVibrate() method in hal/sandbox/SandboxHal.cpp, which looks like this:

    virtual bool RecvVibrate(const InfallibleTArray<unsigned int>& pattern,
                const InfallibleTArray<uint64_t> &id,
                PBrowserParent *browserParent) MOZ_OVERRIDE {
    
      hal::Vibrate(pattern, newID);
      return true;
    }

    This omits some details that aren't relevant to this discussion; however, it shows how the message progresses from a content process through Gecko to Gonk, then to the Gonk HAL implementation of Vibrate(), and eventually to the graphics driver.

    DOM APIs

    DOM interfaces are, in essence, how web content communicates with Gecko. There's more involved than that, and if you're interested in added details, you can read about the DOM. DOM interfaces are defined using IDL, which comprises both a foreign function interface (FFI) and object model (OM) between JavaScript and C++.

    The vibration API is exposed to web content through an IDL interface, which is provided in nsIDOMNavigator.idl:

    [implicit_jscontext] void mozVibrate(in jsval aPattern);

    The jsval argument indicates that mozVibrate() (which is our vendor-prefixed implementation of this non-finalized vibration specification) accepts as input any JavaScript value. The IDL compiler, xpidl, generates a C++ interface that's then implemented by the Navigator class in Navigator.cpp.

    NS_IMETHODIMP Navigator::MozVibrate(const jsval& aPattern, JSContext* cx) {
      // ...
      hal::Vibrate(pattern);
      return NS_OK;
    }

    There's a lot more code in this method than what you see here, but it's not important for the purposes of this discussion. The point is that the call to hal::Vibrate() transfers control from the DOM to the Gecko HAL. From there, we enter the HAL implementation discussed in the previous section and work our way down toward the graphics driver. On top of that, the DOM implementation doesn't care at all what platform it's running on (Gonk, Windows, Mac OS X, or anything else). It also doesn't care whether the code is running in a content process or in the Gecko server process. Those details are all left to lower levels of the system to deal with.

    The vibration API is a very simple API, which makes it a good example. The SMS API is an example of a more complex API which uses its own "remoting" layer connecting content processes to the server.

    Radio Interface Layer (RIL)

    The RIL was mentioned in the section The userspace process architecture. This section will examine how the various pieces of this layer interact in a bit more detail.

    The main components involved in the RIL are:

    rild
    The daemon that talks to the proprietary modem firmware.
    rilproxy
    The daemon that proxies messages between rild and Gecko (which is implemented in the b2g process). This overcomes the permission problem that arises when trying to talk to rild directly, since rild can only be communicated with from within the radio group.
    b2g
    This process, also known as the chrome process, implements Gecko. The portions of it that relate to the Radio Interface Layer are dom/system/gonk/ril_worker.js (which implements a worker thread that talks to rild through rilproxy and implements the radio state machine; and the nsIRadioInterfaceLayer interface, which is the main thread's XPCOM service that acts primarily as a message exchange between the ril_worker.js thread and various other Gecko components, including the Gecko content process.
    Gecko's content process
    Within Gecko's content process, the nsIRILContentHelper interface provides an XPCOM service that lets code implementing parts of the DOM, such as the Telephony and SMS APIs talk to the radio interface, which is in the chrome process.

    Example: Communicating from rild to the DOM

    Let's take a look at an example of how the lower level parts of the system communicate with DOM code. When the modem receives an incoming call, it notifies rild using a proprietary mechanism. rild then prepares a message for its client according to the "open" protocol, which is described in ril.h. In the case of an incoming call, a RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED message is generated and sent by rild to rilproxy.

    rilproxy, implemented in rilproxy.c, receives this message in its main loop, which polls its connection to rild using code like this:

    ret = read(rilproxy_rw, data, 1024);
    
    if(ret > 0) {
      writeToSocket(rild_rw, data, ret);
    }

    Once the message is received from rild, it's then forwarded along to Gecko on the socket that connects rilproxy to Gecko. Gecko receives the forwarded message on its IPC thread:

    int ret = read(fd, mIncoming->Data, 1024);
    // ... handle errors ...
    mIncoming->mSize = ret;
    sConsumer->MessageReceived(mIncoming.forget());
    

    The consumer of these messages is SystemWorkerManager, which repackages the messages and dispatches them to the ril_worker.js thread that implements the RIL state machine; this is done in the RILReceiver::MessageReceived() method:

    virtual void MessageReceived(RilRawData *aMessage) {
      nsRefPtr<DispatchRILEvent> dre(new DispatchRILEvent(aMessage));
      mDispatcher->PostTask(dre);
    }

    The task posted to that thread in turn calls the onRILMessage() function, which is implemented in JavaScript. This is done using the JavaScript API function JS_CallFunctionName():

    return JS_CallFunctionName(aCx, obj, "onRILMessage", NS_ARRAY_LENGTH(argv),
                               argv, argv);

    onRILMessage() is implemented in dom/system/gonk/ril_worker.js, which processes the message bytes and chops them into parcels. Each complete parcel is then dispatched to individual handler methods as appropriate:

    handleParcel: function handleParcel(request_type, length) {
      let method = this[request_type];
      if (typeof method == "function") {
        if (DEBUG) debug("Handling parcel as " + method.name);
        method.call(this, length);
      }
    }
    

    This code works by getting the request type from the object, making sure it's defined as a function in the JavaScript code, then calling the method. Since ril_worker.js implements each request type in a method given the same name as the request type, this is very simple.

    In our example, RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED, the following handler is called:

    RIL[UNSOLICITED_RESPONSE_CALL_STATE_CHANGED] = function UNSOLICITED_RESPONSE_CALL_STATE_CHANGED() {
      this.getCurrentCalls();
    };

    As you see in the code above, when notification is received that the call state has changed, the state machine simply fetches the current call state by calling the getCurrentCall() method:

    getCurrentCalls: function getCurrentCalls() {
      Buf.simpleRequest(REQUEST_GET_CURRENT_CALLS);
    }

    This sends a request back to rild to request the state of all currently active calls. The request flows back along a similar path the RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED message followed, but in the opposite direction (that is, from ril_worker.js to SystemWorkerManager to Ril.cpp, then rilproxy and finally to the rild socket). rild then responds in kind, back along the same path, eventually arriving in ril_worker.js's handler for the REQUEST_GET_CURRENT_CALLS message. And thus bidirectional communication occurs.

    The call state is then processed and compared to the previous state; if there's a change of state, ril_worker.js notifies the nsIRadioInterfaceLayer service on the main thread:

    _handleChangedCallState: function _handleChangedCallState(changedCall) {
      let message = {type: "callStateChange",
                     call: changedCall};
      this.sendDOMMessage(message);
    }

    nsIRadioInterfaceLayer is implemented in dom/system/gonk/RadioInterfaceLayer.js; the message is received by its onmessage() method:

     onmessage: function onmessage(event) {
       let message = event.data;
       debug("Received message from worker: " + JSON.stringify(message));
       switch (message.type) {
         case "callStateChange":
           // This one will handle its own notifications.
           this.handleCallStateChange(message.call);
           break;
       ...
    

    All this really does is dispatch the message to the content process using the Parent Process Message Manager (PPMM):

    handleCallStateChange: function handleCallStateChange(call) {
      [some internal state updating]
      ppmm.sendAsyncMessage("RIL:CallStateChanged", call);
    }

    In the content process, the message is received by receiveMessage() method in the nsIRILContentHelper service, from the Child Process Message Manager (CPMM):

    receiveMessage: function receiveMessage(msg) {
      let request;
      debug("Received message '" + msg.name + "': " + JSON.stringify(msg.json));
      switch (msg.name) {
        case "RIL:CallStateChanged":
          this._deliverTelephonyCallback("callStateChanged",
                                         [msg.json.callIndex, msg.json.state,
                                         msg.json.number, msg.json.isActive]);
          break;

    This, in turn, calls the nsIRILTelephonyCallback.callStateChanged() methods on every registered telephony callback object. Every web application that accesses the window.navigator.mozTelephony API has registered one such callback object that dispatches events to the JavaScript code in the web application, either as a state change of an existing call object or a new incoming call event.

    NS_IMETHODIMP Telephony::CallStateChanged(PRUint32 aCallIndex, PRUint16 aCallState,
                                              const nsAString& aNumber, bool aIsActive) {
      [...]
     
      if (modifiedCall) {
        // Change state.
        modifiedCall->ChangeState(aCallState);
        
        // See if this should replace our current active call.
        if (aIsActive) {
          mActiveCall = modifiedCall;
        }
        
        return NS_OK;
      }
     
      nsRefPtr<TelephonyCall> call =
              TelephonyCall::Create(this, aNumber, aCallState, aCallIndex);
      nsRefPtr<CallEvent> event = CallEvent::Create(call);
      nsresult rv = event->Dispatch(ToIDOMEventTarget(), NS_LITERAL_STRING("incoming"));
      NS_ENSURE_SUCCESS(rv, rv);
      return NS_OK;
    }

    Applications can receive these events and update their user interface and so forth:

    handleEvent: function fm_handleEvent(evt) {
      switch (evt.call.state) {
        case 'connected':
          this.connected();
          break;
        case 'disconnected':
          this.disconnected();
          break;
        default:
          break;
      }
    }

    Take a look at the implementation of handleEvent() in the Dialer application as an extended example.

    3G data

    There is a RIL message that initiates a "data call" to the cellular service; this enables data transfer mode in the modem. This data call ends up creating and activating a Point-to-Point Protocol (PPP) interface device in the Linux kernel that can be configured using the usual interfaces.

    Note: This section needs to be written.

    This section lists DOM APIs that are related to RIL communications.

    WiFi

    The WiFi backend for Firefox OS simply uses wpa_supplicant to do most of the work. That means that the backend's primary job is to simply manage the supplicant, and to do some auxiliary tasks such as loading the WiFi driver and enabling or disabling the network interface. In essence, this means that the backend is a state machine, with the states following the state of the supplicant.

    Note: Much of the interesting stuff that happens in WiFi depends deeply on possible state changes in the wpa_supplicant process.

    The implementation of the WiFi component is broken up into two files:

    dom/wifi/DOMWifiManager.js
    Implements the API that's exposed to web content, as defined in nsIWifi.idl.
    dom/wifi/WifiWorker.js
    Implements the state machine and the code that drives the supplicant.

    These two files communicate with one another using the message manager. The backend listens for messages requesting certain actions, such as "associate", and responds with a message when the requested action has been completed.

    The DOM side listens for the response methods as well as several event messages that indicate state changes and information updates.

    Note: Any synchromous DOM APIs are implemented by caching data on that side of the pipe. Synchronous messages are avoided whenever possible.

    WifiWorker.js

    This file implements the main logic behind the WiFi interface. It runs in the chrome process (in multi-process builds) and is instantiated by the SystemWorkerManager. The file is generally broken into two sections: a giant anonymous function and WifiWorker (and its prototype). The anonymous function ends up being the WifiManager by providing a local API, including notifications for events such as connection to the supplicant and scan results being available. In general, it contains little logic and lets its sole consumer control its actions while it simply responds with the requested information and controls the details of the connection with the supplicant.

    The WifiWorker object sits between the WifiManager and the DOM. It reacts to events and forwards them to the DOM; in turn, it receives requests from the DOM and performs the appropriate actions on the supplicant. It also maintains state information about the supplicant and what it needs to do next.

    DOMWifiManager.js

    This implements the DOM API, transmitting messages back and forth between callers and the actual WiFi worker. There's very little logic involved.

    Note: In order to avoid synchronous messages to the chrome process, the WiFi Manager does need to cache the state based on the received event.

    There's a single synchronous message, which is sent at the time the DOM API is instantiated, in order to get the current state of the supplicant.

    DHCP

    DHCP and DNS are handled by dhcpcd, the standard Linux DHCP client. However, it's not able to react when the network connection is lost. Because of this, Firefox OS kills and restarts dhcpcd each time it connects to a given wireless network.

    dhcpcd is also responsible for setting the default route; we call into the network manager to tell the kernel about DNS servers.

    Network Manager

    The Network Manager configures network interfaces opened by the 3G data and WiFi components.

    Note: This needs to be written.

     

    문서 태그 및 공헌자

    Contributors to this page: sjpark, jongphil15@gmial.com, webix, springofmylife
    최종 변경: webix,