Home | History | Annotate | Download | only in libril
      1 /* //device/libs/telephony/ril.cpp
      2 **
      3 ** Copyright 2006, The Android Open Source Project
      4 **
      5 ** Licensed under the Apache License, Version 2.0 (the "License");
      6 ** you may not use this file except in compliance with the License.
      7 ** You may obtain a copy of the License at
      8 **
      9 **     http://www.apache.org/licenses/LICENSE-2.0
     10 **
     11 ** Unless required by applicable law or agreed to in writing, software
     12 ** distributed under the License is distributed on an "AS IS" BASIS,
     13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 ** See the License for the specific language governing permissions and
     15 ** limitations under the License.
     16 */
     17 
     18 #define LOG_TAG "RILC"
     19 
     20 #include <hardware_legacy/power.h>
     21 #include <telephony/ril.h>
     22 #include <telephony/ril_cdma_sms.h>
     23 #include <cutils/sockets.h>
     24 #include <cutils/jstring.h>
     25 #include <telephony/record_stream.h>
     26 #include <utils/Log.h>
     27 #include <utils/SystemClock.h>
     28 #include <pthread.h>
     29 #include <binder/Parcel.h>
     30 #include <cutils/jstring.h>
     31 #include <sys/types.h>
     32 #include <sys/limits.h>
     33 #include <sys/system_properties.h>
     34 #include <pwd.h>
     35 #include <stdio.h>
     36 #include <stdlib.h>
     37 #include <stdarg.h>
     38 #include <string.h>
     39 #include <unistd.h>
     40 #include <fcntl.h>
     41 #include <time.h>
     42 #include <errno.h>
     43 #include <assert.h>
     44 #include <ctype.h>
     45 #include <sys/un.h>
     46 #include <assert.h>
     47 #include <netinet/in.h>
     48 #include <cutils/properties.h>
     49 #include <RilSapSocket.h>
     50 
     51 extern "C" void
     52 RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen);
     53 
     54 extern "C" void
     55 RIL_onRequestAck(RIL_Token t);
     56 namespace android {
     57 
     58 #define PHONE_PROCESS "radio"
     59 #define BLUETOOTH_PROCESS "bluetooth"
     60 
     61 #define SOCKET_NAME_RIL "rild"
     62 #define SOCKET2_NAME_RIL "rild2"
     63 #define SOCKET3_NAME_RIL "rild3"
     64 #define SOCKET4_NAME_RIL "rild4"
     65 
     66 #define SOCKET_NAME_RIL_DEBUG "rild-debug"
     67 
     68 #define ANDROID_WAKE_LOCK_NAME "radio-interface"
     69 
     70 #define ANDROID_WAKE_LOCK_SECS 0
     71 #define ANDROID_WAKE_LOCK_USECS 200000
     72 
     73 #define PROPERTY_RIL_IMPL "gsm.version.ril-impl"
     74 
     75 // match with constant in RIL.java
     76 #define MAX_COMMAND_BYTES (8 * 1024)
     77 
     78 // Basically: memset buffers that the client library
     79 // shouldn't be using anymore in an attempt to find
     80 // memory usage issues sooner.
     81 #define MEMSET_FREED 1
     82 
     83 #define NUM_ELEMS(a)     (sizeof (a) / sizeof (a)[0])
     84 
     85 #define MIN(a,b) ((a)<(b) ? (a) : (b))
     86 
     87 /* Constants for response types */
     88 #define RESPONSE_SOLICITED 0
     89 #define RESPONSE_UNSOLICITED 1
     90 #define RESPONSE_SOLICITED_ACK 2
     91 #define RESPONSE_SOLICITED_ACK_EXP 3
     92 #define RESPONSE_UNSOLICITED_ACK_EXP 4
     93 
     94 /* Negative values for private RIL errno's */
     95 #define RIL_ERRNO_INVALID_RESPONSE -1
     96 #define RIL_ERRNO_NO_MEMORY -12
     97 
     98 // request, response, and unsolicited msg print macro
     99 #define PRINTBUF_SIZE 8096
    100 
    101 // Enable verbose logging
    102 #define VDBG 0
    103 
    104 // Enable RILC log
    105 #define RILC_LOG 0
    106 
    107 #if RILC_LOG
    108     #define startRequest           sprintf(printBuf, "(")
    109     #define closeRequest           sprintf(printBuf, "%s)", printBuf)
    110     #define printRequest(token, req)           \
    111             RLOGD("[%04d]> %s %s", token, requestToString(req), printBuf)
    112 
    113     #define startResponse           sprintf(printBuf, "%s {", printBuf)
    114     #define closeResponse           sprintf(printBuf, "%s}", printBuf)
    115     #define printResponse           RLOGD("%s", printBuf)
    116 
    117     #define clearPrintBuf           printBuf[0] = 0
    118     #define removeLastChar          printBuf[strlen(printBuf)-1] = 0
    119     #define appendPrintBuf(x...)    snprintf(printBuf, PRINTBUF_SIZE, x)
    120 #else
    121     #define startRequest
    122     #define closeRequest
    123     #define printRequest(token, req)
    124     #define startResponse
    125     #define closeResponse
    126     #define printResponse
    127     #define clearPrintBuf
    128     #define removeLastChar
    129     #define appendPrintBuf(x...)
    130 #endif
    131 
    132 enum WakeType {DONT_WAKE, WAKE_PARTIAL};
    133 
    134 typedef struct {
    135     int requestNumber;
    136     void (*dispatchFunction) (Parcel &p, struct RequestInfo *pRI);
    137     int(*responseFunction) (Parcel &p, void *response, size_t responselen);
    138 } CommandInfo;
    139 
    140 typedef struct {
    141     int requestNumber;
    142     int (*responseFunction) (Parcel &p, void *response, size_t responselen);
    143     WakeType wakeType;
    144 } UnsolResponseInfo;
    145 
    146 typedef struct RequestInfo {
    147     int32_t token;      //this is not RIL_Token
    148     CommandInfo *pCI;
    149     struct RequestInfo *p_next;
    150     char cancelled;
    151     char local;         // responses to local commands do not go back to command process
    152     RIL_SOCKET_ID socket_id;
    153     int wasAckSent;    // Indicates whether an ack was sent earlier
    154 } RequestInfo;
    155 
    156 typedef struct UserCallbackInfo {
    157     RIL_TimedCallback p_callback;
    158     void *userParam;
    159     struct ril_event event;
    160     struct UserCallbackInfo *p_next;
    161 } UserCallbackInfo;
    162 
    163 extern "C" const char * requestToString(int request);
    164 extern "C" const char * failCauseToString(RIL_Errno);
    165 extern "C" const char * callStateToString(RIL_CallState);
    166 extern "C" const char * radioStateToString(RIL_RadioState);
    167 extern "C" const char * rilSocketIdToString(RIL_SOCKET_ID socket_id);
    168 
    169 extern "C"
    170 char rild[MAX_SOCKET_NAME_LENGTH] = SOCKET_NAME_RIL;
    171 /*******************************************************************/
    172 
    173 RIL_RadioFunctions s_callbacks = {0, NULL, NULL, NULL, NULL, NULL};
    174 static int s_registerCalled = 0;
    175 
    176 static pthread_t s_tid_dispatch;
    177 static pthread_t s_tid_reader;
    178 static int s_started = 0;
    179 
    180 static int s_fdDebug = -1;
    181 static int s_fdDebug_socket2 = -1;
    182 
    183 static int s_fdWakeupRead;
    184 static int s_fdWakeupWrite;
    185 
    186 int s_wakelock_count = 0;
    187 
    188 static struct ril_event s_commands_event;
    189 static struct ril_event s_wakeupfd_event;
    190 static struct ril_event s_listen_event;
    191 static SocketListenParam s_ril_param_socket;
    192 
    193 static pthread_mutex_t s_pendingRequestsMutex = PTHREAD_MUTEX_INITIALIZER;
    194 static pthread_mutex_t s_writeMutex = PTHREAD_MUTEX_INITIALIZER;
    195 static pthread_mutex_t s_wakeLockCountMutex = PTHREAD_MUTEX_INITIALIZER;
    196 static RequestInfo *s_pendingRequests = NULL;
    197 
    198 #if (SIM_COUNT >= 2)
    199 static struct ril_event s_commands_event_socket2;
    200 static struct ril_event s_listen_event_socket2;
    201 static SocketListenParam s_ril_param_socket2;
    202 
    203 static pthread_mutex_t s_pendingRequestsMutex_socket2  = PTHREAD_MUTEX_INITIALIZER;
    204 static pthread_mutex_t s_writeMutex_socket2            = PTHREAD_MUTEX_INITIALIZER;
    205 static RequestInfo *s_pendingRequests_socket2          = NULL;
    206 #endif
    207 
    208 #if (SIM_COUNT >= 3)
    209 static struct ril_event s_commands_event_socket3;
    210 static struct ril_event s_listen_event_socket3;
    211 static SocketListenParam s_ril_param_socket3;
    212 
    213 static pthread_mutex_t s_pendingRequestsMutex_socket3  = PTHREAD_MUTEX_INITIALIZER;
    214 static pthread_mutex_t s_writeMutex_socket3            = PTHREAD_MUTEX_INITIALIZER;
    215 static RequestInfo *s_pendingRequests_socket3          = NULL;
    216 #endif
    217 
    218 #if (SIM_COUNT >= 4)
    219 static struct ril_event s_commands_event_socket4;
    220 static struct ril_event s_listen_event_socket4;
    221 static SocketListenParam s_ril_param_socket4;
    222 
    223 static pthread_mutex_t s_pendingRequestsMutex_socket4  = PTHREAD_MUTEX_INITIALIZER;
    224 static pthread_mutex_t s_writeMutex_socket4            = PTHREAD_MUTEX_INITIALIZER;
    225 static RequestInfo *s_pendingRequests_socket4          = NULL;
    226 #endif
    227 
    228 static struct ril_event s_wake_timeout_event;
    229 static struct ril_event s_debug_event;
    230 
    231 
    232 static const struct timeval TIMEVAL_WAKE_TIMEOUT = {ANDROID_WAKE_LOCK_SECS,ANDROID_WAKE_LOCK_USECS};
    233 
    234 
    235 static pthread_mutex_t s_startupMutex = PTHREAD_MUTEX_INITIALIZER;
    236 static pthread_cond_t s_startupCond = PTHREAD_COND_INITIALIZER;
    237 
    238 static pthread_mutex_t s_dispatchMutex = PTHREAD_MUTEX_INITIALIZER;
    239 static pthread_cond_t s_dispatchCond = PTHREAD_COND_INITIALIZER;
    240 
    241 static RequestInfo *s_toDispatchHead = NULL;
    242 static RequestInfo *s_toDispatchTail = NULL;
    243 
    244 static UserCallbackInfo *s_last_wake_timeout_info = NULL;
    245 
    246 static void *s_lastNITZTimeData = NULL;
    247 static size_t s_lastNITZTimeDataSize;
    248 
    249 #if RILC_LOG
    250     static char printBuf[PRINTBUF_SIZE];
    251 #endif
    252 
    253 /*******************************************************************/
    254 static int sendResponse (Parcel &p, RIL_SOCKET_ID socket_id);
    255 
    256 static void dispatchVoid (Parcel& p, RequestInfo *pRI);
    257 static void dispatchString (Parcel& p, RequestInfo *pRI);
    258 static void dispatchStrings (Parcel& p, RequestInfo *pRI);
    259 static void dispatchInts (Parcel& p, RequestInfo *pRI);
    260 static void dispatchDial (Parcel& p, RequestInfo *pRI);
    261 static void dispatchSIM_IO (Parcel& p, RequestInfo *pRI);
    262 static void dispatchSIM_APDU (Parcel& p, RequestInfo *pRI);
    263 static void dispatchCallForward(Parcel& p, RequestInfo *pRI);
    264 static void dispatchRaw(Parcel& p, RequestInfo *pRI);
    265 static void dispatchSmsWrite (Parcel &p, RequestInfo *pRI);
    266 static void dispatchDataCall (Parcel& p, RequestInfo *pRI);
    267 static void dispatchVoiceRadioTech (Parcel& p, RequestInfo *pRI);
    268 static void dispatchSetInitialAttachApn (Parcel& p, RequestInfo *pRI);
    269 static void dispatchCdmaSubscriptionSource (Parcel& p, RequestInfo *pRI);
    270 
    271 static void dispatchCdmaSms(Parcel &p, RequestInfo *pRI);
    272 static void dispatchImsSms(Parcel &p, RequestInfo *pRI);
    273 static void dispatchImsCdmaSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef);
    274 static void dispatchImsGsmSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef);
    275 static void dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI);
    276 static void dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI);
    277 static void dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI);
    278 static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI);
    279 static void dispatchNVReadItem(Parcel &p, RequestInfo *pRI);
    280 static void dispatchNVWriteItem(Parcel &p, RequestInfo *pRI);
    281 static void dispatchUiccSubscripton(Parcel &p, RequestInfo *pRI);
    282 static void dispatchSimAuthentication(Parcel &p, RequestInfo *pRI);
    283 static void dispatchDataProfile(Parcel &p, RequestInfo *pRI);
    284 static void dispatchRadioCapability(Parcel &p, RequestInfo *pRI);
    285 static int responseInts(Parcel &p, void *response, size_t responselen);
    286 static int responseFailCause(Parcel &p, void *response, size_t responselen);
    287 static int responseStrings(Parcel &p, void *response, size_t responselen);
    288 static int responseString(Parcel &p, void *response, size_t responselen);
    289 static int responseVoid(Parcel &p, void *response, size_t responselen);
    290 static int responseCallList(Parcel &p, void *response, size_t responselen);
    291 static int responseSMS(Parcel &p, void *response, size_t responselen);
    292 static int responseSIM_IO(Parcel &p, void *response, size_t responselen);
    293 static int responseCallForwards(Parcel &p, void *response, size_t responselen);
    294 static int responseDataCallList(Parcel &p, void *response, size_t responselen);
    295 static int responseSetupDataCall(Parcel &p, void *response, size_t responselen);
    296 static int responseRaw(Parcel &p, void *response, size_t responselen);
    297 static int responseSsn(Parcel &p, void *response, size_t responselen);
    298 static int responseSimStatus(Parcel &p, void *response, size_t responselen);
    299 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen);
    300 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen);
    301 static int responseCdmaSms(Parcel &p, void *response, size_t responselen);
    302 static int responseCellList(Parcel &p, void *response, size_t responselen);
    303 static int responseCdmaInformationRecords(Parcel &p,void *response, size_t responselen);
    304 static int responseRilSignalStrength(Parcel &p,void *response, size_t responselen);
    305 static int responseCallRing(Parcel &p, void *response, size_t responselen);
    306 static int responseCdmaSignalInfoRecord(Parcel &p,void *response, size_t responselen);
    307 static int responseCdmaCallWaiting(Parcel &p,void *response, size_t responselen);
    308 static int responseSimRefresh(Parcel &p, void *response, size_t responselen);
    309 static int responseCellInfoList(Parcel &p, void *response, size_t responselen);
    310 static int responseHardwareConfig(Parcel &p, void *response, size_t responselen);
    311 static int responseDcRtInfo(Parcel &p, void *response, size_t responselen);
    312 static int responseRadioCapability(Parcel &p, void *response, size_t responselen);
    313 static int responseSSData(Parcel &p, void *response, size_t responselen);
    314 static int responseLceStatus(Parcel &p, void *response, size_t responselen);
    315 static int responseLceData(Parcel &p, void *response, size_t responselen);
    316 static int responseActivityData(Parcel &p, void *response, size_t responselen);
    317 
    318 static int decodeVoiceRadioTechnology (RIL_RadioState radioState);
    319 static int decodeCdmaSubscriptionSource (RIL_RadioState radioState);
    320 static RIL_RadioState processRadioState(RIL_RadioState newRadioState);
    321 static void grabPartialWakeLock();
    322 static void releaseWakeLock();
    323 static void wakeTimeoutCallback(void *);
    324 
    325 static bool isServiceTypeCfQuery(RIL_SsServiceType serType, RIL_SsRequestType reqType);
    326 
    327 static bool isDebuggable();
    328 
    329 #ifdef RIL_SHLIB
    330 #if defined(ANDROID_MULTI_SIM)
    331 extern "C" void RIL_onUnsolicitedResponse(int unsolResponse, const void *data,
    332                                 size_t datalen, RIL_SOCKET_ID socket_id);
    333 #else
    334 extern "C" void RIL_onUnsolicitedResponse(int unsolResponse, const void *data,
    335                                 size_t datalen);
    336 #endif
    337 #endif
    338 
    339 #if defined(ANDROID_MULTI_SIM)
    340 #define RIL_UNSOL_RESPONSE(a, b, c, d) RIL_onUnsolicitedResponse((a), (b), (c), (d))
    341 #define CALL_ONREQUEST(a, b, c, d, e) s_callbacks.onRequest((a), (b), (c), (d), (e))
    342 #define CALL_ONSTATEREQUEST(a) s_callbacks.onStateRequest(a)
    343 #else
    344 #define RIL_UNSOL_RESPONSE(a, b, c, d) RIL_onUnsolicitedResponse((a), (b), (c))
    345 #define CALL_ONREQUEST(a, b, c, d, e) s_callbacks.onRequest((a), (b), (c), (d))
    346 #define CALL_ONSTATEREQUEST(a) s_callbacks.onStateRequest()
    347 #endif
    348 
    349 static UserCallbackInfo * internalRequestTimedCallback
    350     (RIL_TimedCallback callback, void *param,
    351         const struct timeval *relativeTime);
    352 
    353 /** Index == requestNumber */
    354 static CommandInfo s_commands[] = {
    355 #include "ril_commands.h"
    356 };
    357 
    358 static UnsolResponseInfo s_unsolResponses[] = {
    359 #include "ril_unsol_commands.h"
    360 };
    361 
    362 /* For older RILs that do not support new commands RIL_REQUEST_VOICE_RADIO_TECH and
    363    RIL_UNSOL_VOICE_RADIO_TECH_CHANGED messages, decode the voice radio tech from
    364    radio state message and store it. Every time there is a change in Radio State
    365    check to see if voice radio tech changes and notify telephony
    366  */
    367 int voiceRadioTech = -1;
    368 
    369 /* For older RILs that do not support new commands RIL_REQUEST_GET_CDMA_SUBSCRIPTION_SOURCE
    370    and RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED messages, decode the subscription
    371    source from radio state and store it. Every time there is a change in Radio State
    372    check to see if subscription source changed and notify telephony
    373  */
    374 int cdmaSubscriptionSource = -1;
    375 
    376 /* For older RILs that do not send RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, decode the
    377    SIM/RUIM state from radio state and store it. Every time there is a change in Radio State,
    378    check to see if SIM/RUIM status changed and notify telephony
    379  */
    380 int simRuimStatus = -1;
    381 
    382 static char * RIL_getRilSocketName() {
    383     return rild;
    384 }
    385 
    386 extern "C"
    387 void RIL_setRilSocketName(const char * s) {
    388     strncpy(rild, s, MAX_SOCKET_NAME_LENGTH);
    389 }
    390 
    391 static char *
    392 strdupReadString(Parcel &p) {
    393     size_t stringlen;
    394     const char16_t *s16;
    395 
    396     s16 = p.readString16Inplace(&stringlen);
    397 
    398     return strndup16to8(s16, stringlen);
    399 }
    400 
    401 static status_t
    402 readStringFromParcelInplace(Parcel &p, char *str, size_t maxLen) {
    403     size_t s16Len;
    404     const char16_t *s16;
    405 
    406     s16 = p.readString16Inplace(&s16Len);
    407     if (s16 == NULL) {
    408         return NO_MEMORY;
    409     }
    410     size_t strLen = strnlen16to8(s16, s16Len);
    411     if ((strLen + 1) > maxLen) {
    412         return NO_MEMORY;
    413     }
    414     if (strncpy16to8(str, s16, strLen) == NULL) {
    415         return NO_MEMORY;
    416     } else {
    417         return NO_ERROR;
    418     }
    419 }
    420 
    421 static void writeStringToParcel(Parcel &p, const char *s) {
    422     char16_t *s16;
    423     size_t s16_len;
    424     s16 = strdup8to16(s, &s16_len);
    425     p.writeString16(s16, s16_len);
    426     free(s16);
    427 }
    428 
    429 
    430 static void
    431 memsetString (char *s) {
    432     if (s != NULL) {
    433         memset (s, 0, strlen(s));
    434     }
    435 }
    436 
    437 void   nullParcelReleaseFunction (const uint8_t* data, size_t dataSize,
    438                                     const size_t* objects, size_t objectsSize,
    439                                         void* cookie) {
    440     // do nothing -- the data reference lives longer than the Parcel object
    441 }
    442 
    443 /**
    444  * To be called from dispatch thread
    445  * Issue a single local request, ensuring that the response
    446  * is not sent back up to the command process
    447  */
    448 static void
    449 issueLocalRequest(int request, void *data, int len, RIL_SOCKET_ID socket_id) {
    450     RequestInfo *pRI;
    451     int ret;
    452     /* Hook for current context */
    453     /* pendingRequestsMutextHook refer to &s_pendingRequestsMutex */
    454     pthread_mutex_t* pendingRequestsMutexHook = &s_pendingRequestsMutex;
    455     /* pendingRequestsHook refer to &s_pendingRequests */
    456     RequestInfo**    pendingRequestsHook = &s_pendingRequests;
    457 
    458 #if (SIM_COUNT == 2)
    459     if (socket_id == RIL_SOCKET_2) {
    460         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket2;
    461         pendingRequestsHook = &s_pendingRequests_socket2;
    462     }
    463 #endif
    464 
    465     pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
    466     if (pRI == NULL) {
    467         RLOGE("Memory allocation failed for request %s", requestToString(request));
    468         return;
    469     }
    470 
    471     pRI->local = 1;
    472     pRI->token = 0xffffffff;        // token is not used in this context
    473     pRI->pCI = &(s_commands[request]);
    474     pRI->socket_id = socket_id;
    475 
    476     ret = pthread_mutex_lock(pendingRequestsMutexHook);
    477     assert (ret == 0);
    478 
    479     pRI->p_next = *pendingRequestsHook;
    480     *pendingRequestsHook = pRI;
    481 
    482     ret = pthread_mutex_unlock(pendingRequestsMutexHook);
    483     assert (ret == 0);
    484 
    485     RLOGD("C[locl]> %s", requestToString(request));
    486 
    487     CALL_ONREQUEST(request, data, len, pRI, pRI->socket_id);
    488 }
    489 
    490 
    491 
    492 static int
    493 processCommandBuffer(void *buffer, size_t buflen, RIL_SOCKET_ID socket_id) {
    494     Parcel p;
    495     status_t status;
    496     int32_t request;
    497     int32_t token;
    498     RequestInfo *pRI;
    499     int ret;
    500     /* Hook for current context */
    501     /* pendingRequestsMutextHook refer to &s_pendingRequestsMutex */
    502     pthread_mutex_t* pendingRequestsMutexHook = &s_pendingRequestsMutex;
    503     /* pendingRequestsHook refer to &s_pendingRequests */
    504     RequestInfo**    pendingRequestsHook = &s_pendingRequests;
    505 
    506     p.setData((uint8_t *) buffer, buflen);
    507 
    508     // status checked at end
    509     status = p.readInt32(&request);
    510     status = p.readInt32 (&token);
    511 
    512 #if (SIM_COUNT >= 2)
    513     if (socket_id == RIL_SOCKET_2) {
    514         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket2;
    515         pendingRequestsHook = &s_pendingRequests_socket2;
    516     }
    517 #if (SIM_COUNT >= 3)
    518     else if (socket_id == RIL_SOCKET_3) {
    519         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket3;
    520         pendingRequestsHook = &s_pendingRequests_socket3;
    521     }
    522 #endif
    523 #if (SIM_COUNT >= 4)
    524     else if (socket_id == RIL_SOCKET_4) {
    525         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket4;
    526         pendingRequestsHook = &s_pendingRequests_socket4;
    527     }
    528 #endif
    529 #endif
    530 
    531     if (status != NO_ERROR) {
    532         RLOGE("invalid request block");
    533         return 0;
    534     }
    535 
    536     // Received an Ack for the previous result sent to RIL.java,
    537     // so release wakelock and exit
    538     if (request == RIL_RESPONSE_ACKNOWLEDGEMENT) {
    539         releaseWakeLock();
    540         return 0;
    541     }
    542 
    543     if (request < 1 || request >= (int32_t)NUM_ELEMS(s_commands)) {
    544         Parcel pErr;
    545         RLOGE("unsupported request code %d token %d", request, token);
    546         // FIXME this should perhaps return a response
    547         pErr.writeInt32 (RESPONSE_SOLICITED);
    548         pErr.writeInt32 (token);
    549         pErr.writeInt32 (RIL_E_GENERIC_FAILURE);
    550 
    551         sendResponse(pErr, socket_id);
    552         return 0;
    553     }
    554 
    555     pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
    556     if (pRI == NULL) {
    557         RLOGE("Memory allocation failed for request %s", requestToString(request));
    558         return 0;
    559     }
    560 
    561     pRI->token = token;
    562     pRI->pCI = &(s_commands[request]);
    563     pRI->socket_id = socket_id;
    564 
    565     ret = pthread_mutex_lock(pendingRequestsMutexHook);
    566     assert (ret == 0);
    567 
    568     pRI->p_next = *pendingRequestsHook;
    569     *pendingRequestsHook = pRI;
    570 
    571     ret = pthread_mutex_unlock(pendingRequestsMutexHook);
    572     assert (ret == 0);
    573 
    574 /*    sLastDispatchedToken = token; */
    575 
    576     pRI->pCI->dispatchFunction(p, pRI);
    577 
    578     return 0;
    579 }
    580 
    581 static void
    582 invalidCommandBlock (RequestInfo *pRI) {
    583     RLOGE("invalid command block for token %d request %s",
    584                 pRI->token, requestToString(pRI->pCI->requestNumber));
    585 }
    586 
    587 /** Callee expects NULL */
    588 static void
    589 dispatchVoid (Parcel& p, RequestInfo *pRI) {
    590     clearPrintBuf;
    591     printRequest(pRI->token, pRI->pCI->requestNumber);
    592     CALL_ONREQUEST(pRI->pCI->requestNumber, NULL, 0, pRI, pRI->socket_id);
    593 }
    594 
    595 /** Callee expects const char * */
    596 static void
    597 dispatchString (Parcel& p, RequestInfo *pRI) {
    598     status_t status;
    599     size_t datalen;
    600     size_t stringlen;
    601     char *string8 = NULL;
    602 
    603     string8 = strdupReadString(p);
    604 
    605     startRequest;
    606     appendPrintBuf("%s%s", printBuf, string8);
    607     closeRequest;
    608     printRequest(pRI->token, pRI->pCI->requestNumber);
    609 
    610     CALL_ONREQUEST(pRI->pCI->requestNumber, string8,
    611                        sizeof(char *), pRI, pRI->socket_id);
    612 
    613 #ifdef MEMSET_FREED
    614     memsetString(string8);
    615 #endif
    616 
    617     free(string8);
    618     return;
    619 invalid:
    620     invalidCommandBlock(pRI);
    621     return;
    622 }
    623 
    624 /** Callee expects const char ** */
    625 static void
    626 dispatchStrings (Parcel &p, RequestInfo *pRI) {
    627     int32_t countStrings;
    628     status_t status;
    629     size_t datalen;
    630     char **pStrings;
    631 
    632     status = p.readInt32 (&countStrings);
    633 
    634     if (status != NO_ERROR) {
    635         goto invalid;
    636     }
    637 
    638     startRequest;
    639     if (countStrings == 0) {
    640         // just some non-null pointer
    641         pStrings = (char **)calloc(1, sizeof(char *));
    642         if (pStrings == NULL) {
    643             RLOGE("Memory allocation failed for request %s",
    644                     requestToString(pRI->pCI->requestNumber));
    645             closeRequest;
    646             return;
    647         }
    648 
    649         datalen = 0;
    650     } else if (countStrings < 0) {
    651         pStrings = NULL;
    652         datalen = 0;
    653     } else {
    654         datalen = sizeof(char *) * countStrings;
    655 
    656         pStrings = (char **)calloc(countStrings, sizeof(char *));
    657         if (pStrings == NULL) {
    658             RLOGE("Memory allocation failed for request %s",
    659                     requestToString(pRI->pCI->requestNumber));
    660             closeRequest;
    661             return;
    662         }
    663 
    664         for (int i = 0 ; i < countStrings ; i++) {
    665             pStrings[i] = strdupReadString(p);
    666             appendPrintBuf("%s%s,", printBuf, pStrings[i]);
    667         }
    668     }
    669     removeLastChar;
    670     closeRequest;
    671     printRequest(pRI->token, pRI->pCI->requestNumber);
    672 
    673     CALL_ONREQUEST(pRI->pCI->requestNumber, pStrings, datalen, pRI, pRI->socket_id);
    674 
    675     if (pStrings != NULL) {
    676         for (int i = 0 ; i < countStrings ; i++) {
    677 #ifdef MEMSET_FREED
    678             memsetString (pStrings[i]);
    679 #endif
    680             free(pStrings[i]);
    681         }
    682 
    683 #ifdef MEMSET_FREED
    684         memset(pStrings, 0, datalen);
    685 #endif
    686         free(pStrings);
    687     }
    688 
    689     return;
    690 invalid:
    691     invalidCommandBlock(pRI);
    692     return;
    693 }
    694 
    695 /** Callee expects const int * */
    696 static void
    697 dispatchInts (Parcel &p, RequestInfo *pRI) {
    698     int32_t count;
    699     status_t status;
    700     size_t datalen;
    701     int *pInts;
    702 
    703     status = p.readInt32 (&count);
    704 
    705     if (status != NO_ERROR || count <= 0) {
    706         goto invalid;
    707     }
    708 
    709     datalen = sizeof(int) * count;
    710     pInts = (int *)calloc(count, sizeof(int));
    711     if (pInts == NULL) {
    712         RLOGE("Memory allocation failed for request %s", requestToString(pRI->pCI->requestNumber));
    713         return;
    714     }
    715 
    716     startRequest;
    717     for (int i = 0 ; i < count ; i++) {
    718         int32_t t;
    719 
    720         status = p.readInt32(&t);
    721         pInts[i] = (int)t;
    722         appendPrintBuf("%s%d,", printBuf, t);
    723 
    724         if (status != NO_ERROR) {
    725             free(pInts);
    726             goto invalid;
    727         }
    728    }
    729    removeLastChar;
    730    closeRequest;
    731    printRequest(pRI->token, pRI->pCI->requestNumber);
    732 
    733    CALL_ONREQUEST(pRI->pCI->requestNumber, const_cast<int *>(pInts),
    734                        datalen, pRI, pRI->socket_id);
    735 
    736 #ifdef MEMSET_FREED
    737     memset(pInts, 0, datalen);
    738 #endif
    739     free(pInts);
    740     return;
    741 invalid:
    742     invalidCommandBlock(pRI);
    743     return;
    744 }
    745 
    746 
    747 /**
    748  * Callee expects const RIL_SMS_WriteArgs *
    749  * Payload is:
    750  *   int32_t status
    751  *   String pdu
    752  */
    753 static void
    754 dispatchSmsWrite (Parcel &p, RequestInfo *pRI) {
    755     RIL_SMS_WriteArgs args;
    756     int32_t t;
    757     status_t status;
    758 
    759     RLOGD("dispatchSmsWrite");
    760     memset (&args, 0, sizeof(args));
    761 
    762     status = p.readInt32(&t);
    763     args.status = (int)t;
    764 
    765     args.pdu = strdupReadString(p);
    766 
    767     if (status != NO_ERROR || args.pdu == NULL) {
    768         goto invalid;
    769     }
    770 
    771     args.smsc = strdupReadString(p);
    772 
    773     startRequest;
    774     appendPrintBuf("%s%d,%s,smsc=%s", printBuf, args.status,
    775         (char*)args.pdu,  (char*)args.smsc);
    776     closeRequest;
    777     printRequest(pRI->token, pRI->pCI->requestNumber);
    778 
    779     CALL_ONREQUEST(pRI->pCI->requestNumber, &args, sizeof(args), pRI, pRI->socket_id);
    780 
    781 #ifdef MEMSET_FREED
    782     memsetString (args.pdu);
    783 #endif
    784 
    785     free (args.pdu);
    786 
    787 #ifdef MEMSET_FREED
    788     memset(&args, 0, sizeof(args));
    789 #endif
    790 
    791     return;
    792 invalid:
    793     invalidCommandBlock(pRI);
    794     return;
    795 }
    796 
    797 /**
    798  * Callee expects const RIL_Dial *
    799  * Payload is:
    800  *   String address
    801  *   int32_t clir
    802  */
    803 static void
    804 dispatchDial (Parcel &p, RequestInfo *pRI) {
    805     RIL_Dial dial;
    806     RIL_UUS_Info uusInfo;
    807     int32_t sizeOfDial;
    808     int32_t t;
    809     int32_t uusPresent;
    810     status_t status;
    811 
    812     RLOGD("dispatchDial");
    813     memset (&dial, 0, sizeof(dial));
    814 
    815     dial.address = strdupReadString(p);
    816 
    817     status = p.readInt32(&t);
    818     dial.clir = (int)t;
    819 
    820     if (status != NO_ERROR || dial.address == NULL) {
    821         goto invalid;
    822     }
    823 
    824     if (s_callbacks.version < 3) { // Remove when partners upgrade to version 3
    825         uusPresent = 0;
    826         sizeOfDial = sizeof(dial) - sizeof(RIL_UUS_Info *);
    827     } else {
    828         status = p.readInt32(&uusPresent);
    829 
    830         if (status != NO_ERROR) {
    831             goto invalid;
    832         }
    833 
    834         if (uusPresent == 0) {
    835             dial.uusInfo = NULL;
    836         } else {
    837             int32_t len;
    838 
    839             memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
    840 
    841             status = p.readInt32(&t);
    842             uusInfo.uusType = (RIL_UUS_Type) t;
    843 
    844             status = p.readInt32(&t);
    845             uusInfo.uusDcs = (RIL_UUS_DCS) t;
    846 
    847             status = p.readInt32(&len);
    848             if (status != NO_ERROR) {
    849                 goto invalid;
    850             }
    851 
    852             // The java code writes -1 for null arrays
    853             if (((int) len) == -1) {
    854                 uusInfo.uusData = NULL;
    855                 len = 0;
    856             } else {
    857                 uusInfo.uusData = (char*) p.readInplace(len);
    858             }
    859 
    860             uusInfo.uusLength = len;
    861             dial.uusInfo = &uusInfo;
    862         }
    863         sizeOfDial = sizeof(dial);
    864     }
    865 
    866     startRequest;
    867     appendPrintBuf("%snum=%s,clir=%d", printBuf, dial.address, dial.clir);
    868     if (uusPresent) {
    869         appendPrintBuf("%s,uusType=%d,uusDcs=%d,uusLen=%d", printBuf,
    870                 dial.uusInfo->uusType, dial.uusInfo->uusDcs,
    871                 dial.uusInfo->uusLength);
    872     }
    873     closeRequest;
    874     printRequest(pRI->token, pRI->pCI->requestNumber);
    875 
    876     CALL_ONREQUEST(pRI->pCI->requestNumber, &dial, sizeOfDial, pRI, pRI->socket_id);
    877 
    878 #ifdef MEMSET_FREED
    879     memsetString (dial.address);
    880 #endif
    881 
    882     free (dial.address);
    883 
    884 #ifdef MEMSET_FREED
    885     memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
    886     memset(&dial, 0, sizeof(dial));
    887 #endif
    888 
    889     return;
    890 invalid:
    891     invalidCommandBlock(pRI);
    892     return;
    893 }
    894 
    895 /**
    896  * Callee expects const RIL_SIM_IO *
    897  * Payload is:
    898  *   int32_t command
    899  *   int32_t fileid
    900  *   String path
    901  *   int32_t p1, p2, p3
    902  *   String data
    903  *   String pin2
    904  *   String aidPtr
    905  */
    906 static void
    907 dispatchSIM_IO (Parcel &p, RequestInfo *pRI) {
    908     union RIL_SIM_IO {
    909         RIL_SIM_IO_v6 v6;
    910         RIL_SIM_IO_v5 v5;
    911     } simIO;
    912 
    913     int32_t t;
    914     int size;
    915     status_t status;
    916 
    917 #if VDBG
    918     RLOGD("dispatchSIM_IO");
    919 #endif
    920     memset (&simIO, 0, sizeof(simIO));
    921 
    922     // note we only check status at the end
    923 
    924     status = p.readInt32(&t);
    925     simIO.v6.command = (int)t;
    926 
    927     status = p.readInt32(&t);
    928     simIO.v6.fileid = (int)t;
    929 
    930     simIO.v6.path = strdupReadString(p);
    931 
    932     status = p.readInt32(&t);
    933     simIO.v6.p1 = (int)t;
    934 
    935     status = p.readInt32(&t);
    936     simIO.v6.p2 = (int)t;
    937 
    938     status = p.readInt32(&t);
    939     simIO.v6.p3 = (int)t;
    940 
    941     simIO.v6.data = strdupReadString(p);
    942     simIO.v6.pin2 = strdupReadString(p);
    943     simIO.v6.aidPtr = strdupReadString(p);
    944 
    945     startRequest;
    946     appendPrintBuf("%scmd=0x%X,efid=0x%X,path=%s,%d,%d,%d,%s,pin2=%s,aid=%s", printBuf,
    947         simIO.v6.command, simIO.v6.fileid, (char*)simIO.v6.path,
    948         simIO.v6.p1, simIO.v6.p2, simIO.v6.p3,
    949         (char*)simIO.v6.data,  (char*)simIO.v6.pin2, simIO.v6.aidPtr);
    950     closeRequest;
    951     printRequest(pRI->token, pRI->pCI->requestNumber);
    952 
    953     if (status != NO_ERROR) {
    954         goto invalid;
    955     }
    956 
    957     size = (s_callbacks.version < 6) ? sizeof(simIO.v5) : sizeof(simIO.v6);
    958     CALL_ONREQUEST(pRI->pCI->requestNumber, &simIO, size, pRI, pRI->socket_id);
    959 
    960 #ifdef MEMSET_FREED
    961     memsetString (simIO.v6.path);
    962     memsetString (simIO.v6.data);
    963     memsetString (simIO.v6.pin2);
    964     memsetString (simIO.v6.aidPtr);
    965 #endif
    966 
    967     free (simIO.v6.path);
    968     free (simIO.v6.data);
    969     free (simIO.v6.pin2);
    970     free (simIO.v6.aidPtr);
    971 
    972 #ifdef MEMSET_FREED
    973     memset(&simIO, 0, sizeof(simIO));
    974 #endif
    975 
    976     return;
    977 invalid:
    978     invalidCommandBlock(pRI);
    979     return;
    980 }
    981 
    982 /**
    983  * Callee expects const RIL_SIM_APDU *
    984  * Payload is:
    985  *   int32_t sessionid
    986  *   int32_t cla
    987  *   int32_t instruction
    988  *   int32_t p1, p2, p3
    989  *   String data
    990  */
    991 static void
    992 dispatchSIM_APDU (Parcel &p, RequestInfo *pRI) {
    993     int32_t t;
    994     status_t status;
    995     RIL_SIM_APDU apdu;
    996 
    997 #if VDBG
    998     RLOGD("dispatchSIM_APDU");
    999 #endif
   1000     memset (&apdu, 0, sizeof(RIL_SIM_APDU));
   1001 
   1002     // Note we only check status at the end. Any single failure leads to
   1003     // subsequent reads filing.
   1004     status = p.readInt32(&t);
   1005     apdu.sessionid = (int)t;
   1006 
   1007     status = p.readInt32(&t);
   1008     apdu.cla = (int)t;
   1009 
   1010     status = p.readInt32(&t);
   1011     apdu.instruction = (int)t;
   1012 
   1013     status = p.readInt32(&t);
   1014     apdu.p1 = (int)t;
   1015 
   1016     status = p.readInt32(&t);
   1017     apdu.p2 = (int)t;
   1018 
   1019     status = p.readInt32(&t);
   1020     apdu.p3 = (int)t;
   1021 
   1022     apdu.data = strdupReadString(p);
   1023 
   1024     startRequest;
   1025     appendPrintBuf("%ssessionid=%d,cla=%d,ins=%d,p1=%d,p2=%d,p3=%d,data=%s",
   1026         printBuf, apdu.sessionid, apdu.cla, apdu.instruction, apdu.p1, apdu.p2,
   1027         apdu.p3, (char*)apdu.data);
   1028     closeRequest;
   1029     printRequest(pRI->token, pRI->pCI->requestNumber);
   1030 
   1031     if (status != NO_ERROR) {
   1032         goto invalid;
   1033     }
   1034 
   1035     CALL_ONREQUEST(pRI->pCI->requestNumber, &apdu, sizeof(RIL_SIM_APDU), pRI, pRI->socket_id);
   1036 
   1037 #ifdef MEMSET_FREED
   1038     memsetString(apdu.data);
   1039 #endif
   1040     free(apdu.data);
   1041 
   1042 #ifdef MEMSET_FREED
   1043     memset(&apdu, 0, sizeof(RIL_SIM_APDU));
   1044 #endif
   1045 
   1046     return;
   1047 invalid:
   1048     invalidCommandBlock(pRI);
   1049     return;
   1050 }
   1051 
   1052 
   1053 /**
   1054  * Callee expects const RIL_CallForwardInfo *
   1055  * Payload is:
   1056  *  int32_t status/action
   1057  *  int32_t reason
   1058  *  int32_t serviceCode
   1059  *  int32_t toa
   1060  *  String number  (0 length -> null)
   1061  *  int32_t timeSeconds
   1062  */
   1063 static void
   1064 dispatchCallForward(Parcel &p, RequestInfo *pRI) {
   1065     RIL_CallForwardInfo cff;
   1066     int32_t t;
   1067     status_t status;
   1068 
   1069     RLOGD("dispatchCallForward");
   1070     memset (&cff, 0, sizeof(cff));
   1071 
   1072     // note we only check status at the end
   1073 
   1074     status = p.readInt32(&t);
   1075     cff.status = (int)t;
   1076 
   1077     status = p.readInt32(&t);
   1078     cff.reason = (int)t;
   1079 
   1080     status = p.readInt32(&t);
   1081     cff.serviceClass = (int)t;
   1082 
   1083     status = p.readInt32(&t);
   1084     cff.toa = (int)t;
   1085 
   1086     cff.number = strdupReadString(p);
   1087 
   1088     status = p.readInt32(&t);
   1089     cff.timeSeconds = (int)t;
   1090 
   1091     if (status != NO_ERROR) {
   1092         goto invalid;
   1093     }
   1094 
   1095     // special case: number 0-length fields is null
   1096 
   1097     if (cff.number != NULL && strlen (cff.number) == 0) {
   1098         cff.number = NULL;
   1099     }
   1100 
   1101     startRequest;
   1102     appendPrintBuf("%sstat=%d,reason=%d,serv=%d,toa=%d,%s,tout=%d", printBuf,
   1103         cff.status, cff.reason, cff.serviceClass, cff.toa,
   1104         (char*)cff.number, cff.timeSeconds);
   1105     closeRequest;
   1106     printRequest(pRI->token, pRI->pCI->requestNumber);
   1107 
   1108     CALL_ONREQUEST(pRI->pCI->requestNumber, &cff, sizeof(cff), pRI, pRI->socket_id);
   1109 
   1110 #ifdef MEMSET_FREED
   1111     memsetString(cff.number);
   1112 #endif
   1113 
   1114     free (cff.number);
   1115 
   1116 #ifdef MEMSET_FREED
   1117     memset(&cff, 0, sizeof(cff));
   1118 #endif
   1119 
   1120     return;
   1121 invalid:
   1122     invalidCommandBlock(pRI);
   1123     return;
   1124 }
   1125 
   1126 
   1127 static void
   1128 dispatchRaw(Parcel &p, RequestInfo *pRI) {
   1129     int32_t len;
   1130     status_t status;
   1131     const void *data;
   1132 
   1133     status = p.readInt32(&len);
   1134 
   1135     if (status != NO_ERROR) {
   1136         goto invalid;
   1137     }
   1138 
   1139     // The java code writes -1 for null arrays
   1140     if (((int)len) == -1) {
   1141         data = NULL;
   1142         len = 0;
   1143     }
   1144 
   1145     data = p.readInplace(len);
   1146 
   1147     startRequest;
   1148     appendPrintBuf("%sraw_size=%d", printBuf, len);
   1149     closeRequest;
   1150     printRequest(pRI->token, pRI->pCI->requestNumber);
   1151 
   1152     CALL_ONREQUEST(pRI->pCI->requestNumber, const_cast<void *>(data), len, pRI, pRI->socket_id);
   1153 
   1154     return;
   1155 invalid:
   1156     invalidCommandBlock(pRI);
   1157     return;
   1158 }
   1159 
   1160 static status_t
   1161 constructCdmaSms(Parcel &p, RequestInfo *pRI, RIL_CDMA_SMS_Message& rcsm) {
   1162     int32_t  t;
   1163     uint8_t ut;
   1164     status_t status;
   1165     int32_t digitCount;
   1166     int digitLimit;
   1167 
   1168     memset(&rcsm, 0, sizeof(rcsm));
   1169 
   1170     status = p.readInt32(&t);
   1171     rcsm.uTeleserviceID = (int) t;
   1172 
   1173     status = p.read(&ut,sizeof(ut));
   1174     rcsm.bIsServicePresent = (uint8_t) ut;
   1175 
   1176     status = p.readInt32(&t);
   1177     rcsm.uServicecategory = (int) t;
   1178 
   1179     status = p.readInt32(&t);
   1180     rcsm.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
   1181 
   1182     status = p.readInt32(&t);
   1183     rcsm.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
   1184 
   1185     status = p.readInt32(&t);
   1186     rcsm.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
   1187 
   1188     status = p.readInt32(&t);
   1189     rcsm.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
   1190 
   1191     status = p.read(&ut,sizeof(ut));
   1192     rcsm.sAddress.number_of_digits= (uint8_t) ut;
   1193 
   1194     digitLimit= MIN((rcsm.sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
   1195     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
   1196         status = p.read(&ut,sizeof(ut));
   1197         rcsm.sAddress.digits[digitCount] = (uint8_t) ut;
   1198     }
   1199 
   1200     status = p.readInt32(&t);
   1201     rcsm.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
   1202 
   1203     status = p.read(&ut,sizeof(ut));
   1204     rcsm.sSubAddress.odd = (uint8_t) ut;
   1205 
   1206     status = p.read(&ut,sizeof(ut));
   1207     rcsm.sSubAddress.number_of_digits = (uint8_t) ut;
   1208 
   1209     digitLimit= MIN((rcsm.sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
   1210     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
   1211         status = p.read(&ut,sizeof(ut));
   1212         rcsm.sSubAddress.digits[digitCount] = (uint8_t) ut;
   1213     }
   1214 
   1215     status = p.readInt32(&t);
   1216     rcsm.uBearerDataLen = (int) t;
   1217 
   1218     digitLimit= MIN((rcsm.uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
   1219     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
   1220         status = p.read(&ut, sizeof(ut));
   1221         rcsm.aBearerData[digitCount] = (uint8_t) ut;
   1222     }
   1223 
   1224     if (status != NO_ERROR) {
   1225         return status;
   1226     }
   1227 
   1228     startRequest;
   1229     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
   1230             sAddress.digit_mode=%d, sAddress.Number_mode=%d, sAddress.number_type=%d, ",
   1231             printBuf, rcsm.uTeleserviceID,rcsm.bIsServicePresent,rcsm.uServicecategory,
   1232             rcsm.sAddress.digit_mode, rcsm.sAddress.number_mode,rcsm.sAddress.number_type);
   1233     closeRequest;
   1234 
   1235     printRequest(pRI->token, pRI->pCI->requestNumber);
   1236 
   1237     return status;
   1238 }
   1239 
   1240 static void
   1241 dispatchCdmaSms(Parcel &p, RequestInfo *pRI) {
   1242     RIL_CDMA_SMS_Message rcsm;
   1243 
   1244     RLOGD("dispatchCdmaSms");
   1245     if (NO_ERROR != constructCdmaSms(p, pRI, rcsm)) {
   1246         goto invalid;
   1247     }
   1248 
   1249     CALL_ONREQUEST(pRI->pCI->requestNumber, &rcsm, sizeof(rcsm),pRI, pRI->socket_id);
   1250 
   1251 #ifdef MEMSET_FREED
   1252     memset(&rcsm, 0, sizeof(rcsm));
   1253 #endif
   1254 
   1255     return;
   1256 
   1257 invalid:
   1258     invalidCommandBlock(pRI);
   1259     return;
   1260 }
   1261 
   1262 static void
   1263 dispatchImsCdmaSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef) {
   1264     RIL_IMS_SMS_Message rism;
   1265     RIL_CDMA_SMS_Message rcsm;
   1266 
   1267     RLOGD("dispatchImsCdmaSms: retry=%d, messageRef=%d", retry, messageRef);
   1268 
   1269     if (NO_ERROR != constructCdmaSms(p, pRI, rcsm)) {
   1270         goto invalid;
   1271     }
   1272     memset(&rism, 0, sizeof(rism));
   1273     rism.tech = RADIO_TECH_3GPP2;
   1274     rism.retry = retry;
   1275     rism.messageRef = messageRef;
   1276     rism.message.cdmaMessage = &rcsm;
   1277 
   1278     CALL_ONREQUEST(pRI->pCI->requestNumber, &rism,
   1279             sizeof(RIL_RadioTechnologyFamily)+sizeof(uint8_t)+sizeof(int32_t)
   1280             +sizeof(rcsm),pRI, pRI->socket_id);
   1281 
   1282 #ifdef MEMSET_FREED
   1283     memset(&rcsm, 0, sizeof(rcsm));
   1284     memset(&rism, 0, sizeof(rism));
   1285 #endif
   1286 
   1287     return;
   1288 
   1289 invalid:
   1290     invalidCommandBlock(pRI);
   1291     return;
   1292 }
   1293 
   1294 static void
   1295 dispatchImsGsmSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef) {
   1296     RIL_IMS_SMS_Message rism;
   1297     int32_t countStrings;
   1298     status_t status;
   1299     size_t datalen;
   1300     char **pStrings;
   1301     RLOGD("dispatchImsGsmSms: retry=%d, messageRef=%d", retry, messageRef);
   1302 
   1303     status = p.readInt32 (&countStrings);
   1304 
   1305     if (status != NO_ERROR) {
   1306         goto invalid;
   1307     }
   1308 
   1309     memset(&rism, 0, sizeof(rism));
   1310     rism.tech = RADIO_TECH_3GPP;
   1311     rism.retry = retry;
   1312     rism.messageRef = messageRef;
   1313 
   1314     startRequest;
   1315     appendPrintBuf("%stech=%d, retry=%d, messageRef=%d, ", printBuf,
   1316                     (int)rism.tech, (int)rism.retry, rism.messageRef);
   1317     if (countStrings == 0) {
   1318         // just some non-null pointer
   1319         pStrings = (char **)calloc(1, sizeof(char *));
   1320         if (pStrings == NULL) {
   1321             RLOGE("Memory allocation failed for request %s",
   1322                     requestToString(pRI->pCI->requestNumber));
   1323             closeRequest;
   1324             return;
   1325         }
   1326 
   1327         datalen = 0;
   1328     } else if (countStrings < 0) {
   1329         pStrings = NULL;
   1330         datalen = 0;
   1331     } else {
   1332         if (countStrings > (INT_MAX/sizeof(char *))) {
   1333             RLOGE("Invalid value of countStrings: \n");
   1334             closeRequest;
   1335             return;
   1336         }
   1337         datalen = sizeof(char *) * countStrings;
   1338 
   1339         pStrings = (char **)calloc(countStrings, sizeof(char *));
   1340         if (pStrings == NULL) {
   1341             RLOGE("Memory allocation failed for request %s",
   1342                     requestToString(pRI->pCI->requestNumber));
   1343             closeRequest;
   1344             return;
   1345         }
   1346 
   1347         for (int i = 0 ; i < countStrings ; i++) {
   1348             pStrings[i] = strdupReadString(p);
   1349             appendPrintBuf("%s%s,", printBuf, pStrings[i]);
   1350         }
   1351     }
   1352     removeLastChar;
   1353     closeRequest;
   1354     printRequest(pRI->token, pRI->pCI->requestNumber);
   1355 
   1356     rism.message.gsmMessage = pStrings;
   1357     CALL_ONREQUEST(pRI->pCI->requestNumber, &rism,
   1358             sizeof(RIL_RadioTechnologyFamily)+sizeof(uint8_t)+sizeof(int32_t)
   1359             +datalen, pRI, pRI->socket_id);
   1360 
   1361     if (pStrings != NULL) {
   1362         for (int i = 0 ; i < countStrings ; i++) {
   1363 #ifdef MEMSET_FREED
   1364             memsetString (pStrings[i]);
   1365 #endif
   1366             free(pStrings[i]);
   1367         }
   1368 
   1369 #ifdef MEMSET_FREED
   1370         memset(pStrings, 0, datalen);
   1371 #endif
   1372         free(pStrings);
   1373     }
   1374 
   1375 #ifdef MEMSET_FREED
   1376     memset(&rism, 0, sizeof(rism));
   1377 #endif
   1378     return;
   1379 invalid:
   1380     ALOGE("dispatchImsGsmSms invalid block");
   1381     invalidCommandBlock(pRI);
   1382     return;
   1383 }
   1384 
   1385 static void
   1386 dispatchImsSms(Parcel &p, RequestInfo *pRI) {
   1387     int32_t  t;
   1388     status_t status = p.readInt32(&t);
   1389     RIL_RadioTechnologyFamily format;
   1390     uint8_t retry;
   1391     int32_t messageRef;
   1392 
   1393     RLOGD("dispatchImsSms");
   1394     if (status != NO_ERROR) {
   1395         goto invalid;
   1396     }
   1397     format = (RIL_RadioTechnologyFamily) t;
   1398 
   1399     // read retry field
   1400     status = p.read(&retry,sizeof(retry));
   1401     if (status != NO_ERROR) {
   1402         goto invalid;
   1403     }
   1404     // read messageRef field
   1405     status = p.read(&messageRef,sizeof(messageRef));
   1406     if (status != NO_ERROR) {
   1407         goto invalid;
   1408     }
   1409 
   1410     if (RADIO_TECH_3GPP == format) {
   1411         dispatchImsGsmSms(p, pRI, retry, messageRef);
   1412     } else if (RADIO_TECH_3GPP2 == format) {
   1413         dispatchImsCdmaSms(p, pRI, retry, messageRef);
   1414     } else {
   1415         ALOGE("requestImsSendSMS invalid format value =%d", format);
   1416     }
   1417 
   1418     return;
   1419 
   1420 invalid:
   1421     invalidCommandBlock(pRI);
   1422     return;
   1423 }
   1424 
   1425 static void
   1426 dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI) {
   1427     RIL_CDMA_SMS_Ack rcsa;
   1428     int32_t  t;
   1429     status_t status;
   1430     int32_t digitCount;
   1431 
   1432     RLOGD("dispatchCdmaSmsAck");
   1433     memset(&rcsa, 0, sizeof(rcsa));
   1434 
   1435     status = p.readInt32(&t);
   1436     rcsa.uErrorClass = (RIL_CDMA_SMS_ErrorClass) t;
   1437 
   1438     status = p.readInt32(&t);
   1439     rcsa.uSMSCauseCode = (int) t;
   1440 
   1441     if (status != NO_ERROR) {
   1442         goto invalid;
   1443     }
   1444 
   1445     startRequest;
   1446     appendPrintBuf("%suErrorClass=%d, uTLStatus=%d, ",
   1447             printBuf, rcsa.uErrorClass, rcsa.uSMSCauseCode);
   1448     closeRequest;
   1449 
   1450     printRequest(pRI->token, pRI->pCI->requestNumber);
   1451 
   1452     CALL_ONREQUEST(pRI->pCI->requestNumber, &rcsa, sizeof(rcsa),pRI, pRI->socket_id);
   1453 
   1454 #ifdef MEMSET_FREED
   1455     memset(&rcsa, 0, sizeof(rcsa));
   1456 #endif
   1457 
   1458     return;
   1459 
   1460 invalid:
   1461     invalidCommandBlock(pRI);
   1462     return;
   1463 }
   1464 
   1465 static void
   1466 dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI) {
   1467     int32_t t;
   1468     status_t status;
   1469     int32_t num;
   1470 
   1471     status = p.readInt32(&num);
   1472     if (status != NO_ERROR) {
   1473         goto invalid;
   1474     }
   1475 
   1476     {
   1477         RIL_GSM_BroadcastSmsConfigInfo gsmBci[num];
   1478         RIL_GSM_BroadcastSmsConfigInfo *gsmBciPtrs[num];
   1479 
   1480         startRequest;
   1481         for (int i = 0 ; i < num ; i++ ) {
   1482             gsmBciPtrs[i] = &gsmBci[i];
   1483 
   1484             status = p.readInt32(&t);
   1485             gsmBci[i].fromServiceId = (int) t;
   1486 
   1487             status = p.readInt32(&t);
   1488             gsmBci[i].toServiceId = (int) t;
   1489 
   1490             status = p.readInt32(&t);
   1491             gsmBci[i].fromCodeScheme = (int) t;
   1492 
   1493             status = p.readInt32(&t);
   1494             gsmBci[i].toCodeScheme = (int) t;
   1495 
   1496             status = p.readInt32(&t);
   1497             gsmBci[i].selected = (uint8_t) t;
   1498 
   1499             appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId =%d, \
   1500                   fromCodeScheme=%d, toCodeScheme=%d, selected =%d]", printBuf, i,
   1501                   gsmBci[i].fromServiceId, gsmBci[i].toServiceId,
   1502                   gsmBci[i].fromCodeScheme, gsmBci[i].toCodeScheme,
   1503                   gsmBci[i].selected);
   1504         }
   1505         closeRequest;
   1506 
   1507         if (status != NO_ERROR) {
   1508             goto invalid;
   1509         }
   1510 
   1511         CALL_ONREQUEST(pRI->pCI->requestNumber,
   1512                               gsmBciPtrs,
   1513                               num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *),
   1514                               pRI, pRI->socket_id);
   1515 
   1516 #ifdef MEMSET_FREED
   1517         memset(gsmBci, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo));
   1518         memset(gsmBciPtrs, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *));
   1519 #endif
   1520     }
   1521 
   1522     return;
   1523 
   1524 invalid:
   1525     invalidCommandBlock(pRI);
   1526     return;
   1527 }
   1528 
   1529 static void
   1530 dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI) {
   1531     int32_t t;
   1532     status_t status;
   1533     int32_t num;
   1534 
   1535     status = p.readInt32(&num);
   1536     if (status != NO_ERROR) {
   1537         goto invalid;
   1538     }
   1539 
   1540     {
   1541         RIL_CDMA_BroadcastSmsConfigInfo cdmaBci[num];
   1542         RIL_CDMA_BroadcastSmsConfigInfo *cdmaBciPtrs[num];
   1543 
   1544         startRequest;
   1545         for (int i = 0 ; i < num ; i++ ) {
   1546             cdmaBciPtrs[i] = &cdmaBci[i];
   1547 
   1548             status = p.readInt32(&t);
   1549             cdmaBci[i].service_category = (int) t;
   1550 
   1551             status = p.readInt32(&t);
   1552             cdmaBci[i].language = (int) t;
   1553 
   1554             status = p.readInt32(&t);
   1555             cdmaBci[i].selected = (uint8_t) t;
   1556 
   1557             appendPrintBuf("%s [%d: service_category=%d, language =%d, \
   1558                   entries.bSelected =%d]", printBuf, i, cdmaBci[i].service_category,
   1559                   cdmaBci[i].language, cdmaBci[i].selected);
   1560         }
   1561         closeRequest;
   1562 
   1563         if (status != NO_ERROR) {
   1564             goto invalid;
   1565         }
   1566 
   1567         CALL_ONREQUEST(pRI->pCI->requestNumber,
   1568                               cdmaBciPtrs,
   1569                               num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *),
   1570                               pRI, pRI->socket_id);
   1571 
   1572 #ifdef MEMSET_FREED
   1573         memset(cdmaBci, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo));
   1574         memset(cdmaBciPtrs, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *));
   1575 #endif
   1576     }
   1577 
   1578     return;
   1579 
   1580 invalid:
   1581     invalidCommandBlock(pRI);
   1582     return;
   1583 }
   1584 
   1585 static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI) {
   1586     RIL_CDMA_SMS_WriteArgs rcsw;
   1587     int32_t  t;
   1588     uint32_t ut;
   1589     uint8_t  uct;
   1590     status_t status;
   1591     int32_t  digitCount;
   1592     int32_t  digitLimit;
   1593 
   1594     memset(&rcsw, 0, sizeof(rcsw));
   1595 
   1596     status = p.readInt32(&t);
   1597     rcsw.status = t;
   1598 
   1599     status = p.readInt32(&t);
   1600     rcsw.message.uTeleserviceID = (int) t;
   1601 
   1602     status = p.read(&uct,sizeof(uct));
   1603     rcsw.message.bIsServicePresent = (uint8_t) uct;
   1604 
   1605     status = p.readInt32(&t);
   1606     rcsw.message.uServicecategory = (int) t;
   1607 
   1608     status = p.readInt32(&t);
   1609     rcsw.message.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
   1610 
   1611     status = p.readInt32(&t);
   1612     rcsw.message.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
   1613 
   1614     status = p.readInt32(&t);
   1615     rcsw.message.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
   1616 
   1617     status = p.readInt32(&t);
   1618     rcsw.message.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
   1619 
   1620     status = p.read(&uct,sizeof(uct));
   1621     rcsw.message.sAddress.number_of_digits = (uint8_t) uct;
   1622 
   1623     digitLimit = MIN((rcsw.message.sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
   1624 
   1625     for(digitCount = 0 ; digitCount < digitLimit; digitCount ++) {
   1626         status = p.read(&uct,sizeof(uct));
   1627         rcsw.message.sAddress.digits[digitCount] = (uint8_t) uct;
   1628     }
   1629 
   1630     status = p.readInt32(&t);
   1631     rcsw.message.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
   1632 
   1633     status = p.read(&uct,sizeof(uct));
   1634     rcsw.message.sSubAddress.odd = (uint8_t) uct;
   1635 
   1636     status = p.read(&uct,sizeof(uct));
   1637     rcsw.message.sSubAddress.number_of_digits = (uint8_t) uct;
   1638 
   1639     digitLimit = MIN((rcsw.message.sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
   1640 
   1641     for(digitCount = 0 ; digitCount < digitLimit; digitCount ++) {
   1642         status = p.read(&uct,sizeof(uct));
   1643         rcsw.message.sSubAddress.digits[digitCount] = (uint8_t) uct;
   1644     }
   1645 
   1646     status = p.readInt32(&t);
   1647     rcsw.message.uBearerDataLen = (int) t;
   1648 
   1649     digitLimit = MIN((rcsw.message.uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
   1650 
   1651     for(digitCount = 0 ; digitCount < digitLimit; digitCount ++) {
   1652         status = p.read(&uct, sizeof(uct));
   1653         rcsw.message.aBearerData[digitCount] = (uint8_t) uct;
   1654     }
   1655 
   1656     if (status != NO_ERROR) {
   1657         goto invalid;
   1658     }
   1659 
   1660     startRequest;
   1661     appendPrintBuf("%sstatus=%d, message.uTeleserviceID=%d, message.bIsServicePresent=%d, \
   1662             message.uServicecategory=%d, message.sAddress.digit_mode=%d, \
   1663             message.sAddress.number_mode=%d, \
   1664             message.sAddress.number_type=%d, ",
   1665             printBuf, rcsw.status, rcsw.message.uTeleserviceID, rcsw.message.bIsServicePresent,
   1666             rcsw.message.uServicecategory, rcsw.message.sAddress.digit_mode,
   1667             rcsw.message.sAddress.number_mode,
   1668             rcsw.message.sAddress.number_type);
   1669     closeRequest;
   1670 
   1671     printRequest(pRI->token, pRI->pCI->requestNumber);
   1672 
   1673     CALL_ONREQUEST(pRI->pCI->requestNumber, &rcsw, sizeof(rcsw),pRI, pRI->socket_id);
   1674 
   1675 #ifdef MEMSET_FREED
   1676     memset(&rcsw, 0, sizeof(rcsw));
   1677 #endif
   1678 
   1679     return;
   1680 
   1681 invalid:
   1682     invalidCommandBlock(pRI);
   1683     return;
   1684 
   1685 }
   1686 
   1687 // For backwards compatibility in RIL_REQUEST_SETUP_DATA_CALL.
   1688 // Version 4 of the RIL interface adds a new PDP type parameter to support
   1689 // IPv6 and dual-stack PDP contexts. When dealing with a previous version of
   1690 // RIL, remove the parameter from the request.
   1691 static void dispatchDataCall(Parcel& p, RequestInfo *pRI) {
   1692     // In RIL v3, REQUEST_SETUP_DATA_CALL takes 6 parameters.
   1693     const int numParamsRilV3 = 6;
   1694 
   1695     // The first bytes of the RIL parcel contain the request number and the
   1696     // serial number - see processCommandBuffer(). Copy them over too.
   1697     int pos = p.dataPosition();
   1698 
   1699     int numParams = p.readInt32();
   1700     if (s_callbacks.version < 4 && numParams > numParamsRilV3) {
   1701       Parcel p2;
   1702       p2.appendFrom(&p, 0, pos);
   1703       p2.writeInt32(numParamsRilV3);
   1704       for(int i = 0; i < numParamsRilV3; i++) {
   1705         p2.writeString16(p.readString16());
   1706       }
   1707       p2.setDataPosition(pos);
   1708       dispatchStrings(p2, pRI);
   1709     } else {
   1710       p.setDataPosition(pos);
   1711       dispatchStrings(p, pRI);
   1712     }
   1713 }
   1714 
   1715 // For backwards compatibility with RILs that dont support RIL_REQUEST_VOICE_RADIO_TECH.
   1716 // When all RILs handle this request, this function can be removed and
   1717 // the request can be sent directly to the RIL using dispatchVoid.
   1718 static void dispatchVoiceRadioTech(Parcel& p, RequestInfo *pRI) {
   1719     RIL_RadioState state = CALL_ONSTATEREQUEST((RIL_SOCKET_ID)pRI->socket_id);
   1720 
   1721     if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
   1722         RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1723     }
   1724 
   1725     // RILs that support RADIO_STATE_ON should support this request.
   1726     if (RADIO_STATE_ON == state) {
   1727         dispatchVoid(p, pRI);
   1728         return;
   1729     }
   1730 
   1731     // For Older RILs, that do not support RADIO_STATE_ON, assume that they
   1732     // will not support this new request either and decode Voice Radio Technology
   1733     // from Radio State
   1734     voiceRadioTech = decodeVoiceRadioTechnology(state);
   1735 
   1736     if (voiceRadioTech < 0)
   1737         RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
   1738     else
   1739         RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &voiceRadioTech, sizeof(int));
   1740 }
   1741 
   1742 // For backwards compatibility in RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:.
   1743 // When all RILs handle this request, this function can be removed and
   1744 // the request can be sent directly to the RIL using dispatchVoid.
   1745 static void dispatchCdmaSubscriptionSource(Parcel& p, RequestInfo *pRI) {
   1746     RIL_RadioState state = CALL_ONSTATEREQUEST((RIL_SOCKET_ID)pRI->socket_id);
   1747 
   1748     if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
   1749         RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1750     }
   1751 
   1752     // RILs that support RADIO_STATE_ON should support this request.
   1753     if (RADIO_STATE_ON == state) {
   1754         dispatchVoid(p, pRI);
   1755         return;
   1756     }
   1757 
   1758     // For Older RILs, that do not support RADIO_STATE_ON, assume that they
   1759     // will not support this new request either and decode CDMA Subscription Source
   1760     // from Radio State
   1761     cdmaSubscriptionSource = decodeCdmaSubscriptionSource(state);
   1762 
   1763     if (cdmaSubscriptionSource < 0)
   1764         RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
   1765     else
   1766         RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &cdmaSubscriptionSource, sizeof(int));
   1767 }
   1768 
   1769 static void dispatchSetInitialAttachApn(Parcel &p, RequestInfo *pRI)
   1770 {
   1771     RIL_InitialAttachApn pf;
   1772     int32_t  t;
   1773     status_t status;
   1774 
   1775     memset(&pf, 0, sizeof(pf));
   1776 
   1777     pf.apn = strdupReadString(p);
   1778     pf.protocol = strdupReadString(p);
   1779 
   1780     status = p.readInt32(&t);
   1781     pf.authtype = (int) t;
   1782 
   1783     pf.username = strdupReadString(p);
   1784     pf.password = strdupReadString(p);
   1785 
   1786     startRequest;
   1787     appendPrintBuf("%sapn=%s, protocol=%s, authtype=%d, username=%s, password=%s",
   1788             printBuf, pf.apn, pf.protocol, pf.authtype, pf.username, pf.password);
   1789     closeRequest;
   1790     printRequest(pRI->token, pRI->pCI->requestNumber);
   1791 
   1792     if (status != NO_ERROR) {
   1793         goto invalid;
   1794     }
   1795     CALL_ONREQUEST(pRI->pCI->requestNumber, &pf, sizeof(pf), pRI, pRI->socket_id);
   1796 
   1797 #ifdef MEMSET_FREED
   1798     memsetString(pf.apn);
   1799     memsetString(pf.protocol);
   1800     memsetString(pf.username);
   1801     memsetString(pf.password);
   1802 #endif
   1803 
   1804     free(pf.apn);
   1805     free(pf.protocol);
   1806     free(pf.username);
   1807     free(pf.password);
   1808 
   1809 #ifdef MEMSET_FREED
   1810     memset(&pf, 0, sizeof(pf));
   1811 #endif
   1812 
   1813     return;
   1814 invalid:
   1815     invalidCommandBlock(pRI);
   1816     return;
   1817 }
   1818 
   1819 static void dispatchNVReadItem(Parcel &p, RequestInfo *pRI) {
   1820     RIL_NV_ReadItem nvri;
   1821     int32_t  t;
   1822     status_t status;
   1823 
   1824     memset(&nvri, 0, sizeof(nvri));
   1825 
   1826     status = p.readInt32(&t);
   1827     nvri.itemID = (RIL_NV_Item) t;
   1828 
   1829     if (status != NO_ERROR) {
   1830         goto invalid;
   1831     }
   1832 
   1833     startRequest;
   1834     appendPrintBuf("%snvri.itemID=%d, ", printBuf, nvri.itemID);
   1835     closeRequest;
   1836 
   1837     printRequest(pRI->token, pRI->pCI->requestNumber);
   1838 
   1839     CALL_ONREQUEST(pRI->pCI->requestNumber, &nvri, sizeof(nvri), pRI, pRI->socket_id);
   1840 
   1841 #ifdef MEMSET_FREED
   1842     memset(&nvri, 0, sizeof(nvri));
   1843 #endif
   1844 
   1845     return;
   1846 
   1847 invalid:
   1848     invalidCommandBlock(pRI);
   1849     return;
   1850 }
   1851 
   1852 static void dispatchNVWriteItem(Parcel &p, RequestInfo *pRI) {
   1853     RIL_NV_WriteItem nvwi;
   1854     int32_t  t;
   1855     status_t status;
   1856 
   1857     memset(&nvwi, 0, sizeof(nvwi));
   1858 
   1859     status = p.readInt32(&t);
   1860     nvwi.itemID = (RIL_NV_Item) t;
   1861 
   1862     nvwi.value = strdupReadString(p);
   1863 
   1864     if (status != NO_ERROR || nvwi.value == NULL) {
   1865         goto invalid;
   1866     }
   1867 
   1868     startRequest;
   1869     appendPrintBuf("%snvwi.itemID=%d, value=%s, ", printBuf, nvwi.itemID,
   1870             nvwi.value);
   1871     closeRequest;
   1872 
   1873     printRequest(pRI->token, pRI->pCI->requestNumber);
   1874 
   1875     CALL_ONREQUEST(pRI->pCI->requestNumber, &nvwi, sizeof(nvwi), pRI, pRI->socket_id);
   1876 
   1877 #ifdef MEMSET_FREED
   1878     memsetString(nvwi.value);
   1879 #endif
   1880 
   1881     free(nvwi.value);
   1882 
   1883 #ifdef MEMSET_FREED
   1884     memset(&nvwi, 0, sizeof(nvwi));
   1885 #endif
   1886 
   1887     return;
   1888 
   1889 invalid:
   1890     invalidCommandBlock(pRI);
   1891     return;
   1892 }
   1893 
   1894 
   1895 static void dispatchUiccSubscripton(Parcel &p, RequestInfo *pRI) {
   1896     RIL_SelectUiccSub uicc_sub;
   1897     status_t status;
   1898     int32_t  t;
   1899     memset(&uicc_sub, 0, sizeof(uicc_sub));
   1900 
   1901     status = p.readInt32(&t);
   1902     if (status != NO_ERROR) {
   1903         goto invalid;
   1904     }
   1905     uicc_sub.slot = (int) t;
   1906 
   1907     status = p.readInt32(&t);
   1908     if (status != NO_ERROR) {
   1909         goto invalid;
   1910     }
   1911     uicc_sub.app_index = (int) t;
   1912 
   1913     status = p.readInt32(&t);
   1914     if (status != NO_ERROR) {
   1915         goto invalid;
   1916     }
   1917     uicc_sub.sub_type = (RIL_SubscriptionType) t;
   1918 
   1919     status = p.readInt32(&t);
   1920     if (status != NO_ERROR) {
   1921         goto invalid;
   1922     }
   1923     uicc_sub.act_status = (RIL_UiccSubActStatus) t;
   1924 
   1925     startRequest;
   1926     appendPrintBuf("slot=%d, app_index=%d, act_status = %d", uicc_sub.slot, uicc_sub.app_index,
   1927             uicc_sub.act_status);
   1928     RLOGD("dispatchUiccSubscription, slot=%d, app_index=%d, act_status = %d", uicc_sub.slot,
   1929             uicc_sub.app_index, uicc_sub.act_status);
   1930     closeRequest;
   1931     printRequest(pRI->token, pRI->pCI->requestNumber);
   1932 
   1933     CALL_ONREQUEST(pRI->pCI->requestNumber, &uicc_sub, sizeof(uicc_sub), pRI, pRI->socket_id);
   1934 
   1935 #ifdef MEMSET_FREED
   1936     memset(&uicc_sub, 0, sizeof(uicc_sub));
   1937 #endif
   1938     return;
   1939 
   1940 invalid:
   1941     invalidCommandBlock(pRI);
   1942     return;
   1943 }
   1944 
   1945 static void dispatchSimAuthentication(Parcel &p, RequestInfo *pRI)
   1946 {
   1947     RIL_SimAuthentication pf;
   1948     int32_t  t;
   1949     status_t status;
   1950 
   1951     memset(&pf, 0, sizeof(pf));
   1952 
   1953     status = p.readInt32(&t);
   1954     pf.authContext = (int) t;
   1955     pf.authData = strdupReadString(p);
   1956     pf.aid = strdupReadString(p);
   1957 
   1958     startRequest;
   1959     appendPrintBuf("authContext=%s, authData=%s, aid=%s", pf.authContext, pf.authData, pf.aid);
   1960     closeRequest;
   1961     printRequest(pRI->token, pRI->pCI->requestNumber);
   1962 
   1963     if (status != NO_ERROR) {
   1964         goto invalid;
   1965     }
   1966     CALL_ONREQUEST(pRI->pCI->requestNumber, &pf, sizeof(pf), pRI, pRI->socket_id);
   1967 
   1968 #ifdef MEMSET_FREED
   1969     memsetString(pf.authData);
   1970     memsetString(pf.aid);
   1971 #endif
   1972 
   1973     free(pf.authData);
   1974     free(pf.aid);
   1975 
   1976 #ifdef MEMSET_FREED
   1977     memset(&pf, 0, sizeof(pf));
   1978 #endif
   1979 
   1980     return;
   1981 invalid:
   1982     invalidCommandBlock(pRI);
   1983     return;
   1984 }
   1985 
   1986 static void dispatchDataProfile(Parcel &p, RequestInfo *pRI) {
   1987     int32_t t;
   1988     status_t status;
   1989     int32_t num;
   1990 
   1991     status = p.readInt32(&num);
   1992     if (status != NO_ERROR || num < 0) {
   1993         goto invalid;
   1994     }
   1995 
   1996     {
   1997         RIL_DataProfileInfo *dataProfiles =
   1998                 (RIL_DataProfileInfo *)calloc(num, sizeof(RIL_DataProfileInfo));
   1999         if (dataProfiles == NULL) {
   2000             RLOGE("Memory allocation failed for request %s",
   2001                     requestToString(pRI->pCI->requestNumber));
   2002             return;
   2003         }
   2004         RIL_DataProfileInfo **dataProfilePtrs =
   2005                 (RIL_DataProfileInfo **)calloc(num, sizeof(RIL_DataProfileInfo *));
   2006         if (dataProfilePtrs == NULL) {
   2007             RLOGE("Memory allocation failed for request %s",
   2008                     requestToString(pRI->pCI->requestNumber));
   2009             free(dataProfiles);
   2010             return;
   2011         }
   2012 
   2013         startRequest;
   2014         for (int i = 0 ; i < num ; i++ ) {
   2015             dataProfilePtrs[i] = &dataProfiles[i];
   2016 
   2017             status = p.readInt32(&t);
   2018             dataProfiles[i].profileId = (int) t;
   2019 
   2020             dataProfiles[i].apn = strdupReadString(p);
   2021             dataProfiles[i].protocol = strdupReadString(p);
   2022             status = p.readInt32(&t);
   2023             dataProfiles[i].authType = (int) t;
   2024 
   2025             dataProfiles[i].user = strdupReadString(p);
   2026             dataProfiles[i].password = strdupReadString(p);
   2027 
   2028             status = p.readInt32(&t);
   2029             dataProfiles[i].type = (int) t;
   2030 
   2031             status = p.readInt32(&t);
   2032             dataProfiles[i].maxConnsTime = (int) t;
   2033             status = p.readInt32(&t);
   2034             dataProfiles[i].maxConns = (int) t;
   2035             status = p.readInt32(&t);
   2036             dataProfiles[i].waitTime = (int) t;
   2037 
   2038             status = p.readInt32(&t);
   2039             dataProfiles[i].enabled = (int) t;
   2040 
   2041             appendPrintBuf("%s [%d: profileId=%d, apn =%s, protocol =%s, authType =%d, \
   2042                   user =%s, password =%s, type =%d, maxConnsTime =%d, maxConns =%d, \
   2043                   waitTime =%d, enabled =%d]", printBuf, i, dataProfiles[i].profileId,
   2044                   dataProfiles[i].apn, dataProfiles[i].protocol, dataProfiles[i].authType,
   2045                   dataProfiles[i].user, dataProfiles[i].password, dataProfiles[i].type,
   2046                   dataProfiles[i].maxConnsTime, dataProfiles[i].maxConns,
   2047                   dataProfiles[i].waitTime, dataProfiles[i].enabled);
   2048         }
   2049         closeRequest;
   2050         printRequest(pRI->token, pRI->pCI->requestNumber);
   2051 
   2052         if (status != NO_ERROR) {
   2053             free(dataProfiles);
   2054             free(dataProfilePtrs);
   2055             goto invalid;
   2056         }
   2057         CALL_ONREQUEST(pRI->pCI->requestNumber,
   2058                               dataProfilePtrs,
   2059                               num * sizeof(RIL_DataProfileInfo *),
   2060                               pRI, pRI->socket_id);
   2061 
   2062 #ifdef MEMSET_FREED
   2063         memset(dataProfiles, 0, num * sizeof(RIL_DataProfileInfo));
   2064         memset(dataProfilePtrs, 0, num * sizeof(RIL_DataProfileInfo *));
   2065 #endif
   2066         free(dataProfiles);
   2067         free(dataProfilePtrs);
   2068     }
   2069 
   2070     return;
   2071 
   2072 invalid:
   2073     invalidCommandBlock(pRI);
   2074     return;
   2075 }
   2076 
   2077 static void dispatchRadioCapability(Parcel &p, RequestInfo *pRI){
   2078     RIL_RadioCapability rc;
   2079     int32_t t;
   2080     status_t status;
   2081 
   2082     memset (&rc, 0, sizeof(RIL_RadioCapability));
   2083 
   2084     status = p.readInt32(&t);
   2085     rc.version = (int)t;
   2086     if (status != NO_ERROR) {
   2087         goto invalid;
   2088     }
   2089 
   2090     status = p.readInt32(&t);
   2091     rc.session= (int)t;
   2092     if (status != NO_ERROR) {
   2093         goto invalid;
   2094     }
   2095 
   2096     status = p.readInt32(&t);
   2097     rc.phase= (int)t;
   2098     if (status != NO_ERROR) {
   2099         goto invalid;
   2100     }
   2101 
   2102     status = p.readInt32(&t);
   2103     rc.rat = (int)t;
   2104     if (status != NO_ERROR) {
   2105         goto invalid;
   2106     }
   2107 
   2108     status = readStringFromParcelInplace(p, rc.logicalModemUuid, sizeof(rc.logicalModemUuid));
   2109     if (status != NO_ERROR) {
   2110         goto invalid;
   2111     }
   2112 
   2113     status = p.readInt32(&t);
   2114     rc.status = (int)t;
   2115 
   2116     if (status != NO_ERROR) {
   2117         goto invalid;
   2118     }
   2119 
   2120     startRequest;
   2121     appendPrintBuf("%s [version:%d, session:%d, phase:%d, rat:%d, \
   2122             logicalModemUuid:%s, status:%d", printBuf, rc.version, rc.session,
   2123             rc.phase, rc.rat, rc.logicalModemUuid, rc.session);
   2124 
   2125     closeRequest;
   2126     printRequest(pRI->token, pRI->pCI->requestNumber);
   2127 
   2128     CALL_ONREQUEST(pRI->pCI->requestNumber,
   2129                 &rc,
   2130                 sizeof(RIL_RadioCapability),
   2131                 pRI, pRI->socket_id);
   2132     return;
   2133 invalid:
   2134     invalidCommandBlock(pRI);
   2135     return;
   2136 }
   2137 
   2138 static int
   2139 blockingWrite(int fd, const void *buffer, size_t len) {
   2140     size_t writeOffset = 0;
   2141     const uint8_t *toWrite;
   2142 
   2143     toWrite = (const uint8_t *)buffer;
   2144 
   2145     while (writeOffset < len) {
   2146         ssize_t written;
   2147         do {
   2148             written = write (fd, toWrite + writeOffset,
   2149                                 len - writeOffset);
   2150         } while (written < 0 && ((errno == EINTR) || (errno == EAGAIN)));
   2151 
   2152         if (written >= 0) {
   2153             writeOffset += written;
   2154         } else {   // written < 0
   2155             RLOGE ("RIL Response: unexpected error on write errno:%d", errno);
   2156             close(fd);
   2157             return -1;
   2158         }
   2159     }
   2160 #if VDBG
   2161     RLOGE("RIL Response bytes written:%d", writeOffset);
   2162 #endif
   2163     return 0;
   2164 }
   2165 
   2166 static int
   2167 sendResponseRaw (const void *data, size_t dataSize, RIL_SOCKET_ID socket_id) {
   2168     int fd = s_ril_param_socket.fdCommand;
   2169     int ret;
   2170     uint32_t header;
   2171     pthread_mutex_t * writeMutexHook = &s_writeMutex;
   2172 
   2173 #if VDBG
   2174     RLOGE("Send Response to %s", rilSocketIdToString(socket_id));
   2175 #endif
   2176 
   2177 #if (SIM_COUNT >= 2)
   2178     if (socket_id == RIL_SOCKET_2) {
   2179         fd = s_ril_param_socket2.fdCommand;
   2180         writeMutexHook = &s_writeMutex_socket2;
   2181     }
   2182 #if (SIM_COUNT >= 3)
   2183     else if (socket_id == RIL_SOCKET_3) {
   2184         fd = s_ril_param_socket3.fdCommand;
   2185         writeMutexHook = &s_writeMutex_socket3;
   2186     }
   2187 #endif
   2188 #if (SIM_COUNT >= 4)
   2189     else if (socket_id == RIL_SOCKET_4) {
   2190         fd = s_ril_param_socket4.fdCommand;
   2191         writeMutexHook = &s_writeMutex_socket4;
   2192     }
   2193 #endif
   2194 #endif
   2195     if (fd < 0) {
   2196         return -1;
   2197     }
   2198 
   2199     if (dataSize > MAX_COMMAND_BYTES) {
   2200         RLOGE("RIL: packet larger than %u (%u)",
   2201                 MAX_COMMAND_BYTES, (unsigned int )dataSize);
   2202 
   2203         return -1;
   2204     }
   2205 
   2206     pthread_mutex_lock(writeMutexHook);
   2207 
   2208     header = htonl(dataSize);
   2209 
   2210     ret = blockingWrite(fd, (void *)&header, sizeof(header));
   2211 
   2212     if (ret < 0) {
   2213         pthread_mutex_unlock(writeMutexHook);
   2214         return ret;
   2215     }
   2216 
   2217     ret = blockingWrite(fd, data, dataSize);
   2218 
   2219     if (ret < 0) {
   2220         pthread_mutex_unlock(writeMutexHook);
   2221         return ret;
   2222     }
   2223 
   2224     pthread_mutex_unlock(writeMutexHook);
   2225 
   2226     return 0;
   2227 }
   2228 
   2229 static int
   2230 sendResponse (Parcel &p, RIL_SOCKET_ID socket_id) {
   2231     printResponse;
   2232     return sendResponseRaw(p.data(), p.dataSize(), socket_id);
   2233 }
   2234 
   2235 /** response is an int* pointing to an array of ints */
   2236 
   2237 static int
   2238 responseInts(Parcel &p, void *response, size_t responselen) {
   2239     int numInts;
   2240 
   2241     if (response == NULL && responselen != 0) {
   2242         RLOGE("invalid response: NULL");
   2243         return RIL_ERRNO_INVALID_RESPONSE;
   2244     }
   2245     if (responselen % sizeof(int) != 0) {
   2246         RLOGE("responseInts: invalid response length %d expected multiple of %d\n",
   2247             (int)responselen, (int)sizeof(int));
   2248         return RIL_ERRNO_INVALID_RESPONSE;
   2249     }
   2250 
   2251     int *p_int = (int *) response;
   2252 
   2253     numInts = responselen / sizeof(int);
   2254     p.writeInt32 (numInts);
   2255 
   2256     /* each int*/
   2257     startResponse;
   2258     for (int i = 0 ; i < numInts ; i++) {
   2259         appendPrintBuf("%s%d,", printBuf, p_int[i]);
   2260         p.writeInt32(p_int[i]);
   2261     }
   2262     removeLastChar;
   2263     closeResponse;
   2264 
   2265     return 0;
   2266 }
   2267 
   2268 // Response is an int or RIL_LastCallFailCauseInfo.
   2269 // Currently, only Shamu plans to use RIL_LastCallFailCauseInfo.
   2270 // TODO(yjl): Let all implementations use RIL_LastCallFailCauseInfo.
   2271 static int responseFailCause(Parcel &p, void *response, size_t responselen) {
   2272     if (response == NULL && responselen != 0) {
   2273         RLOGE("invalid response: NULL");
   2274         return RIL_ERRNO_INVALID_RESPONSE;
   2275     }
   2276 
   2277     if (responselen == sizeof(int)) {
   2278       startResponse;
   2279       int *p_int = (int *) response;
   2280       appendPrintBuf("%s%d,", printBuf, p_int[0]);
   2281       p.writeInt32(p_int[0]);
   2282       removeLastChar;
   2283       closeResponse;
   2284     } else if (responselen == sizeof(RIL_LastCallFailCauseInfo)) {
   2285       startResponse;
   2286       RIL_LastCallFailCauseInfo *p_fail_cause_info = (RIL_LastCallFailCauseInfo *) response;
   2287       appendPrintBuf("%s[cause_code=%d,vendor_cause=%s]", printBuf, p_fail_cause_info->cause_code,
   2288                      p_fail_cause_info->vendor_cause);
   2289       p.writeInt32(p_fail_cause_info->cause_code);
   2290       writeStringToParcel(p, p_fail_cause_info->vendor_cause);
   2291       removeLastChar;
   2292       closeResponse;
   2293     } else {
   2294       RLOGE("responseFailCause: invalid response length %d expected an int or "
   2295             "RIL_LastCallFailCauseInfo", (int)responselen);
   2296       return RIL_ERRNO_INVALID_RESPONSE;
   2297     }
   2298 
   2299     return 0;
   2300 }
   2301 
   2302 /** response is a char **, pointing to an array of char *'s
   2303     The parcel will begin with the version */
   2304 static int responseStringsWithVersion(int version, Parcel &p, void *response, size_t responselen) {
   2305     p.writeInt32(version);
   2306     return responseStrings(p, response, responselen);
   2307 }
   2308 
   2309 /** response is a char **, pointing to an array of char *'s */
   2310 static int responseStrings(Parcel &p, void *response, size_t responselen) {
   2311     int numStrings;
   2312 
   2313     if (response == NULL && responselen != 0) {
   2314         RLOGE("invalid response: NULL");
   2315         return RIL_ERRNO_INVALID_RESPONSE;
   2316     }
   2317     if (responselen % sizeof(char *) != 0) {
   2318         RLOGE("responseStrings: invalid response length %d expected multiple of %d\n",
   2319             (int)responselen, (int)sizeof(char *));
   2320         return RIL_ERRNO_INVALID_RESPONSE;
   2321     }
   2322 
   2323     if (response == NULL) {
   2324         p.writeInt32 (0);
   2325     } else {
   2326         char **p_cur = (char **) response;
   2327 
   2328         numStrings = responselen / sizeof(char *);
   2329         p.writeInt32 (numStrings);
   2330 
   2331         /* each string*/
   2332         startResponse;
   2333         for (int i = 0 ; i < numStrings ; i++) {
   2334             appendPrintBuf("%s%s,", printBuf, (char*)p_cur[i]);
   2335             writeStringToParcel (p, p_cur[i]);
   2336         }
   2337         removeLastChar;
   2338         closeResponse;
   2339     }
   2340     return 0;
   2341 }
   2342 
   2343 
   2344 /**
   2345  * NULL strings are accepted
   2346  * FIXME currently ignores responselen
   2347  */
   2348 static int responseString(Parcel &p, void *response, size_t responselen) {
   2349     /* one string only */
   2350     startResponse;
   2351     appendPrintBuf("%s%s", printBuf, (char*)response);
   2352     closeResponse;
   2353 
   2354     writeStringToParcel(p, (const char *)response);
   2355 
   2356     return 0;
   2357 }
   2358 
   2359 static int responseVoid(Parcel &p, void *response, size_t responselen) {
   2360     startResponse;
   2361     removeLastChar;
   2362     return 0;
   2363 }
   2364 
   2365 static int responseCallList(Parcel &p, void *response, size_t responselen) {
   2366     int num;
   2367 
   2368     if (response == NULL && responselen != 0) {
   2369         RLOGE("invalid response: NULL");
   2370         return RIL_ERRNO_INVALID_RESPONSE;
   2371     }
   2372 
   2373     if (responselen % sizeof (RIL_Call *) != 0) {
   2374         RLOGE("responseCallList: invalid response length %d expected multiple of %d\n",
   2375             (int)responselen, (int)sizeof (RIL_Call *));
   2376         return RIL_ERRNO_INVALID_RESPONSE;
   2377     }
   2378 
   2379     startResponse;
   2380     /* number of call info's */
   2381     num = responselen / sizeof(RIL_Call *);
   2382     p.writeInt32(num);
   2383 
   2384     for (int i = 0 ; i < num ; i++) {
   2385         RIL_Call *p_cur = ((RIL_Call **) response)[i];
   2386         /* each call info */
   2387         p.writeInt32(p_cur->state);
   2388         p.writeInt32(p_cur->index);
   2389         p.writeInt32(p_cur->toa);
   2390         p.writeInt32(p_cur->isMpty);
   2391         p.writeInt32(p_cur->isMT);
   2392         p.writeInt32(p_cur->als);
   2393         p.writeInt32(p_cur->isVoice);
   2394         p.writeInt32(p_cur->isVoicePrivacy);
   2395         writeStringToParcel(p, p_cur->number);
   2396         p.writeInt32(p_cur->numberPresentation);
   2397         writeStringToParcel(p, p_cur->name);
   2398         p.writeInt32(p_cur->namePresentation);
   2399         // Remove when partners upgrade to version 3
   2400         if ((s_callbacks.version < 3) || (p_cur->uusInfo == NULL || p_cur->uusInfo->uusData == NULL)) {
   2401             p.writeInt32(0); /* UUS Information is absent */
   2402         } else {
   2403             RIL_UUS_Info *uusInfo = p_cur->uusInfo;
   2404             p.writeInt32(1); /* UUS Information is present */
   2405             p.writeInt32(uusInfo->uusType);
   2406             p.writeInt32(uusInfo->uusDcs);
   2407             p.writeInt32(uusInfo->uusLength);
   2408             p.write(uusInfo->uusData, uusInfo->uusLength);
   2409         }
   2410         appendPrintBuf("%s[id=%d,%s,toa=%d,",
   2411             printBuf,
   2412             p_cur->index,
   2413             callStateToString(p_cur->state),
   2414             p_cur->toa);
   2415         appendPrintBuf("%s%s,%s,als=%d,%s,%s,",
   2416             printBuf,
   2417             (p_cur->isMpty)?"conf":"norm",
   2418             (p_cur->isMT)?"mt":"mo",
   2419             p_cur->als,
   2420             (p_cur->isVoice)?"voc":"nonvoc",
   2421             (p_cur->isVoicePrivacy)?"evp":"noevp");
   2422         appendPrintBuf("%s%s,cli=%d,name='%s',%d]",
   2423             printBuf,
   2424             p_cur->number,
   2425             p_cur->numberPresentation,
   2426             p_cur->name,
   2427             p_cur->namePresentation);
   2428     }
   2429     removeLastChar;
   2430     closeResponse;
   2431 
   2432     return 0;
   2433 }
   2434 
   2435 static int responseSMS(Parcel &p, void *response, size_t responselen) {
   2436     if (response == NULL) {
   2437         RLOGE("invalid response: NULL");
   2438         return RIL_ERRNO_INVALID_RESPONSE;
   2439     }
   2440 
   2441     if (responselen != sizeof (RIL_SMS_Response) ) {
   2442         RLOGE("invalid response length %d expected %d",
   2443                 (int)responselen, (int)sizeof (RIL_SMS_Response));
   2444         return RIL_ERRNO_INVALID_RESPONSE;
   2445     }
   2446 
   2447     RIL_SMS_Response *p_cur = (RIL_SMS_Response *) response;
   2448 
   2449     p.writeInt32(p_cur->messageRef);
   2450     writeStringToParcel(p, p_cur->ackPDU);
   2451     p.writeInt32(p_cur->errorCode);
   2452 
   2453     startResponse;
   2454     appendPrintBuf("%s%d,%s,%d", printBuf, p_cur->messageRef,
   2455         (char*)p_cur->ackPDU, p_cur->errorCode);
   2456     closeResponse;
   2457 
   2458     return 0;
   2459 }
   2460 
   2461 static int responseDataCallListV4(Parcel &p, void *response, size_t responselen)
   2462 {
   2463     if (response == NULL && responselen != 0) {
   2464         RLOGE("invalid response: NULL");
   2465         return RIL_ERRNO_INVALID_RESPONSE;
   2466     }
   2467 
   2468     if (responselen % sizeof(RIL_Data_Call_Response_v4) != 0) {
   2469         RLOGE("responseDataCallListV4: invalid response length %d expected multiple of %d",
   2470                 (int)responselen, (int)sizeof(RIL_Data_Call_Response_v4));
   2471         return RIL_ERRNO_INVALID_RESPONSE;
   2472     }
   2473 
   2474     // Write version
   2475     p.writeInt32(4);
   2476 
   2477     int num = responselen / sizeof(RIL_Data_Call_Response_v4);
   2478     p.writeInt32(num);
   2479 
   2480     RIL_Data_Call_Response_v4 *p_cur = (RIL_Data_Call_Response_v4 *) response;
   2481     startResponse;
   2482     int i;
   2483     for (i = 0; i < num; i++) {
   2484         p.writeInt32(p_cur[i].cid);
   2485         p.writeInt32(p_cur[i].active);
   2486         writeStringToParcel(p, p_cur[i].type);
   2487         // apn is not used, so don't send.
   2488         writeStringToParcel(p, p_cur[i].address);
   2489         appendPrintBuf("%s[cid=%d,%s,%s,%s],", printBuf,
   2490             p_cur[i].cid,
   2491             (p_cur[i].active==0)?"down":"up",
   2492             (char*)p_cur[i].type,
   2493             (char*)p_cur[i].address);
   2494     }
   2495     removeLastChar;
   2496     closeResponse;
   2497 
   2498     return 0;
   2499 }
   2500 
   2501 static int responseDataCallListV6(Parcel &p, void *response, size_t responselen)
   2502 {
   2503     if (response == NULL && responselen != 0) {
   2504         RLOGE("invalid response: NULL");
   2505         return RIL_ERRNO_INVALID_RESPONSE;
   2506     }
   2507 
   2508     if (responselen % sizeof(RIL_Data_Call_Response_v6) != 0) {
   2509         RLOGE("responseDataCallListV6: invalid response length %d expected multiple of %d",
   2510                 (int)responselen, (int)sizeof(RIL_Data_Call_Response_v6));
   2511         return RIL_ERRNO_INVALID_RESPONSE;
   2512     }
   2513 
   2514     // Write version
   2515     p.writeInt32(6);
   2516 
   2517     int num = responselen / sizeof(RIL_Data_Call_Response_v6);
   2518     p.writeInt32(num);
   2519 
   2520     RIL_Data_Call_Response_v6 *p_cur = (RIL_Data_Call_Response_v6 *) response;
   2521     startResponse;
   2522     int i;
   2523     for (i = 0; i < num; i++) {
   2524         p.writeInt32((int)p_cur[i].status);
   2525         p.writeInt32(p_cur[i].suggestedRetryTime);
   2526         p.writeInt32(p_cur[i].cid);
   2527         p.writeInt32(p_cur[i].active);
   2528         writeStringToParcel(p, p_cur[i].type);
   2529         writeStringToParcel(p, p_cur[i].ifname);
   2530         writeStringToParcel(p, p_cur[i].addresses);
   2531         writeStringToParcel(p, p_cur[i].dnses);
   2532         writeStringToParcel(p, p_cur[i].gateways);
   2533         appendPrintBuf("%s[status=%d,retry=%d,cid=%d,%s,%s,%s,%s,%s,%s],", printBuf,
   2534             p_cur[i].status,
   2535             p_cur[i].suggestedRetryTime,
   2536             p_cur[i].cid,
   2537             (p_cur[i].active==0)?"down":"up",
   2538             (char*)p_cur[i].type,
   2539             (char*)p_cur[i].ifname,
   2540             (char*)p_cur[i].addresses,
   2541             (char*)p_cur[i].dnses,
   2542             (char*)p_cur[i].gateways);
   2543     }
   2544     removeLastChar;
   2545     closeResponse;
   2546 
   2547     return 0;
   2548 }
   2549 
   2550 static int responseDataCallListV9(Parcel &p, void *response, size_t responselen)
   2551 {
   2552     if (response == NULL && responselen != 0) {
   2553         RLOGE("invalid response: NULL");
   2554         return RIL_ERRNO_INVALID_RESPONSE;
   2555     }
   2556 
   2557     if (responselen % sizeof(RIL_Data_Call_Response_v9) != 0) {
   2558         RLOGE("responseDataCallListV9: invalid response length %d expected multiple of %d",
   2559                 (int)responselen, (int)sizeof(RIL_Data_Call_Response_v9));
   2560         return RIL_ERRNO_INVALID_RESPONSE;
   2561     }
   2562 
   2563     // Write version
   2564     p.writeInt32(10);
   2565 
   2566     int num = responselen / sizeof(RIL_Data_Call_Response_v9);
   2567     p.writeInt32(num);
   2568 
   2569     RIL_Data_Call_Response_v9 *p_cur = (RIL_Data_Call_Response_v9 *) response;
   2570     startResponse;
   2571     int i;
   2572     for (i = 0; i < num; i++) {
   2573         p.writeInt32((int)p_cur[i].status);
   2574         p.writeInt32(p_cur[i].suggestedRetryTime);
   2575         p.writeInt32(p_cur[i].cid);
   2576         p.writeInt32(p_cur[i].active);
   2577         writeStringToParcel(p, p_cur[i].type);
   2578         writeStringToParcel(p, p_cur[i].ifname);
   2579         writeStringToParcel(p, p_cur[i].addresses);
   2580         writeStringToParcel(p, p_cur[i].dnses);
   2581         writeStringToParcel(p, p_cur[i].gateways);
   2582         writeStringToParcel(p, p_cur[i].pcscf);
   2583         appendPrintBuf("%s[status=%d,retry=%d,cid=%d,%s,%s,%s,%s,%s,%s,%s],", printBuf,
   2584             p_cur[i].status,
   2585             p_cur[i].suggestedRetryTime,
   2586             p_cur[i].cid,
   2587             (p_cur[i].active==0)?"down":"up",
   2588             (char*)p_cur[i].type,
   2589             (char*)p_cur[i].ifname,
   2590             (char*)p_cur[i].addresses,
   2591             (char*)p_cur[i].dnses,
   2592             (char*)p_cur[i].gateways,
   2593             (char*)p_cur[i].pcscf);
   2594     }
   2595     removeLastChar;
   2596     closeResponse;
   2597 
   2598     return 0;
   2599 }
   2600 
   2601 static int responseDataCallListV11(Parcel &p, void *response, size_t responselen) {
   2602     if (response == NULL && responselen != 0) {
   2603                 RLOGE("invalid response: NULL");
   2604                 return RIL_ERRNO_INVALID_RESPONSE;
   2605     }
   2606 
   2607     if (responselen % sizeof(RIL_Data_Call_Response_v11) != 0) {
   2608         RLOGE("invalid response length %d expected multiple of %d",
   2609         (int)responselen, (int)sizeof(RIL_Data_Call_Response_v11));
   2610         return RIL_ERRNO_INVALID_RESPONSE;
   2611     }
   2612 
   2613     // Write version
   2614     p.writeInt32(11);
   2615 
   2616     int num = responselen / sizeof(RIL_Data_Call_Response_v11);
   2617     p.writeInt32(num);
   2618 
   2619     RIL_Data_Call_Response_v11 *p_cur = (RIL_Data_Call_Response_v11 *) response;
   2620     startResponse;
   2621     int i;
   2622     for (i = 0; i < num; i++) {
   2623         p.writeInt32((int)p_cur[i].status);
   2624         p.writeInt32(p_cur[i].suggestedRetryTime);
   2625         p.writeInt32(p_cur[i].cid);
   2626         p.writeInt32(p_cur[i].active);
   2627         writeStringToParcel(p, p_cur[i].type);
   2628         writeStringToParcel(p, p_cur[i].ifname);
   2629         writeStringToParcel(p, p_cur[i].addresses);
   2630         writeStringToParcel(p, p_cur[i].dnses);
   2631         writeStringToParcel(p, p_cur[i].gateways);
   2632         writeStringToParcel(p, p_cur[i].pcscf);
   2633         p.writeInt32(p_cur[i].mtu);
   2634         appendPrintBuf("%s[status=%d,retry=%d,cid=%d,%s,%s,%s,%s,%s,%s,%s,mtu=%d],", printBuf,
   2635         p_cur[i].status,
   2636         p_cur[i].suggestedRetryTime,
   2637         p_cur[i].cid,
   2638         (p_cur[i].active==0)?"down":"up",
   2639         (char*)p_cur[i].type,
   2640         (char*)p_cur[i].ifname,
   2641         (char*)p_cur[i].addresses,
   2642         (char*)p_cur[i].dnses,
   2643         (char*)p_cur[i].gateways,
   2644         (char*)p_cur[i].pcscf,
   2645         p_cur[i].mtu);
   2646     }
   2647     removeLastChar;
   2648     closeResponse;
   2649 
   2650     return 0;
   2651 }
   2652 
   2653 static int responseDataCallList(Parcel &p, void *response, size_t responselen)
   2654 {
   2655     if (s_callbacks.version <= LAST_IMPRECISE_RIL_VERSION) {
   2656         if (s_callbacks.version < 5) {
   2657             RLOGD("responseDataCallList: v4");
   2658             return responseDataCallListV4(p, response, responselen);
   2659         } else if (responselen % sizeof(RIL_Data_Call_Response_v6) == 0) {
   2660             return responseDataCallListV6(p, response, responselen);
   2661         } else if (responselen % sizeof(RIL_Data_Call_Response_v9) == 0) {
   2662             return responseDataCallListV9(p, response, responselen);
   2663         } else {
   2664             return responseDataCallListV11(p, response, responselen);
   2665         }
   2666     } else { // RIL version >= 13
   2667         if (responselen % sizeof(RIL_Data_Call_Response_v11) != 0) {
   2668             RLOGE("Data structure expected is RIL_Data_Call_Response_v11");
   2669             if (!isDebuggable()) {
   2670                 return RIL_ERRNO_INVALID_RESPONSE;
   2671             } else {
   2672                 assert(0);
   2673             }
   2674         }
   2675         return responseDataCallListV11(p, response, responselen);
   2676     }
   2677 }
   2678 
   2679 static int responseSetupDataCall(Parcel &p, void *response, size_t responselen)
   2680 {
   2681     if (s_callbacks.version < 5) {
   2682         return responseStringsWithVersion(s_callbacks.version, p, response, responselen);
   2683     } else {
   2684         return responseDataCallList(p, response, responselen);
   2685     }
   2686 }
   2687 
   2688 static int responseRaw(Parcel &p, void *response, size_t responselen) {
   2689     if (response == NULL && responselen != 0) {
   2690         RLOGE("invalid response: NULL with responselen != 0");
   2691         return RIL_ERRNO_INVALID_RESPONSE;
   2692     }
   2693 
   2694     // The java code reads -1 size as null byte array
   2695     if (response == NULL) {
   2696         p.writeInt32(-1);
   2697     } else {
   2698         p.writeInt32(responselen);
   2699         p.write(response, responselen);
   2700     }
   2701 
   2702     return 0;
   2703 }
   2704 
   2705 
   2706 static int responseSIM_IO(Parcel &p, void *response, size_t responselen) {
   2707     if (response == NULL) {
   2708         RLOGE("invalid response: NULL");
   2709         return RIL_ERRNO_INVALID_RESPONSE;
   2710     }
   2711 
   2712     if (responselen != sizeof (RIL_SIM_IO_Response) ) {
   2713         RLOGE("invalid response length was %d expected %d",
   2714                 (int)responselen, (int)sizeof (RIL_SIM_IO_Response));
   2715         return RIL_ERRNO_INVALID_RESPONSE;
   2716     }
   2717 
   2718     RIL_SIM_IO_Response *p_cur = (RIL_SIM_IO_Response *) response;
   2719     p.writeInt32(p_cur->sw1);
   2720     p.writeInt32(p_cur->sw2);
   2721     writeStringToParcel(p, p_cur->simResponse);
   2722 
   2723     startResponse;
   2724     appendPrintBuf("%ssw1=0x%X,sw2=0x%X,%s", printBuf, p_cur->sw1, p_cur->sw2,
   2725         (char*)p_cur->simResponse);
   2726     closeResponse;
   2727 
   2728 
   2729     return 0;
   2730 }
   2731 
   2732 static int responseCallForwards(Parcel &p, void *response, size_t responselen) {
   2733     int num;
   2734 
   2735     if (response == NULL && responselen != 0) {
   2736         RLOGE("invalid response: NULL");
   2737         return RIL_ERRNO_INVALID_RESPONSE;
   2738     }
   2739 
   2740     if (responselen % sizeof(RIL_CallForwardInfo *) != 0) {
   2741         RLOGE("responseCallForwards: invalid response length %d expected multiple of %d",
   2742                 (int)responselen, (int)sizeof(RIL_CallForwardInfo *));
   2743         return RIL_ERRNO_INVALID_RESPONSE;
   2744     }
   2745 
   2746     /* number of call info's */
   2747     num = responselen / sizeof(RIL_CallForwardInfo *);
   2748     p.writeInt32(num);
   2749 
   2750     startResponse;
   2751     for (int i = 0 ; i < num ; i++) {
   2752         RIL_CallForwardInfo *p_cur = ((RIL_CallForwardInfo **) response)[i];
   2753 
   2754         p.writeInt32(p_cur->status);
   2755         p.writeInt32(p_cur->reason);
   2756         p.writeInt32(p_cur->serviceClass);
   2757         p.writeInt32(p_cur->toa);
   2758         writeStringToParcel(p, p_cur->number);
   2759         p.writeInt32(p_cur->timeSeconds);
   2760         appendPrintBuf("%s[%s,reason=%d,cls=%d,toa=%d,%s,tout=%d],", printBuf,
   2761             (p_cur->status==1)?"enable":"disable",
   2762             p_cur->reason, p_cur->serviceClass, p_cur->toa,
   2763             (char*)p_cur->number,
   2764             p_cur->timeSeconds);
   2765     }
   2766     removeLastChar;
   2767     closeResponse;
   2768 
   2769     return 0;
   2770 }
   2771 
   2772 static int responseSsn(Parcel &p, void *response, size_t responselen) {
   2773     if (response == NULL) {
   2774         RLOGE("invalid response: NULL");
   2775         return RIL_ERRNO_INVALID_RESPONSE;
   2776     }
   2777 
   2778     if (responselen != sizeof(RIL_SuppSvcNotification)) {
   2779         RLOGE("invalid response length was %d expected %d",
   2780                 (int)responselen, (int)sizeof (RIL_SuppSvcNotification));
   2781         return RIL_ERRNO_INVALID_RESPONSE;
   2782     }
   2783 
   2784     RIL_SuppSvcNotification *p_cur = (RIL_SuppSvcNotification *) response;
   2785     p.writeInt32(p_cur->notificationType);
   2786     p.writeInt32(p_cur->code);
   2787     p.writeInt32(p_cur->index);
   2788     p.writeInt32(p_cur->type);
   2789     writeStringToParcel(p, p_cur->number);
   2790 
   2791     startResponse;
   2792     appendPrintBuf("%s%s,code=%d,id=%d,type=%d,%s", printBuf,
   2793         (p_cur->notificationType==0)?"mo":"mt",
   2794          p_cur->code, p_cur->index, p_cur->type,
   2795         (char*)p_cur->number);
   2796     closeResponse;
   2797 
   2798     return 0;
   2799 }
   2800 
   2801 static int responseCellList(Parcel &p, void *response, size_t responselen) {
   2802     int num;
   2803 
   2804     if (response == NULL && responselen != 0) {
   2805         RLOGE("invalid response: NULL");
   2806         return RIL_ERRNO_INVALID_RESPONSE;
   2807     }
   2808 
   2809     if (responselen % sizeof (RIL_NeighboringCell *) != 0) {
   2810         RLOGE("responseCellList: invalid response length %d expected multiple of %d\n",
   2811             (int)responselen, (int)sizeof (RIL_NeighboringCell *));
   2812         return RIL_ERRNO_INVALID_RESPONSE;
   2813     }
   2814 
   2815     startResponse;
   2816     /* number of records */
   2817     num = responselen / sizeof(RIL_NeighboringCell *);
   2818     p.writeInt32(num);
   2819 
   2820     for (int i = 0 ; i < num ; i++) {
   2821         RIL_NeighboringCell *p_cur = ((RIL_NeighboringCell **) response)[i];
   2822 
   2823         p.writeInt32(p_cur->rssi);
   2824         writeStringToParcel (p, p_cur->cid);
   2825 
   2826         appendPrintBuf("%s[cid=%s,rssi=%d],", printBuf,
   2827             p_cur->cid, p_cur->rssi);
   2828     }
   2829     removeLastChar;
   2830     closeResponse;
   2831 
   2832     return 0;
   2833 }
   2834 
   2835 /**
   2836  * Marshall the signalInfoRecord into the parcel if it exists.
   2837  */
   2838 static void marshallSignalInfoRecord(Parcel &p,
   2839             RIL_CDMA_SignalInfoRecord &p_signalInfoRecord) {
   2840     p.writeInt32(p_signalInfoRecord.isPresent);
   2841     p.writeInt32(p_signalInfoRecord.signalType);
   2842     p.writeInt32(p_signalInfoRecord.alertPitch);
   2843     p.writeInt32(p_signalInfoRecord.signal);
   2844 }
   2845 
   2846 static int responseCdmaInformationRecords(Parcel &p,
   2847             void *response, size_t responselen) {
   2848     int num;
   2849     char* string8 = NULL;
   2850     int buffer_lenght;
   2851     RIL_CDMA_InformationRecord *infoRec;
   2852 
   2853     if (response == NULL && responselen != 0) {
   2854         RLOGE("invalid response: NULL");
   2855         return RIL_ERRNO_INVALID_RESPONSE;
   2856     }
   2857 
   2858     if (responselen != sizeof (RIL_CDMA_InformationRecords)) {
   2859         RLOGE("responseCdmaInformationRecords: invalid response length %d expected multiple of %d\n",
   2860             (int)responselen, (int)sizeof (RIL_CDMA_InformationRecords *));
   2861         return RIL_ERRNO_INVALID_RESPONSE;
   2862     }
   2863 
   2864     RIL_CDMA_InformationRecords *p_cur =
   2865                              (RIL_CDMA_InformationRecords *) response;
   2866     num = MIN(p_cur->numberOfInfoRecs, RIL_CDMA_MAX_NUMBER_OF_INFO_RECS);
   2867 
   2868     startResponse;
   2869     p.writeInt32(num);
   2870 
   2871     for (int i = 0 ; i < num ; i++) {
   2872         infoRec = &p_cur->infoRec[i];
   2873         p.writeInt32(infoRec->name);
   2874         switch (infoRec->name) {
   2875             case RIL_CDMA_DISPLAY_INFO_REC:
   2876             case RIL_CDMA_EXTENDED_DISPLAY_INFO_REC:
   2877                 if (infoRec->rec.display.alpha_len >
   2878                                          CDMA_ALPHA_INFO_BUFFER_LENGTH) {
   2879                     RLOGE("invalid display info response length %d \
   2880                           expected not more than %d\n",
   2881                          (int)infoRec->rec.display.alpha_len,
   2882                          CDMA_ALPHA_INFO_BUFFER_LENGTH);
   2883                     return RIL_ERRNO_INVALID_RESPONSE;
   2884                 }
   2885                 string8 = (char*) calloc(infoRec->rec.display.alpha_len + 1, sizeof(char));
   2886                 if (string8 == NULL) {
   2887                     RLOGE("Memory allocation failed for responseCdmaInformationRecords");
   2888                     closeRequest;
   2889                     return RIL_ERRNO_NO_MEMORY;
   2890                 }
   2891                 for (int i = 0 ; i < infoRec->rec.display.alpha_len ; i++) {
   2892                     string8[i] = infoRec->rec.display.alpha_buf[i];
   2893                 }
   2894                 string8[(int)infoRec->rec.display.alpha_len] = '\0';
   2895                 writeStringToParcel(p, (const char*)string8);
   2896                 free(string8);
   2897                 string8 = NULL;
   2898                 break;
   2899             case RIL_CDMA_CALLED_PARTY_NUMBER_INFO_REC:
   2900             case RIL_CDMA_CALLING_PARTY_NUMBER_INFO_REC:
   2901             case RIL_CDMA_CONNECTED_NUMBER_INFO_REC:
   2902                 if (infoRec->rec.number.len > CDMA_NUMBER_INFO_BUFFER_LENGTH) {
   2903                     RLOGE("invalid display info response length %d \
   2904                           expected not more than %d\n",
   2905                          (int)infoRec->rec.number.len,
   2906                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
   2907                     return RIL_ERRNO_INVALID_RESPONSE;
   2908                 }
   2909                 string8 = (char*) calloc(infoRec->rec.number.len + 1, sizeof(char));
   2910                 if (string8 == NULL) {
   2911                     RLOGE("Memory allocation failed for responseCdmaInformationRecords");
   2912                     closeRequest;
   2913                     return RIL_ERRNO_NO_MEMORY;
   2914                 }
   2915                 for (int i = 0 ; i < infoRec->rec.number.len; i++) {
   2916                     string8[i] = infoRec->rec.number.buf[i];
   2917                 }
   2918                 string8[(int)infoRec->rec.number.len] = '\0';
   2919                 writeStringToParcel(p, (const char*)string8);
   2920                 free(string8);
   2921                 string8 = NULL;
   2922                 p.writeInt32(infoRec->rec.number.number_type);
   2923                 p.writeInt32(infoRec->rec.number.number_plan);
   2924                 p.writeInt32(infoRec->rec.number.pi);
   2925                 p.writeInt32(infoRec->rec.number.si);
   2926                 break;
   2927             case RIL_CDMA_SIGNAL_INFO_REC:
   2928                 p.writeInt32(infoRec->rec.signal.isPresent);
   2929                 p.writeInt32(infoRec->rec.signal.signalType);
   2930                 p.writeInt32(infoRec->rec.signal.alertPitch);
   2931                 p.writeInt32(infoRec->rec.signal.signal);
   2932 
   2933                 appendPrintBuf("%sisPresent=%X, signalType=%X, \
   2934                                 alertPitch=%X, signal=%X, ",
   2935                    printBuf, (int)infoRec->rec.signal.isPresent,
   2936                    (int)infoRec->rec.signal.signalType,
   2937                    (int)infoRec->rec.signal.alertPitch,
   2938                    (int)infoRec->rec.signal.signal);
   2939                 removeLastChar;
   2940                 break;
   2941             case RIL_CDMA_REDIRECTING_NUMBER_INFO_REC:
   2942                 if (infoRec->rec.redir.redirectingNumber.len >
   2943                                               CDMA_NUMBER_INFO_BUFFER_LENGTH) {
   2944                     RLOGE("invalid display info response length %d \
   2945                           expected not more than %d\n",
   2946                          (int)infoRec->rec.redir.redirectingNumber.len,
   2947                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
   2948                     return RIL_ERRNO_INVALID_RESPONSE;
   2949                 }
   2950                 string8 = (char*) calloc(infoRec->rec.redir.redirectingNumber.len + 1,
   2951                         sizeof(char));
   2952                 if (string8 == NULL) {
   2953                     RLOGE("Memory allocation failed for responseCdmaInformationRecords");
   2954                     closeRequest;
   2955                     return RIL_ERRNO_NO_MEMORY;
   2956                 }
   2957                 for (int i = 0;
   2958                          i < infoRec->rec.redir.redirectingNumber.len;
   2959                          i++) {
   2960                     string8[i] = infoRec->rec.redir.redirectingNumber.buf[i];
   2961                 }
   2962                 string8[(int)infoRec->rec.redir.redirectingNumber.len] = '\0';
   2963                 writeStringToParcel(p, (const char*)string8);
   2964                 free(string8);
   2965                 string8 = NULL;
   2966                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_type);
   2967                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_plan);
   2968                 p.writeInt32(infoRec->rec.redir.redirectingNumber.pi);
   2969                 p.writeInt32(infoRec->rec.redir.redirectingNumber.si);
   2970                 p.writeInt32(infoRec->rec.redir.redirectingReason);
   2971                 break;
   2972             case RIL_CDMA_LINE_CONTROL_INFO_REC:
   2973                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPolarityIncluded);
   2974                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlToggle);
   2975                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlReverse);
   2976                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPowerDenial);
   2977 
   2978                 appendPrintBuf("%slineCtrlPolarityIncluded=%d, \
   2979                                 lineCtrlToggle=%d, lineCtrlReverse=%d, \
   2980                                 lineCtrlPowerDenial=%d, ", printBuf,
   2981                        (int)infoRec->rec.lineCtrl.lineCtrlPolarityIncluded,
   2982                        (int)infoRec->rec.lineCtrl.lineCtrlToggle,
   2983                        (int)infoRec->rec.lineCtrl.lineCtrlReverse,
   2984                        (int)infoRec->rec.lineCtrl.lineCtrlPowerDenial);
   2985                 removeLastChar;
   2986                 break;
   2987             case RIL_CDMA_T53_CLIR_INFO_REC:
   2988                 p.writeInt32((int)(infoRec->rec.clir.cause));
   2989 
   2990                 appendPrintBuf("%scause%d", printBuf, infoRec->rec.clir.cause);
   2991                 removeLastChar;
   2992                 break;
   2993             case RIL_CDMA_T53_AUDIO_CONTROL_INFO_REC:
   2994                 p.writeInt32(infoRec->rec.audioCtrl.upLink);
   2995                 p.writeInt32(infoRec->rec.audioCtrl.downLink);
   2996 
   2997                 appendPrintBuf("%supLink=%d, downLink=%d, ", printBuf,
   2998                         infoRec->rec.audioCtrl.upLink,
   2999                         infoRec->rec.audioCtrl.downLink);
   3000                 removeLastChar;
   3001                 break;
   3002             case RIL_CDMA_T53_RELEASE_INFO_REC:
   3003                 // TODO(Moto): See David Krause, he has the answer:)
   3004                 RLOGE("RIL_CDMA_T53_RELEASE_INFO_REC: return INVALID_RESPONSE");
   3005                 return RIL_ERRNO_INVALID_RESPONSE;
   3006             default:
   3007                 RLOGE("Incorrect name value");
   3008                 return RIL_ERRNO_INVALID_RESPONSE;
   3009         }
   3010     }
   3011     closeResponse;
   3012 
   3013     return 0;
   3014 }
   3015 
   3016 static void responseRilSignalStrengthV5(Parcel &p, RIL_SignalStrength_v10 *p_cur) {
   3017     p.writeInt32(p_cur->GW_SignalStrength.signalStrength);
   3018     p.writeInt32(p_cur->GW_SignalStrength.bitErrorRate);
   3019     p.writeInt32(p_cur->CDMA_SignalStrength.dbm);
   3020     p.writeInt32(p_cur->CDMA_SignalStrength.ecio);
   3021     p.writeInt32(p_cur->EVDO_SignalStrength.dbm);
   3022     p.writeInt32(p_cur->EVDO_SignalStrength.ecio);
   3023     p.writeInt32(p_cur->EVDO_SignalStrength.signalNoiseRatio);
   3024 }
   3025 
   3026 static void responseRilSignalStrengthV6Extra(Parcel &p, RIL_SignalStrength_v10 *p_cur) {
   3027     /*
   3028      * Fixup LTE for backwards compatibility
   3029      */
   3030     // signalStrength: -1 -> 99
   3031     if (p_cur->LTE_SignalStrength.signalStrength == -1) {
   3032         p_cur->LTE_SignalStrength.signalStrength = 99;
   3033     }
   3034     // rsrp: -1 -> INT_MAX all other negative value to positive.
   3035     // So remap here
   3036     if (p_cur->LTE_SignalStrength.rsrp == -1) {
   3037         p_cur->LTE_SignalStrength.rsrp = INT_MAX;
   3038     } else if (p_cur->LTE_SignalStrength.rsrp < -1) {
   3039         p_cur->LTE_SignalStrength.rsrp = -p_cur->LTE_SignalStrength.rsrp;
   3040     }
   3041     // rsrq: -1 -> INT_MAX
   3042     if (p_cur->LTE_SignalStrength.rsrq == -1) {
   3043         p_cur->LTE_SignalStrength.rsrq = INT_MAX;
   3044     }
   3045     // Not remapping rssnr is already using INT_MAX
   3046 
   3047     // cqi: -1 -> INT_MAX
   3048     if (p_cur->LTE_SignalStrength.cqi == -1) {
   3049         p_cur->LTE_SignalStrength.cqi = INT_MAX;
   3050     }
   3051 
   3052     p.writeInt32(p_cur->LTE_SignalStrength.signalStrength);
   3053     p.writeInt32(p_cur->LTE_SignalStrength.rsrp);
   3054     p.writeInt32(p_cur->LTE_SignalStrength.rsrq);
   3055     p.writeInt32(p_cur->LTE_SignalStrength.rssnr);
   3056     p.writeInt32(p_cur->LTE_SignalStrength.cqi);
   3057 }
   3058 
   3059 static void responseRilSignalStrengthV10(Parcel &p, RIL_SignalStrength_v10 *p_cur) {
   3060     responseRilSignalStrengthV5(p, p_cur);
   3061     responseRilSignalStrengthV6Extra(p, p_cur);
   3062     p.writeInt32(p_cur->TD_SCDMA_SignalStrength.rscp);
   3063 }
   3064 
   3065 static int responseRilSignalStrength(Parcel &p,
   3066                     void *response, size_t responselen) {
   3067     if (response == NULL && responselen != 0) {
   3068         RLOGE("invalid response: NULL");
   3069         return RIL_ERRNO_INVALID_RESPONSE;
   3070     }
   3071 
   3072     RIL_SignalStrength_v10 *p_cur;
   3073     if (s_callbacks.version <= LAST_IMPRECISE_RIL_VERSION) {
   3074         if (responselen >= sizeof (RIL_SignalStrength_v5)) {
   3075             p_cur = ((RIL_SignalStrength_v10 *) response);
   3076 
   3077             responseRilSignalStrengthV5(p, p_cur);
   3078 
   3079             if (responselen >= sizeof (RIL_SignalStrength_v6)) {
   3080                 responseRilSignalStrengthV6Extra(p, p_cur);
   3081                 if (responselen >= sizeof (RIL_SignalStrength_v10)) {
   3082                     p.writeInt32(p_cur->TD_SCDMA_SignalStrength.rscp);
   3083                 } else {
   3084                     p.writeInt32(INT_MAX);
   3085                 }
   3086             } else {
   3087                 p.writeInt32(99);
   3088                 p.writeInt32(INT_MAX);
   3089                 p.writeInt32(INT_MAX);
   3090                 p.writeInt32(INT_MAX);
   3091                 p.writeInt32(INT_MAX);
   3092                 p.writeInt32(INT_MAX);
   3093             }
   3094         } else {
   3095             RLOGE("invalid response length");
   3096             return RIL_ERRNO_INVALID_RESPONSE;
   3097         }
   3098     } else { // RIL version >= 13
   3099         if (responselen % sizeof(RIL_SignalStrength_v10) != 0) {
   3100             RLOGE("Data structure expected is RIL_SignalStrength_v10");
   3101             if (!isDebuggable()) {
   3102                 return RIL_ERRNO_INVALID_RESPONSE;
   3103             } else {
   3104                 assert(0);
   3105             }
   3106         }
   3107         p_cur = ((RIL_SignalStrength_v10 *) response);
   3108         responseRilSignalStrengthV10(p, p_cur);
   3109     }
   3110     startResponse;
   3111     appendPrintBuf("%s[signalStrength=%d,bitErrorRate=%d,\
   3112             CDMA_SS.dbm=%d,CDMA_SSecio=%d,\
   3113             EVDO_SS.dbm=%d,EVDO_SS.ecio=%d,\
   3114             EVDO_SS.signalNoiseRatio=%d,\
   3115             LTE_SS.signalStrength=%d,LTE_SS.rsrp=%d,LTE_SS.rsrq=%d,\
   3116             LTE_SS.rssnr=%d,LTE_SS.cqi=%d,TDSCDMA_SS.rscp=%d]",
   3117             printBuf,
   3118             p_cur->GW_SignalStrength.signalStrength,
   3119             p_cur->GW_SignalStrength.bitErrorRate,
   3120             p_cur->CDMA_SignalStrength.dbm,
   3121             p_cur->CDMA_SignalStrength.ecio,
   3122             p_cur->EVDO_SignalStrength.dbm,
   3123             p_cur->EVDO_SignalStrength.ecio,
   3124             p_cur->EVDO_SignalStrength.signalNoiseRatio,
   3125             p_cur->LTE_SignalStrength.signalStrength,
   3126             p_cur->LTE_SignalStrength.rsrp,
   3127             p_cur->LTE_SignalStrength.rsrq,
   3128             p_cur->LTE_SignalStrength.rssnr,
   3129             p_cur->LTE_SignalStrength.cqi,
   3130             p_cur->TD_SCDMA_SignalStrength.rscp);
   3131     closeResponse;
   3132     return 0;
   3133 }
   3134 
   3135 static int responseCallRing(Parcel &p, void *response, size_t responselen) {
   3136     if ((response == NULL) || (responselen == 0)) {
   3137         return responseVoid(p, response, responselen);
   3138     } else {
   3139         return responseCdmaSignalInfoRecord(p, response, responselen);
   3140     }
   3141 }
   3142 
   3143 static int responseCdmaSignalInfoRecord(Parcel &p, void *response, size_t responselen) {
   3144     if (response == NULL || responselen == 0) {
   3145         RLOGE("invalid response: NULL");
   3146         return RIL_ERRNO_INVALID_RESPONSE;
   3147     }
   3148 
   3149     if (responselen != sizeof (RIL_CDMA_SignalInfoRecord)) {
   3150         RLOGE("invalid response length %d expected sizeof (RIL_CDMA_SignalInfoRecord) of %d\n",
   3151             (int)responselen, (int)sizeof (RIL_CDMA_SignalInfoRecord));
   3152         return RIL_ERRNO_INVALID_RESPONSE;
   3153     }
   3154 
   3155     startResponse;
   3156 
   3157     RIL_CDMA_SignalInfoRecord *p_cur = ((RIL_CDMA_SignalInfoRecord *) response);
   3158     marshallSignalInfoRecord(p, *p_cur);
   3159 
   3160     appendPrintBuf("%s[isPresent=%d,signalType=%d,alertPitch=%d\
   3161               signal=%d]",
   3162               printBuf,
   3163               p_cur->isPresent,
   3164               p_cur->signalType,
   3165               p_cur->alertPitch,
   3166               p_cur->signal);
   3167 
   3168     closeResponse;
   3169     return 0;
   3170 }
   3171 
   3172 static int responseCdmaCallWaiting(Parcel &p, void *response,
   3173             size_t responselen) {
   3174     if (response == NULL && responselen != 0) {
   3175         RLOGE("invalid response: NULL");
   3176         return RIL_ERRNO_INVALID_RESPONSE;
   3177     }
   3178 
   3179     if (responselen < sizeof(RIL_CDMA_CallWaiting_v6)) {
   3180         RLOGW("Upgrade to ril version %d\n", RIL_VERSION);
   3181     }
   3182 
   3183     RIL_CDMA_CallWaiting_v6 *p_cur = ((RIL_CDMA_CallWaiting_v6 *) response);
   3184 
   3185     writeStringToParcel(p, p_cur->number);
   3186     p.writeInt32(p_cur->numberPresentation);
   3187     writeStringToParcel(p, p_cur->name);
   3188     marshallSignalInfoRecord(p, p_cur->signalInfoRecord);
   3189 
   3190     if (s_callbacks.version <= LAST_IMPRECISE_RIL_VERSION) {
   3191         if (responselen >= sizeof(RIL_CDMA_CallWaiting_v6)) {
   3192             p.writeInt32(p_cur->number_type);
   3193             p.writeInt32(p_cur->number_plan);
   3194         } else {
   3195             p.writeInt32(0);
   3196             p.writeInt32(0);
   3197         }
   3198     } else { // RIL version >= 13
   3199         if (responselen % sizeof(RIL_CDMA_CallWaiting_v6) != 0) {
   3200             RLOGE("Data structure expected is RIL_CDMA_CallWaiting_v6");
   3201             if (!isDebuggable()) {
   3202                 return RIL_ERRNO_INVALID_RESPONSE;
   3203             } else {
   3204                 assert(0);
   3205             }
   3206         }
   3207         p.writeInt32(p_cur->number_type);
   3208         p.writeInt32(p_cur->number_plan);
   3209     }
   3210 
   3211     startResponse;
   3212     appendPrintBuf("%snumber=%s,numberPresentation=%d, name=%s,\
   3213             signalInfoRecord[isPresent=%d,signalType=%d,alertPitch=%d\
   3214             signal=%d,number_type=%d,number_plan=%d]",
   3215             printBuf,
   3216             p_cur->number,
   3217             p_cur->numberPresentation,
   3218             p_cur->name,
   3219             p_cur->signalInfoRecord.isPresent,
   3220             p_cur->signalInfoRecord.signalType,
   3221             p_cur->signalInfoRecord.alertPitch,
   3222             p_cur->signalInfoRecord.signal,
   3223             p_cur->number_type,
   3224             p_cur->number_plan);
   3225     closeResponse;
   3226 
   3227     return 0;
   3228 }
   3229 
   3230 static void responseSimRefreshV7(Parcel &p, void *response) {
   3231       RIL_SimRefreshResponse_v7 *p_cur = ((RIL_SimRefreshResponse_v7 *) response);
   3232       p.writeInt32(p_cur->result);
   3233       p.writeInt32(p_cur->ef_id);
   3234       writeStringToParcel(p, p_cur->aid);
   3235 
   3236       appendPrintBuf("%sresult=%d, ef_id=%d, aid=%s",
   3237             printBuf,
   3238             p_cur->result,
   3239             p_cur->ef_id,
   3240             p_cur->aid);
   3241 
   3242 }
   3243 
   3244 static int responseSimRefresh(Parcel &p, void *response, size_t responselen) {
   3245     if (response == NULL && responselen != 0) {
   3246         RLOGE("responseSimRefresh: invalid response: NULL");
   3247         return RIL_ERRNO_INVALID_RESPONSE;
   3248     }
   3249 
   3250     startResponse;
   3251     if (s_callbacks.version <= LAST_IMPRECISE_RIL_VERSION) {
   3252         if (s_callbacks.version >= 7) {
   3253             responseSimRefreshV7(p, response);
   3254         } else {
   3255             int *p_cur = ((int *) response);
   3256             p.writeInt32(p_cur[0]);
   3257             p.writeInt32(p_cur[1]);
   3258             writeStringToParcel(p, NULL);
   3259 
   3260             appendPrintBuf("%sresult=%d, ef_id=%d",
   3261                     printBuf,
   3262                     p_cur[0],
   3263                     p_cur[1]);
   3264         }
   3265     } else { // RIL version >= 13
   3266         if (responselen % sizeof(RIL_SimRefreshResponse_v7) != 0) {
   3267             RLOGE("Data structure expected is RIL_SimRefreshResponse_v7");
   3268             if (!isDebuggable()) {
   3269                 return RIL_ERRNO_INVALID_RESPONSE;
   3270             } else {
   3271                 assert(0);
   3272             }
   3273         }
   3274         responseSimRefreshV7(p, response);
   3275 
   3276     }
   3277     closeResponse;
   3278 
   3279     return 0;
   3280 }
   3281 
   3282 static int responseCellInfoListV6(Parcel &p, void *response, size_t responselen) {
   3283     if (response == NULL && responselen != 0) {
   3284         RLOGE("invalid response: NULL");
   3285         return RIL_ERRNO_INVALID_RESPONSE;
   3286     }
   3287 
   3288     if (responselen % sizeof(RIL_CellInfo) != 0) {
   3289         RLOGE("responseCellInfoList: invalid response length %d expected multiple of %d",
   3290                 (int)responselen, (int)sizeof(RIL_CellInfo));
   3291         return RIL_ERRNO_INVALID_RESPONSE;
   3292     }
   3293 
   3294     int num = responselen / sizeof(RIL_CellInfo);
   3295     p.writeInt32(num);
   3296 
   3297     RIL_CellInfo *p_cur = (RIL_CellInfo *) response;
   3298     startResponse;
   3299     int i;
   3300     for (i = 0; i < num; i++) {
   3301         p.writeInt32((int)p_cur->cellInfoType);
   3302         p.writeInt32(p_cur->registered);
   3303         p.writeInt32(p_cur->timeStampType);
   3304         p.writeInt64(p_cur->timeStamp);
   3305         switch(p_cur->cellInfoType) {
   3306             case RIL_CELL_INFO_TYPE_GSM: {
   3307                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mcc);
   3308                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mnc);
   3309                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.lac);
   3310                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.cid);
   3311                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength);
   3312                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
   3313                 break;
   3314             }
   3315             case RIL_CELL_INFO_TYPE_WCDMA: {
   3316                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc);
   3317                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc);
   3318                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.lac);
   3319                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.cid);
   3320                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
   3321                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength);
   3322                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
   3323                 break;
   3324             }
   3325             case RIL_CELL_INFO_TYPE_CDMA: {
   3326                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.networkId);
   3327                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.systemId);
   3328                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.basestationId);
   3329                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.longitude);
   3330                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
   3331 
   3332                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.dbm);
   3333                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.ecio);
   3334                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.dbm);
   3335                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.ecio);
   3336                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
   3337                 break;
   3338             }
   3339             case RIL_CELL_INFO_TYPE_LTE: {
   3340                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mcc);
   3341                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mnc);
   3342                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.ci);
   3343                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.pci);
   3344                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.tac);
   3345 
   3346                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.signalStrength);
   3347                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrp);
   3348                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrq);
   3349                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rssnr);
   3350                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.cqi);
   3351                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
   3352                 break;
   3353             }
   3354             case RIL_CELL_INFO_TYPE_TD_SCDMA: {
   3355                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.mcc);
   3356                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.mnc);
   3357                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.lac);
   3358                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.cid);
   3359                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.cpid);
   3360                 p.writeInt32(p_cur->CellInfo.tdscdma.signalStrengthTdscdma.rscp);
   3361                 break;
   3362             }
   3363         }
   3364         p_cur += 1;
   3365     }
   3366     removeLastChar;
   3367     closeResponse;
   3368 
   3369     return 0;
   3370 }
   3371 
   3372 static int responseCellInfoListV12(Parcel &p, void *response, size_t responselen) {
   3373     if (response == NULL && responselen != 0) {
   3374         RLOGE("invalid response: NULL");
   3375         return RIL_ERRNO_INVALID_RESPONSE;
   3376     }
   3377 
   3378     if (responselen % sizeof(RIL_CellInfo_v12) != 0) {
   3379         RLOGE("responseCellInfoList: invalid response length %d expected multiple of %d",
   3380                 (int)responselen, (int)sizeof(RIL_CellInfo_v12));
   3381         return RIL_ERRNO_INVALID_RESPONSE;
   3382     }
   3383 
   3384     int num = responselen / sizeof(RIL_CellInfo_v12);
   3385     p.writeInt32(num);
   3386 
   3387     RIL_CellInfo_v12 *p_cur = (RIL_CellInfo_v12 *) response;
   3388     startResponse;
   3389     int i;
   3390     for (i = 0; i < num; i++) {
   3391         p.writeInt32((int)p_cur->cellInfoType);
   3392         p.writeInt32(p_cur->registered);
   3393         p.writeInt32(p_cur->timeStampType);
   3394         p.writeInt64(p_cur->timeStamp);
   3395         switch(p_cur->cellInfoType) {
   3396             case RIL_CELL_INFO_TYPE_GSM: {
   3397                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mcc);
   3398                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mnc);
   3399                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.lac);
   3400                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.cid);
   3401                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.arfcn);
   3402                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.bsic);
   3403                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength);
   3404                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
   3405                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.timingAdvance);
   3406                 break;
   3407             }
   3408             case RIL_CELL_INFO_TYPE_WCDMA: {
   3409                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc);
   3410                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc);
   3411                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.lac);
   3412                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.cid);
   3413                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
   3414                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.uarfcn);
   3415                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength);
   3416                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
   3417                 break;
   3418             }
   3419             case RIL_CELL_INFO_TYPE_CDMA: {
   3420                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.networkId);
   3421                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.systemId);
   3422                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.basestationId);
   3423                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.longitude);
   3424                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
   3425 
   3426                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.dbm);
   3427                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.ecio);
   3428                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.dbm);
   3429                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.ecio);
   3430                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
   3431                 break;
   3432             }
   3433             case RIL_CELL_INFO_TYPE_LTE: {
   3434                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mcc);
   3435                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mnc);
   3436                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.ci);
   3437                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.pci);
   3438                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.tac);
   3439                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.earfcn);
   3440 
   3441                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.signalStrength);
   3442                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrp);
   3443                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrq);
   3444                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rssnr);
   3445                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.cqi);
   3446                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
   3447                 break;
   3448             }
   3449             case RIL_CELL_INFO_TYPE_TD_SCDMA: {
   3450                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.mcc);
   3451                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.mnc);
   3452                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.lac);
   3453                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.cid);
   3454                 p.writeInt32(p_cur->CellInfo.tdscdma.cellIdentityTdscdma.cpid);
   3455                 p.writeInt32(p_cur->CellInfo.tdscdma.signalStrengthTdscdma.rscp);
   3456                 break;
   3457             }
   3458         }
   3459         p_cur += 1;
   3460     }
   3461     removeLastChar;
   3462     closeResponse;
   3463     return 0;
   3464 }
   3465 
   3466 static int responseCellInfoList(Parcel &p, void *response, size_t responselen)
   3467 {
   3468     if (s_callbacks.version <= LAST_IMPRECISE_RIL_VERSION) {
   3469         if (s_callbacks.version < 12) {
   3470             RLOGD("responseCellInfoList: v6");
   3471             return responseCellInfoListV6(p, response, responselen);
   3472         } else {
   3473             RLOGD("responseCellInfoList: v12");
   3474             return responseCellInfoListV12(p, response, responselen);
   3475         }
   3476     } else { // RIL version >= 13
   3477         if (responselen % sizeof(RIL_CellInfo_v12) != 0) {
   3478             RLOGE("Data structure expected is RIL_CellInfo_v12");
   3479             if (!isDebuggable()) {
   3480                 return RIL_ERRNO_INVALID_RESPONSE;
   3481             } else {
   3482                 assert(0);
   3483             }
   3484         }
   3485         return responseCellInfoListV12(p, response, responselen);
   3486     }
   3487 
   3488     return 0;
   3489 }
   3490 
   3491 static int responseHardwareConfig(Parcel &p, void *response, size_t responselen)
   3492 {
   3493    if (response == NULL && responselen != 0) {
   3494        RLOGE("invalid response: NULL");
   3495        return RIL_ERRNO_INVALID_RESPONSE;
   3496    }
   3497 
   3498    if (responselen % sizeof(RIL_HardwareConfig) != 0) {
   3499        RLOGE("responseHardwareConfig: invalid response length %d expected multiple of %d",
   3500           (int)responselen, (int)sizeof(RIL_HardwareConfig));
   3501        return RIL_ERRNO_INVALID_RESPONSE;
   3502    }
   3503 
   3504    int num = responselen / sizeof(RIL_HardwareConfig);
   3505    int i;
   3506    RIL_HardwareConfig *p_cur = (RIL_HardwareConfig *) response;
   3507 
   3508    p.writeInt32(num);
   3509 
   3510    startResponse;
   3511    for (i = 0; i < num; i++) {
   3512       switch (p_cur[i].type) {
   3513          case RIL_HARDWARE_CONFIG_MODEM: {
   3514             writeStringToParcel(p, p_cur[i].uuid);
   3515             p.writeInt32((int)p_cur[i].state);
   3516             p.writeInt32(p_cur[i].cfg.modem.rat);
   3517             p.writeInt32(p_cur[i].cfg.modem.maxVoice);
   3518             p.writeInt32(p_cur[i].cfg.modem.maxData);
   3519             p.writeInt32(p_cur[i].cfg.modem.maxStandby);
   3520 
   3521             appendPrintBuf("%s modem: uuid=%s,state=%d,rat=%08x,maxV=%d,maxD=%d,maxS=%d", printBuf,
   3522                p_cur[i].uuid, (int)p_cur[i].state, p_cur[i].cfg.modem.rat,
   3523                p_cur[i].cfg.modem.maxVoice, p_cur[i].cfg.modem.maxData, p_cur[i].cfg.modem.maxStandby);
   3524             break;
   3525          }
   3526          case RIL_HARDWARE_CONFIG_SIM: {
   3527             writeStringToParcel(p, p_cur[i].uuid);
   3528             p.writeInt32((int)p_cur[i].state);
   3529             writeStringToParcel(p, p_cur[i].cfg.sim.modemUuid);
   3530 
   3531             appendPrintBuf("%s sim: uuid=%s,state=%d,modem-uuid=%s", printBuf,
   3532                p_cur[i].uuid, (int)p_cur[i].state, p_cur[i].cfg.sim.modemUuid);
   3533             break;
   3534          }
   3535       }
   3536    }
   3537    removeLastChar;
   3538    closeResponse;
   3539    return 0;
   3540 }
   3541 
   3542 static int responseRadioCapability(Parcel &p, void *response, size_t responselen) {
   3543     if (response == NULL) {
   3544         RLOGE("invalid response: NULL");
   3545         return RIL_ERRNO_INVALID_RESPONSE;
   3546     }
   3547 
   3548     if (responselen != sizeof (RIL_RadioCapability) ) {
   3549         RLOGE("invalid response length was %d expected %d",
   3550                 (int)responselen, (int)sizeof (RIL_SIM_IO_Response));
   3551         return RIL_ERRNO_INVALID_RESPONSE;
   3552     }
   3553 
   3554     RIL_RadioCapability *p_cur = (RIL_RadioCapability *) response;
   3555     p.writeInt32(p_cur->version);
   3556     p.writeInt32(p_cur->session);
   3557     p.writeInt32(p_cur->phase);
   3558     p.writeInt32(p_cur->rat);
   3559     writeStringToParcel(p, p_cur->logicalModemUuid);
   3560     p.writeInt32(p_cur->status);
   3561 
   3562     startResponse;
   3563     appendPrintBuf("%s[version=%d,session=%d,phase=%d,\
   3564             rat=%s,logicalModemUuid=%s,status=%d]",
   3565             printBuf,
   3566             p_cur->version,
   3567             p_cur->session,
   3568             p_cur->phase,
   3569             p_cur->rat,
   3570             p_cur->logicalModemUuid,
   3571             p_cur->status);
   3572     closeResponse;
   3573     return 0;
   3574 }
   3575 
   3576 static int responseSSData(Parcel &p, void *response, size_t responselen) {
   3577     RLOGD("In responseSSData");
   3578     int num;
   3579 
   3580     if (response == NULL && responselen != 0) {
   3581         RLOGE("invalid response length was %d expected %d",
   3582                 (int)responselen, (int)sizeof (RIL_SIM_IO_Response));
   3583         return RIL_ERRNO_INVALID_RESPONSE;
   3584     }
   3585 
   3586     if (responselen != sizeof(RIL_StkCcUnsolSsResponse)) {
   3587         RLOGE("invalid response length %d, expected %d",
   3588                (int)responselen, (int)sizeof(RIL_StkCcUnsolSsResponse));
   3589         return RIL_ERRNO_INVALID_RESPONSE;
   3590     }
   3591 
   3592     startResponse;
   3593     RIL_StkCcUnsolSsResponse *p_cur = (RIL_StkCcUnsolSsResponse *) response;
   3594     p.writeInt32(p_cur->serviceType);
   3595     p.writeInt32(p_cur->requestType);
   3596     p.writeInt32(p_cur->teleserviceType);
   3597     p.writeInt32(p_cur->serviceClass);
   3598     p.writeInt32(p_cur->result);
   3599 
   3600     if (isServiceTypeCfQuery(p_cur->serviceType, p_cur->requestType)) {
   3601         RLOGD("responseSSData CF type, num of Cf elements %d", p_cur->cfData.numValidIndexes);
   3602         if (p_cur->cfData.numValidIndexes > NUM_SERVICE_CLASSES) {
   3603             RLOGE("numValidIndexes is greater than max value %d, "
   3604                   "truncating it to max value", NUM_SERVICE_CLASSES);
   3605             p_cur->cfData.numValidIndexes = NUM_SERVICE_CLASSES;
   3606         }
   3607         /* number of call info's */
   3608         p.writeInt32(p_cur->cfData.numValidIndexes);
   3609 
   3610         for (int i = 0; i < p_cur->cfData.numValidIndexes; i++) {
   3611              RIL_CallForwardInfo cf = p_cur->cfData.cfInfo[i];
   3612 
   3613              p.writeInt32(cf.status);
   3614              p.writeInt32(cf.reason);
   3615              p.writeInt32(cf.serviceClass);
   3616              p.writeInt32(cf.toa);
   3617              writeStringToParcel(p, cf.number);
   3618              p.writeInt32(cf.timeSeconds);
   3619              appendPrintBuf("%s[%s,reason=%d,cls=%d,toa=%d,%s,tout=%d],", printBuf,
   3620                  (cf.status==1)?"enable":"disable", cf.reason, cf.serviceClass, cf.toa,
   3621                   (char*)cf.number, cf.timeSeconds);
   3622              RLOGD("Data: %d,reason=%d,cls=%d,toa=%d,num=%s,tout=%d],", cf.status,
   3623                   cf.reason, cf.serviceClass, cf.toa, (char*)cf.number, cf.timeSeconds);
   3624         }
   3625     } else {
   3626         p.writeInt32 (SS_INFO_MAX);
   3627 
   3628         /* each int*/
   3629         for (int i = 0; i < SS_INFO_MAX; i++) {
   3630              appendPrintBuf("%s%d,", printBuf, p_cur->ssInfo[i]);
   3631              RLOGD("Data: %d",p_cur->ssInfo[i]);
   3632              p.writeInt32(p_cur->ssInfo[i]);
   3633         }
   3634     }
   3635     removeLastChar;
   3636     closeResponse;
   3637 
   3638     return 0;
   3639 }
   3640 
   3641 static bool isServiceTypeCfQuery(RIL_SsServiceType serType, RIL_SsRequestType reqType) {
   3642     if ((reqType == SS_INTERROGATION) &&
   3643         (serType == SS_CFU ||
   3644          serType == SS_CF_BUSY ||
   3645          serType == SS_CF_NO_REPLY ||
   3646          serType == SS_CF_NOT_REACHABLE ||
   3647          serType == SS_CF_ALL ||
   3648          serType == SS_CF_ALL_CONDITIONAL)) {
   3649         return true;
   3650     }
   3651     return false;
   3652 }
   3653 
   3654 static void triggerEvLoop() {
   3655     int ret;
   3656     if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
   3657         /* trigger event loop to wakeup. No reason to do this,
   3658          * if we're in the event loop thread */
   3659          do {
   3660             ret = write (s_fdWakeupWrite, " ", 1);
   3661          } while (ret < 0 && errno == EINTR);
   3662     }
   3663 }
   3664 
   3665 static void rilEventAddWakeup(struct ril_event *ev) {
   3666     ril_event_add(ev);
   3667     triggerEvLoop();
   3668 }
   3669 
   3670 static void sendSimStatusAppInfo(Parcel &p, int num_apps, RIL_AppStatus appStatus[]) {
   3671         p.writeInt32(num_apps);
   3672         startResponse;
   3673         for (int i = 0; i < num_apps; i++) {
   3674             p.writeInt32(appStatus[i].app_type);
   3675             p.writeInt32(appStatus[i].app_state);
   3676             p.writeInt32(appStatus[i].perso_substate);
   3677             writeStringToParcel(p, (const char*)(appStatus[i].aid_ptr));
   3678             writeStringToParcel(p, (const char*)
   3679                                           (appStatus[i].app_label_ptr));
   3680             p.writeInt32(appStatus[i].pin1_replaced);
   3681             p.writeInt32(appStatus[i].pin1);
   3682             p.writeInt32(appStatus[i].pin2);
   3683             appendPrintBuf("%s[app_type=%d,app_state=%d,perso_substate=%d,\
   3684                     aid_ptr=%s,app_label_ptr=%s,pin1_replaced=%d,pin1=%d,pin2=%d],",
   3685                     printBuf,
   3686                     appStatus[i].app_type,
   3687                     appStatus[i].app_state,
   3688                     appStatus[i].perso_substate,
   3689                     appStatus[i].aid_ptr,
   3690                     appStatus[i].app_label_ptr,
   3691                     appStatus[i].pin1_replaced,
   3692                     appStatus[i].pin1,
   3693                     appStatus[i].pin2);
   3694         }
   3695         closeResponse;
   3696 }
   3697 
   3698 static void responseSimStatusV5(Parcel &p, void *response) {
   3699     RIL_CardStatus_v5 *p_cur = ((RIL_CardStatus_v5 *) response);
   3700 
   3701     p.writeInt32(p_cur->card_state);
   3702     p.writeInt32(p_cur->universal_pin_state);
   3703     p.writeInt32(p_cur->gsm_umts_subscription_app_index);
   3704     p.writeInt32(p_cur->cdma_subscription_app_index);
   3705 
   3706     sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
   3707 }
   3708 
   3709 static void responseSimStatusV6(Parcel &p, void *response) {
   3710     RIL_CardStatus_v6 *p_cur = ((RIL_CardStatus_v6 *) response);
   3711 
   3712     p.writeInt32(p_cur->card_state);
   3713     p.writeInt32(p_cur->universal_pin_state);
   3714     p.writeInt32(p_cur->gsm_umts_subscription_app_index);
   3715     p.writeInt32(p_cur->cdma_subscription_app_index);
   3716     p.writeInt32(p_cur->ims_subscription_app_index);
   3717 
   3718     sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
   3719 }
   3720 
   3721 static int responseSimStatus(Parcel &p, void *response, size_t responselen) {
   3722     int i;
   3723 
   3724     if (response == NULL && responselen != 0) {
   3725         RLOGE("invalid response: NULL");
   3726         return RIL_ERRNO_INVALID_RESPONSE;
   3727     }
   3728 
   3729     if (s_callbacks.version <= LAST_IMPRECISE_RIL_VERSION) {
   3730         if (responselen == sizeof (RIL_CardStatus_v6)) {
   3731             responseSimStatusV6(p, response);
   3732         } else if (responselen == sizeof (RIL_CardStatus_v5)) {
   3733             responseSimStatusV5(p, response);
   3734         } else {
   3735             RLOGE("responseSimStatus: A RilCardStatus_v6 or _v5 expected\n");
   3736             return RIL_ERRNO_INVALID_RESPONSE;
   3737         }
   3738     } else { // RIL version >= 13
   3739         if (responselen % sizeof(RIL_CardStatus_v6) != 0) {
   3740             RLOGE("Data structure expected is RIL_CardStatus_v6");
   3741             if (!isDebuggable()) {
   3742                 return RIL_ERRNO_INVALID_RESPONSE;
   3743             } else {
   3744                 assert(0);
   3745             }
   3746         }
   3747         responseSimStatusV6(p, response);
   3748     }
   3749 
   3750     return 0;
   3751 }
   3752 
   3753 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen) {
   3754     int num = responselen / sizeof(RIL_GSM_BroadcastSmsConfigInfo *);
   3755     p.writeInt32(num);
   3756 
   3757     startResponse;
   3758     RIL_GSM_BroadcastSmsConfigInfo **p_cur =
   3759                 (RIL_GSM_BroadcastSmsConfigInfo **) response;
   3760     for (int i = 0; i < num; i++) {
   3761         p.writeInt32(p_cur[i]->fromServiceId);
   3762         p.writeInt32(p_cur[i]->toServiceId);
   3763         p.writeInt32(p_cur[i]->fromCodeScheme);
   3764         p.writeInt32(p_cur[i]->toCodeScheme);
   3765         p.writeInt32(p_cur[i]->selected);
   3766 
   3767         appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId=%d, \
   3768                 fromCodeScheme=%d, toCodeScheme=%d, selected =%d]",
   3769                 printBuf, i, p_cur[i]->fromServiceId, p_cur[i]->toServiceId,
   3770                 p_cur[i]->fromCodeScheme, p_cur[i]->toCodeScheme,
   3771                 p_cur[i]->selected);
   3772     }
   3773     closeResponse;
   3774 
   3775     return 0;
   3776 }
   3777 
   3778 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen) {
   3779     RIL_CDMA_BroadcastSmsConfigInfo **p_cur =
   3780                (RIL_CDMA_BroadcastSmsConfigInfo **) response;
   3781 
   3782     int num = responselen / sizeof (RIL_CDMA_BroadcastSmsConfigInfo *);
   3783     p.writeInt32(num);
   3784 
   3785     startResponse;
   3786     for (int i = 0 ; i < num ; i++ ) {
   3787         p.writeInt32(p_cur[i]->service_category);
   3788         p.writeInt32(p_cur[i]->language);
   3789         p.writeInt32(p_cur[i]->selected);
   3790 
   3791         appendPrintBuf("%s [%d: srvice_category=%d, language =%d, \
   3792               selected =%d], ",
   3793               printBuf, i, p_cur[i]->service_category, p_cur[i]->language,
   3794               p_cur[i]->selected);
   3795     }
   3796     closeResponse;
   3797 
   3798     return 0;
   3799 }
   3800 
   3801 static int responseCdmaSms(Parcel &p, void *response, size_t responselen) {
   3802     int num;
   3803     int digitCount;
   3804     int digitLimit;
   3805     uint8_t uct;
   3806     void* dest;
   3807 
   3808     RLOGD("Inside responseCdmaSms");
   3809 
   3810     if (response == NULL && responselen != 0) {
   3811         RLOGE("invalid response: NULL");
   3812         return RIL_ERRNO_INVALID_RESPONSE;
   3813     }
   3814 
   3815     if (responselen != sizeof(RIL_CDMA_SMS_Message)) {
   3816         RLOGE("invalid response length was %d expected %d",
   3817                 (int)responselen, (int)sizeof(RIL_CDMA_SMS_Message));
   3818         return RIL_ERRNO_INVALID_RESPONSE;
   3819     }
   3820 
   3821     RIL_CDMA_SMS_Message *p_cur = (RIL_CDMA_SMS_Message *) response;
   3822     p.writeInt32(p_cur->uTeleserviceID);
   3823     p.write(&(p_cur->bIsServicePresent),sizeof(uct));
   3824     p.writeInt32(p_cur->uServicecategory);
   3825     p.writeInt32(p_cur->sAddress.digit_mode);
   3826     p.writeInt32(p_cur->sAddress.number_mode);
   3827     p.writeInt32(p_cur->sAddress.number_type);
   3828     p.writeInt32(p_cur->sAddress.number_plan);
   3829     p.write(&(p_cur->sAddress.number_of_digits), sizeof(uct));
   3830     digitLimit= MIN((p_cur->sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
   3831     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
   3832         p.write(&(p_cur->sAddress.digits[digitCount]),sizeof(uct));
   3833     }
   3834 
   3835     p.writeInt32(p_cur->sSubAddress.subaddressType);
   3836     p.write(&(p_cur->sSubAddress.odd),sizeof(uct));
   3837     p.write(&(p_cur->sSubAddress.number_of_digits),sizeof(uct));
   3838     digitLimit= MIN((p_cur->sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
   3839     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
   3840         p.write(&(p_cur->sSubAddress.digits[digitCount]),sizeof(uct));
   3841     }
   3842 
   3843     digitLimit= MIN((p_cur->uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
   3844     p.writeInt32(p_cur->uBearerDataLen);
   3845     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
   3846        p.write(&(p_cur->aBearerData[digitCount]), sizeof(uct));
   3847     }
   3848 
   3849     startResponse;
   3850     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
   3851             sAddress.digit_mode=%d, sAddress.number_mode=%d, sAddress.number_type=%d, ",
   3852             printBuf, p_cur->uTeleserviceID,p_cur->bIsServicePresent,p_cur->uServicecategory,
   3853             p_cur->sAddress.digit_mode, p_cur->sAddress.number_mode,p_cur->sAddress.number_type);
   3854     closeResponse;
   3855 
   3856     return 0;
   3857 }
   3858 
   3859 static int responseDcRtInfo(Parcel &p, void *response, size_t responselen)
   3860 {
   3861     int num = responselen / sizeof(RIL_DcRtInfo);
   3862     if ((responselen % sizeof(RIL_DcRtInfo) != 0) || (num != 1)) {
   3863         RLOGE("responseDcRtInfo: invalid response length %d expected multiple of %d",
   3864                 (int)responselen, (int)sizeof(RIL_DcRtInfo));
   3865         return RIL_ERRNO_INVALID_RESPONSE;
   3866     }
   3867 
   3868     startResponse;
   3869     RIL_DcRtInfo *pDcRtInfo = (RIL_DcRtInfo *)response;
   3870     p.writeInt64(pDcRtInfo->time);
   3871     p.writeInt32(pDcRtInfo->powerState);
   3872     appendPrintBuf("%s[time=%d,powerState=%d]", printBuf,
   3873         pDcRtInfo->time,
   3874         pDcRtInfo->powerState);
   3875     closeResponse;
   3876 
   3877     return 0;
   3878 }
   3879 
   3880 static int responseLceStatus(Parcel &p, void *response, size_t responselen) {
   3881   if (response == NULL || responselen != sizeof(RIL_LceStatusInfo)) {
   3882     if (response == NULL) {
   3883       RLOGE("invalid response: NULL");
   3884     }
   3885     else {
   3886       RLOGE("responseLceStatus: invalid response length %d expecting len: d%",
   3887             sizeof(RIL_LceStatusInfo), responselen);
   3888     }
   3889     return RIL_ERRNO_INVALID_RESPONSE;
   3890   }
   3891 
   3892   RIL_LceStatusInfo *p_cur = (RIL_LceStatusInfo *)response;
   3893   p.write((void *)p_cur, 1);  // p_cur->lce_status takes one byte.
   3894   p.writeInt32(p_cur->actual_interval_ms);
   3895 
   3896   startResponse;
   3897   appendPrintBuf("LCE Status: %d, actual_interval_ms: %d",
   3898                  p_cur->lce_status, p_cur->actual_interval_ms);
   3899   closeResponse;
   3900 
   3901   return 0;
   3902 }
   3903 
   3904 static int responseLceData(Parcel &p, void *response, size_t responselen) {
   3905   if (response == NULL || responselen != sizeof(RIL_LceDataInfo)) {
   3906     if (response == NULL) {
   3907       RLOGE("invalid response: NULL");
   3908     }
   3909     else {
   3910       RLOGE("responseLceData: invalid response length %d expecting len: d%",
   3911             sizeof(RIL_LceDataInfo), responselen);
   3912     }
   3913     return RIL_ERRNO_INVALID_RESPONSE;
   3914   }
   3915 
   3916   RIL_LceDataInfo *p_cur = (RIL_LceDataInfo *)response;
   3917   p.writeInt32(p_cur->last_hop_capacity_kbps);
   3918 
   3919   /* p_cur->confidence_level and p_cur->lce_suspended take 1 byte each.*/
   3920   p.write((void *)&(p_cur->confidence_level), 1);
   3921   p.write((void *)&(p_cur->lce_suspended), 1);
   3922 
   3923   startResponse;
   3924   appendPrintBuf("LCE info received: capacity %d confidence level %d \
   3925                   and suspended %d",
   3926                   p_cur->last_hop_capacity_kbps, p_cur->confidence_level,
   3927                   p_cur->lce_suspended);
   3928   closeResponse;
   3929 
   3930   return 0;
   3931 }
   3932 
   3933 static int responseActivityData(Parcel &p, void *response, size_t responselen) {
   3934   if (response == NULL || responselen != sizeof(RIL_ActivityStatsInfo)) {
   3935     if (response == NULL) {
   3936       RLOGE("invalid response: NULL");
   3937     }
   3938     else {
   3939       RLOGE("responseActivityData: invalid response length %d expecting len: d%",
   3940             sizeof(RIL_ActivityStatsInfo), responselen);
   3941     }
   3942     return RIL_ERRNO_INVALID_RESPONSE;
   3943   }
   3944 
   3945   RIL_ActivityStatsInfo *p_cur = (RIL_ActivityStatsInfo *)response;
   3946   p.writeInt32(p_cur->sleep_mode_time_ms);
   3947   p.writeInt32(p_cur->idle_mode_time_ms);
   3948   for(int i = 0; i < RIL_NUM_TX_POWER_LEVELS; i++) {
   3949     p.writeInt32(p_cur->tx_mode_time_ms[i]);
   3950   }
   3951   p.writeInt32(p_cur->rx_mode_time_ms);
   3952 
   3953   startResponse;
   3954   appendPrintBuf("Modem activity info received: sleep_mode_time_ms %d idle_mode_time_ms %d \
   3955                   tx_mode_time_ms %d %d %d %d %d and rx_mode_time_ms %d",
   3956                   p_cur->sleep_mode_time_ms, p_cur->idle_mode_time_ms, p_cur->tx_mode_time_ms[0],
   3957                   p_cur->tx_mode_time_ms[1], p_cur->tx_mode_time_ms[2], p_cur->tx_mode_time_ms[3],
   3958                   p_cur->tx_mode_time_ms[4], p_cur->rx_mode_time_ms);
   3959    closeResponse;
   3960 
   3961   return 0;
   3962 }
   3963 
   3964 /**
   3965  * A write on the wakeup fd is done just to pop us out of select()
   3966  * We empty the buffer here and then ril_event will reset the timers on the
   3967  * way back down
   3968  */
   3969 static void processWakeupCallback(int fd, short flags, void *param) {
   3970     char buff[16];
   3971     int ret;
   3972 
   3973     RLOGV("processWakeupCallback");
   3974 
   3975     /* empty our wakeup socket out */
   3976     do {
   3977         ret = read(s_fdWakeupRead, &buff, sizeof(buff));
   3978     } while (ret > 0 || (ret < 0 && errno == EINTR));
   3979 }
   3980 
   3981 static void onCommandsSocketClosed(RIL_SOCKET_ID socket_id) {
   3982     int ret;
   3983     RequestInfo *p_cur;
   3984     /* Hook for current context
   3985        pendingRequestsMutextHook refer to &s_pendingRequestsMutex */
   3986     pthread_mutex_t * pendingRequestsMutexHook = &s_pendingRequestsMutex;
   3987     /* pendingRequestsHook refer to &s_pendingRequests */
   3988     RequestInfo **    pendingRequestsHook = &s_pendingRequests;
   3989 
   3990 #if (SIM_COUNT >= 2)
   3991     if (socket_id == RIL_SOCKET_2) {
   3992         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket2;
   3993         pendingRequestsHook = &s_pendingRequests_socket2;
   3994     }
   3995 #if (SIM_COUNT >= 3)
   3996     else if (socket_id == RIL_SOCKET_3) {
   3997         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket3;
   3998         pendingRequestsHook = &s_pendingRequests_socket3;
   3999     }
   4000 #endif
   4001 #if (SIM_COUNT >= 4)
   4002     else if (socket_id == RIL_SOCKET_4) {
   4003         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket4;
   4004         pendingRequestsHook = &s_pendingRequests_socket4;
   4005     }
   4006 #endif
   4007 #endif
   4008     /* mark pending requests as "cancelled" so we dont report responses */
   4009     ret = pthread_mutex_lock(pendingRequestsMutexHook);
   4010     assert (ret == 0);
   4011 
   4012     p_cur = *pendingRequestsHook;
   4013 
   4014     for (p_cur = *pendingRequestsHook
   4015             ; p_cur != NULL
   4016             ; p_cur  = p_cur->p_next
   4017     ) {
   4018         p_cur->cancelled = 1;
   4019     }
   4020 
   4021     ret = pthread_mutex_unlock(pendingRequestsMutexHook);
   4022     assert (ret == 0);
   4023 }
   4024 
   4025 static void processCommandsCallback(int fd, short flags, void *param) {
   4026     RecordStream *p_rs;
   4027     void *p_record;
   4028     size_t recordlen;
   4029     int ret;
   4030     SocketListenParam *p_info = (SocketListenParam *)param;
   4031 
   4032     assert(fd == p_info->fdCommand);
   4033 
   4034     p_rs = p_info->p_rs;
   4035 
   4036     for (;;) {
   4037         /* loop until EAGAIN/EINTR, end of stream, or other error */
   4038         ret = record_stream_get_next(p_rs, &p_record, &recordlen);
   4039 
   4040         if (ret == 0 && p_record == NULL) {
   4041             /* end-of-stream */
   4042             break;
   4043         } else if (ret < 0) {
   4044             break;
   4045         } else if (ret == 0) { /* && p_record != NULL */
   4046             processCommandBuffer(p_record, recordlen, p_info->socket_id);
   4047         }
   4048     }
   4049 
   4050     if (ret == 0 || !(errno == EAGAIN || errno == EINTR)) {
   4051         /* fatal error or end-of-stream */
   4052         if (ret != 0) {
   4053             RLOGE("error on reading command socket errno:%d\n", errno);
   4054         } else {
   4055             RLOGW("EOS.  Closing command socket.");
   4056         }
   4057 
   4058         close(fd);
   4059         p_info->fdCommand = -1;
   4060 
   4061         ril_event_del(p_info->commands_event);
   4062 
   4063         record_stream_free(p_rs);
   4064 
   4065         /* start listening for new connections again */
   4066         rilEventAddWakeup(&s_listen_event);
   4067 
   4068         onCommandsSocketClosed(p_info->socket_id);
   4069     }
   4070 }
   4071 
   4072 
   4073 static void onNewCommandConnect(RIL_SOCKET_ID socket_id) {
   4074     // Inform we are connected and the ril version
   4075     int rilVer = s_callbacks.version;
   4076     RIL_UNSOL_RESPONSE(RIL_UNSOL_RIL_CONNECTED,
   4077                                     &rilVer, sizeof(rilVer), socket_id);
   4078 
   4079     // implicit radio state changed
   4080     RIL_UNSOL_RESPONSE(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
   4081                                     NULL, 0, socket_id);
   4082 
   4083     // Send last NITZ time data, in case it was missed
   4084     if (s_lastNITZTimeData != NULL) {
   4085         sendResponseRaw(s_lastNITZTimeData, s_lastNITZTimeDataSize, socket_id);
   4086 
   4087         free(s_lastNITZTimeData);
   4088         s_lastNITZTimeData = NULL;
   4089     }
   4090 
   4091     // Get version string
   4092     if (s_callbacks.getVersion != NULL) {
   4093         const char *version;
   4094         version = s_callbacks.getVersion();
   4095         RLOGI("RIL Daemon version: %s\n", version);
   4096 
   4097         property_set(PROPERTY_RIL_IMPL, version);
   4098     } else {
   4099         RLOGI("RIL Daemon version: unavailable\n");
   4100         property_set(PROPERTY_RIL_IMPL, "unavailable");
   4101     }
   4102 
   4103 }
   4104 
   4105 static void listenCallback (int fd, short flags, void *param) {
   4106     int ret;
   4107     int err;
   4108     int is_phone_socket;
   4109     int fdCommand = -1;
   4110     char* processName;
   4111     RecordStream *p_rs;
   4112     MySocketListenParam* listenParam;
   4113     RilSocket *sapSocket = NULL;
   4114     socketClient *sClient = NULL;
   4115 
   4116     SocketListenParam *p_info = (SocketListenParam *)param;
   4117 
   4118     if(RIL_SAP_SOCKET == p_info->type) {
   4119         listenParam = (MySocketListenParam *)param;
   4120         sapSocket = listenParam->socket;
   4121     }
   4122 
   4123     struct sockaddr_un peeraddr;
   4124     socklen_t socklen = sizeof (peeraddr);
   4125 
   4126     struct ucred creds;
   4127     socklen_t szCreds = sizeof(creds);
   4128 
   4129     struct passwd *pwd = NULL;
   4130 
   4131     if(NULL == sapSocket) {
   4132         assert (*p_info->fdCommand < 0);
   4133         assert (fd == *p_info->fdListen);
   4134         processName = PHONE_PROCESS;
   4135     } else {
   4136         assert (sapSocket->commandFd < 0);
   4137         assert (fd == sapSocket->listenFd);
   4138         processName = BLUETOOTH_PROCESS;
   4139     }
   4140 
   4141 
   4142     fdCommand = accept(fd, (sockaddr *) &peeraddr, &socklen);
   4143 
   4144     if (fdCommand < 0 ) {
   4145         RLOGE("Error on accept() errno:%d", errno);
   4146         /* start listening for new connections again */
   4147         if(NULL == sapSocket) {
   4148             rilEventAddWakeup(p_info->listen_event);
   4149         } else {
   4150             rilEventAddWakeup(sapSocket->getListenEvent());
   4151         }
   4152         return;
   4153     }
   4154 
   4155     /* check the credential of the other side and only accept socket from
   4156      * phone process
   4157      */
   4158     errno = 0;
   4159     is_phone_socket = 0;
   4160 
   4161     err = getsockopt(fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
   4162 
   4163     if (err == 0 && szCreds > 0) {
   4164         errno = 0;
   4165         pwd = getpwuid(creds.uid);
   4166         if (pwd != NULL) {
   4167             if (strcmp(pwd->pw_name, processName) == 0) {
   4168                 is_phone_socket = 1;
   4169             } else {
   4170                 RLOGE("RILD can't accept socket from process %s", pwd->pw_name);
   4171             }
   4172         } else {
   4173             RLOGE("Error on getpwuid() errno: %d", errno);
   4174         }
   4175     } else {
   4176         RLOGD("Error on getsockopt() errno: %d", errno);
   4177     }
   4178 
   4179     if (!is_phone_socket) {
   4180         RLOGE("RILD must accept socket from %s", processName);
   4181 
   4182         close(fdCommand);
   4183         fdCommand = -1;
   4184 
   4185         if(NULL == sapSocket) {
   4186             onCommandsSocketClosed(p_info->socket_id);
   4187 
   4188             /* start listening for new connections again */
   4189             rilEventAddWakeup(p_info->listen_event);
   4190         } else {
   4191             sapSocket->onCommandsSocketClosed();
   4192 
   4193             /* start listening for new connections again */
   4194             rilEventAddWakeup(sapSocket->getListenEvent());
   4195         }
   4196 
   4197         return;
   4198     }
   4199 
   4200     ret = fcntl(fdCommand, F_SETFL, O_NONBLOCK);
   4201 
   4202     if (ret < 0) {
   4203         RLOGE ("Error setting O_NONBLOCK errno:%d", errno);
   4204     }
   4205 
   4206     if(NULL == sapSocket) {
   4207         RLOGI("libril: new connection to %s", rilSocketIdToString(p_info->socket_id));
   4208 
   4209         p_info->fdCommand = fdCommand;
   4210         p_rs = record_stream_new(p_info->fdCommand, MAX_COMMAND_BYTES);
   4211         p_info->p_rs = p_rs;
   4212 
   4213         ril_event_set (p_info->commands_event, p_info->fdCommand, 1,
   4214         p_info->processCommandsCallback, p_info);
   4215         rilEventAddWakeup (p_info->commands_event);
   4216 
   4217         onNewCommandConnect(p_info->socket_id);
   4218     } else {
   4219         RLOGI("libril: new connection");
   4220 
   4221         sapSocket->setCommandFd(fdCommand);
   4222         p_rs = record_stream_new(sapSocket->getCommandFd(), MAX_COMMAND_BYTES);
   4223         sClient = new socketClient(sapSocket,p_rs);
   4224         ril_event_set (sapSocket->getCallbackEvent(), sapSocket->getCommandFd(), 1,
   4225         sapSocket->getCommandCb(), sClient);
   4226 
   4227         rilEventAddWakeup(sapSocket->getCallbackEvent());
   4228         sapSocket->onNewCommandConnect();
   4229     }
   4230 }
   4231 
   4232 static void freeDebugCallbackArgs(int number, char **args) {
   4233     for (int i = 0; i < number; i++) {
   4234         if (args[i] != NULL) {
   4235             free(args[i]);
   4236         }
   4237     }
   4238     free(args);
   4239 }
   4240 
   4241 static void debugCallback (int fd, short flags, void *param) {
   4242     int acceptFD, option;
   4243     struct sockaddr_un peeraddr;
   4244     socklen_t socklen = sizeof (peeraddr);
   4245     int data;
   4246     unsigned int qxdm_data[6];
   4247     const char *deactData[1] = {"1"};
   4248     char *actData[1];
   4249     RIL_Dial dialData;
   4250     int hangupData[1] = {1};
   4251     int number;
   4252     char **args;
   4253     RIL_SOCKET_ID socket_id = RIL_SOCKET_1;
   4254     int sim_id = 0;
   4255 
   4256     RLOGI("debugCallback for socket %s", rilSocketIdToString(socket_id));
   4257 
   4258     acceptFD = accept (fd,  (sockaddr *) &peeraddr, &socklen);
   4259 
   4260     if (acceptFD < 0) {
   4261         RLOGE ("error accepting on debug port: %d\n", errno);
   4262         return;
   4263     }
   4264 
   4265     if (recv(acceptFD, &number, sizeof(int), 0) != sizeof(int)) {
   4266         RLOGE ("error reading on socket: number of Args: \n");
   4267         close(acceptFD);
   4268         return;
   4269     }
   4270 
   4271     if (number < 0) {
   4272         RLOGE ("Invalid number of arguments: \n");
   4273         close(acceptFD);
   4274         return;
   4275     }
   4276 
   4277     args = (char **) calloc(number, sizeof(char*));
   4278     if (args == NULL) {
   4279         RLOGE("Memory allocation failed for debug args");
   4280         close(acceptFD);
   4281         return;
   4282     }
   4283 
   4284     for (int i = 0; i < number; i++) {
   4285         int len;
   4286         if (recv(acceptFD, &len, sizeof(int), 0) != sizeof(int)) {
   4287             RLOGE ("error reading on socket: Len of Args: \n");
   4288             freeDebugCallbackArgs(i, args);
   4289             close(acceptFD);
   4290             return;
   4291         }
   4292         if (len == INT_MAX || len < 0) {
   4293             RLOGE("Invalid value of len: \n");
   4294             freeDebugCallbackArgs(i, args);
   4295             close(acceptFD);
   4296             return;
   4297         }
   4298 
   4299         // +1 for null-term
   4300         args[i] = (char *) calloc(len + 1, sizeof(char));
   4301         if (args[i] == NULL) {
   4302             RLOGE("Memory allocation failed for debug args");
   4303             freeDebugCallbackArgs(i, args);
   4304             close(acceptFD);
   4305             return;
   4306         }
   4307         if (recv(acceptFD, args[i], sizeof(char) * len, 0)
   4308             != (int)sizeof(char) * len) {
   4309             RLOGE ("error reading on socket: Args[%d] \n", i);
   4310             freeDebugCallbackArgs(i, args);
   4311             close(acceptFD);
   4312             return;
   4313         }
   4314         char * buf = args[i];
   4315         buf[len] = 0;
   4316         if ((i+1) == number) {
   4317             /* The last argument should be sim id 0(SIM1)~3(SIM4) */
   4318             sim_id = atoi(args[i]);
   4319             switch (sim_id) {
   4320                 case 0:
   4321                     socket_id = RIL_SOCKET_1;
   4322                     break;
   4323             #if (SIM_COUNT >= 2)
   4324                 case 1:
   4325                     socket_id = RIL_SOCKET_2;
   4326                     break;
   4327             #endif
   4328             #if (SIM_COUNT >= 3)
   4329                 case 2:
   4330                     socket_id = RIL_SOCKET_3;
   4331                     break;
   4332             #endif
   4333             #if (SIM_COUNT >= 4)
   4334                 case 3:
   4335                     socket_id = RIL_SOCKET_4;
   4336                     break;
   4337             #endif
   4338                 default:
   4339                     socket_id = RIL_SOCKET_1;
   4340                     break;
   4341             }
   4342         }
   4343     }
   4344 
   4345     switch (atoi(args[0])) {
   4346         case 0:
   4347             RLOGI ("Connection on debug port: issuing reset.");
   4348             issueLocalRequest(RIL_REQUEST_RESET_RADIO, NULL, 0, socket_id);
   4349             break;
   4350         case 1:
   4351             RLOGI ("Connection on debug port: issuing radio power off.");
   4352             data = 0;
   4353             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int), socket_id);
   4354             // Close the socket
   4355             if (socket_id == RIL_SOCKET_1 && s_ril_param_socket.fdCommand > 0) {
   4356                 close(s_ril_param_socket.fdCommand);
   4357                 s_ril_param_socket.fdCommand = -1;
   4358             }
   4359         #if (SIM_COUNT == 2)
   4360             else if (socket_id == RIL_SOCKET_2 && s_ril_param_socket2.fdCommand > 0) {
   4361                 close(s_ril_param_socket2.fdCommand);
   4362                 s_ril_param_socket2.fdCommand = -1;
   4363             }
   4364         #endif
   4365             break;
   4366         case 2:
   4367             RLOGI ("Debug port: issuing unsolicited voice network change.");
   4368             RIL_UNSOL_RESPONSE(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED, NULL, 0, socket_id);
   4369             break;
   4370         case 3:
   4371             RLOGI ("Debug port: QXDM log enable.");
   4372             qxdm_data[0] = 65536;     // head.func_tag
   4373             qxdm_data[1] = 16;        // head.len
   4374             qxdm_data[2] = 1;         // mode: 1 for 'start logging'
   4375             qxdm_data[3] = 32;        // log_file_size: 32megabytes
   4376             qxdm_data[4] = 0;         // log_mask
   4377             qxdm_data[5] = 8;         // log_max_fileindex
   4378             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
   4379                               6 * sizeof(int), socket_id);
   4380             break;
   4381         case 4:
   4382             RLOGI ("Debug port: QXDM log disable.");
   4383             qxdm_data[0] = 65536;
   4384             qxdm_data[1] = 16;
   4385             qxdm_data[2] = 0;          // mode: 0 for 'stop logging'
   4386             qxdm_data[3] = 32;
   4387             qxdm_data[4] = 0;
   4388             qxdm_data[5] = 8;
   4389             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
   4390                               6 * sizeof(int), socket_id);
   4391             break;
   4392         case 5:
   4393             RLOGI("Debug port: Radio On");
   4394             data = 1;
   4395             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int), socket_id);
   4396             sleep(2);
   4397             // Set network selection automatic.
   4398             issueLocalRequest(RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, NULL, 0, socket_id);
   4399             break;
   4400         case 6:
   4401             RLOGI("Debug port: Setup Data Call, Apn :%s\n", args[1]);
   4402             actData[0] = args[1];
   4403             issueLocalRequest(RIL_REQUEST_SETUP_DATA_CALL, &actData,
   4404                               sizeof(actData), socket_id);
   4405             break;
   4406         case 7:
   4407             RLOGI("Debug port: Deactivate Data Call");
   4408             issueLocalRequest(RIL_REQUEST_DEACTIVATE_DATA_CALL, &deactData,
   4409                               sizeof(deactData), socket_id);
   4410             break;
   4411         case 8:
   4412             RLOGI("Debug port: Dial Call");
   4413             dialData.clir = 0;
   4414             dialData.address = args[1];
   4415             issueLocalRequest(RIL_REQUEST_DIAL, &dialData, sizeof(dialData), socket_id);
   4416             break;
   4417         case 9:
   4418             RLOGI("Debug port: Answer Call");
   4419             issueLocalRequest(RIL_REQUEST_ANSWER, NULL, 0, socket_id);
   4420             break;
   4421         case 10:
   4422             RLOGI("Debug port: End Call");
   4423             issueLocalRequest(RIL_REQUEST_HANGUP, &hangupData,
   4424                               sizeof(hangupData), socket_id);
   4425             break;
   4426         default:
   4427             RLOGE ("Invalid request");
   4428             break;
   4429     }
   4430     freeDebugCallbackArgs(number, args);
   4431     close(acceptFD);
   4432 }
   4433 
   4434 
   4435 static void userTimerCallback (int fd, short flags, void *param) {
   4436     UserCallbackInfo *p_info;
   4437 
   4438     p_info = (UserCallbackInfo *)param;
   4439 
   4440     p_info->p_callback(p_info->userParam);
   4441 
   4442 
   4443     // FIXME generalize this...there should be a cancel mechanism
   4444     if (s_last_wake_timeout_info != NULL && s_last_wake_timeout_info == p_info) {
   4445         s_last_wake_timeout_info = NULL;
   4446     }
   4447 
   4448     free(p_info);
   4449 }
   4450 
   4451 
   4452 static void *
   4453 eventLoop(void *param) {
   4454     int ret;
   4455     int filedes[2];
   4456 
   4457     ril_event_init();
   4458 
   4459     pthread_mutex_lock(&s_startupMutex);
   4460 
   4461     s_started = 1;
   4462     pthread_cond_broadcast(&s_startupCond);
   4463 
   4464     pthread_mutex_unlock(&s_startupMutex);
   4465 
   4466     ret = pipe(filedes);
   4467 
   4468     if (ret < 0) {
   4469         RLOGE("Error in pipe() errno:%d", errno);
   4470         return NULL;
   4471     }
   4472 
   4473     s_fdWakeupRead = filedes[0];
   4474     s_fdWakeupWrite = filedes[1];
   4475 
   4476     fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
   4477 
   4478     ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
   4479                 processWakeupCallback, NULL);
   4480 
   4481     rilEventAddWakeup (&s_wakeupfd_event);
   4482 
   4483     // Only returns on error
   4484     ril_event_loop();
   4485     RLOGE ("error in event_loop_base errno:%d", errno);
   4486     // kill self to restart on error
   4487     kill(0, SIGKILL);
   4488 
   4489     return NULL;
   4490 }
   4491 
   4492 extern "C" void
   4493 RIL_startEventLoop(void) {
   4494     /* spin up eventLoop thread and wait for it to get started */
   4495     s_started = 0;
   4496     pthread_mutex_lock(&s_startupMutex);
   4497 
   4498     pthread_attr_t attr;
   4499     pthread_attr_init(&attr);
   4500     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
   4501 
   4502     int result = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL);
   4503     if (result != 0) {
   4504         RLOGE("Failed to create dispatch thread: %s", strerror(result));
   4505         goto done;
   4506     }
   4507 
   4508     while (s_started == 0) {
   4509         pthread_cond_wait(&s_startupCond, &s_startupMutex);
   4510     }
   4511 
   4512 done:
   4513     pthread_mutex_unlock(&s_startupMutex);
   4514 }
   4515 
   4516 // Used for testing purpose only.
   4517 extern "C" void RIL_setcallbacks (const RIL_RadioFunctions *callbacks) {
   4518     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
   4519 }
   4520 
   4521 static void startListen(RIL_SOCKET_ID socket_id, SocketListenParam* socket_listen_p) {
   4522     int fdListen = -1;
   4523     int ret;
   4524     char socket_name[10];
   4525 
   4526     memset(socket_name, 0, sizeof(char)*10);
   4527 
   4528     switch(socket_id) {
   4529         case RIL_SOCKET_1:
   4530             strncpy(socket_name, RIL_getRilSocketName(), 9);
   4531             break;
   4532     #if (SIM_COUNT >= 2)
   4533         case RIL_SOCKET_2:
   4534             strncpy(socket_name, SOCKET2_NAME_RIL, 9);
   4535             break;
   4536     #endif
   4537     #if (SIM_COUNT >= 3)
   4538         case RIL_SOCKET_3:
   4539             strncpy(socket_name, SOCKET3_NAME_RIL, 9);
   4540             break;
   4541     #endif
   4542     #if (SIM_COUNT >= 4)
   4543         case RIL_SOCKET_4:
   4544             strncpy(socket_name, SOCKET4_NAME_RIL, 9);
   4545             break;
   4546     #endif
   4547         default:
   4548             RLOGE("Socket id is wrong!!");
   4549             return;
   4550     }
   4551 
   4552     RLOGI("Start to listen %s", rilSocketIdToString(socket_id));
   4553 
   4554     fdListen = android_get_control_socket(socket_name);
   4555     if (fdListen < 0) {
   4556         RLOGE("Failed to get socket %s", socket_name);
   4557         exit(-1);
   4558     }
   4559 
   4560     ret = listen(fdListen, 4);
   4561 
   4562     if (ret < 0) {
   4563         RLOGE("Failed to listen on control socket '%d': %s",
   4564              fdListen, strerror(errno));
   4565         exit(-1);
   4566     }
   4567     socket_listen_p->fdListen = fdListen;
   4568 
   4569     /* note: non-persistent so we can accept only one connection at a time */
   4570     ril_event_set (socket_listen_p->listen_event, fdListen, false,
   4571                 listenCallback, socket_listen_p);
   4572 
   4573     rilEventAddWakeup (socket_listen_p->listen_event);
   4574 }
   4575 
   4576 extern "C" void
   4577 RIL_register (const RIL_RadioFunctions *callbacks) {
   4578     int ret;
   4579     int flags;
   4580 
   4581     RLOGI("SIM_COUNT: %d", SIM_COUNT);
   4582 
   4583     if (callbacks == NULL) {
   4584         RLOGE("RIL_register: RIL_RadioFunctions * null");
   4585         return;
   4586     }
   4587     if (callbacks->version < RIL_VERSION_MIN) {
   4588         RLOGE("RIL_register: version %d is to old, min version is %d",
   4589              callbacks->version, RIL_VERSION_MIN);
   4590         return;
   4591     }
   4592 
   4593     RLOGE("RIL_register: RIL version %d", callbacks->version);
   4594 
   4595     if (s_registerCalled > 0) {
   4596         RLOGE("RIL_register has been called more than once. "
   4597                 "Subsequent call ignored");
   4598         return;
   4599     }
   4600 
   4601     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
   4602 
   4603     /* Initialize socket1 parameters */
   4604     s_ril_param_socket = {
   4605                         RIL_SOCKET_1,             /* socket_id */
   4606                         -1,                       /* fdListen */
   4607                         -1,                       /* fdCommand */
   4608                         PHONE_PROCESS,            /* processName */
   4609                         &s_commands_event,        /* commands_event */
   4610                         &s_listen_event,          /* listen_event */
   4611                         processCommandsCallback,  /* processCommandsCallback */
   4612                         NULL                      /* p_rs */
   4613                         };
   4614 
   4615 #if (SIM_COUNT >= 2)
   4616     s_ril_param_socket2 = {
   4617                         RIL_SOCKET_2,               /* socket_id */
   4618                         -1,                         /* fdListen */
   4619                         -1,                         /* fdCommand */
   4620                         PHONE_PROCESS,              /* processName */
   4621                         &s_commands_event_socket2,  /* commands_event */
   4622                         &s_listen_event_socket2,    /* listen_event */
   4623                         processCommandsCallback,    /* processCommandsCallback */
   4624                         NULL                        /* p_rs */
   4625                         };
   4626 #endif
   4627 
   4628 #if (SIM_COUNT >= 3)
   4629     s_ril_param_socket3 = {
   4630                         RIL_SOCKET_3,               /* socket_id */
   4631                         -1,                         /* fdListen */
   4632                         -1,                         /* fdCommand */
   4633                         PHONE_PROCESS,              /* processName */
   4634                         &s_commands_event_socket3,  /* commands_event */
   4635                         &s_listen_event_socket3,    /* listen_event */
   4636                         processCommandsCallback,    /* processCommandsCallback */
   4637                         NULL                        /* p_rs */
   4638                         };
   4639 #endif
   4640 
   4641 #if (SIM_COUNT >= 4)
   4642     s_ril_param_socket4 = {
   4643                         RIL_SOCKET_4,               /* socket_id */
   4644                         -1,                         /* fdListen */
   4645                         -1,                         /* fdCommand */
   4646                         PHONE_PROCESS,              /* processName */
   4647                         &s_commands_event_socket4,  /* commands_event */
   4648                         &s_listen_event_socket4,    /* listen_event */
   4649                         processCommandsCallback,    /* processCommandsCallback */
   4650                         NULL                        /* p_rs */
   4651                         };
   4652 #endif
   4653 
   4654 
   4655     s_registerCalled = 1;
   4656 
   4657     RLOGI("s_registerCalled flag set, %d", s_started);
   4658     // Little self-check
   4659 
   4660     for (int i = 0; i < (int)NUM_ELEMS(s_commands); i++) {
   4661         assert(i == s_commands[i].requestNumber);
   4662     }
   4663 
   4664     for (int i = 0; i < (int)NUM_ELEMS(s_unsolResponses); i++) {
   4665         assert(i + RIL_UNSOL_RESPONSE_BASE
   4666                 == s_unsolResponses[i].requestNumber);
   4667     }
   4668 
   4669     // New rild impl calls RIL_startEventLoop() first
   4670     // old standalone impl wants it here.
   4671 
   4672     if (s_started == 0) {
   4673         RIL_startEventLoop();
   4674     }
   4675 
   4676     // start listen socket1
   4677     startListen(RIL_SOCKET_1, &s_ril_param_socket);
   4678 
   4679 #if (SIM_COUNT >= 2)
   4680     // start listen socket2
   4681     startListen(RIL_SOCKET_2, &s_ril_param_socket2);
   4682 #endif /* (SIM_COUNT == 2) */
   4683 
   4684 #if (SIM_COUNT >= 3)
   4685     // start listen socket3
   4686     startListen(RIL_SOCKET_3, &s_ril_param_socket3);
   4687 #endif /* (SIM_COUNT == 3) */
   4688 
   4689 #if (SIM_COUNT >= 4)
   4690     // start listen socket4
   4691     startListen(RIL_SOCKET_4, &s_ril_param_socket4);
   4692 #endif /* (SIM_COUNT == 4) */
   4693 
   4694 
   4695 #if 1
   4696     // start debug interface socket
   4697 
   4698     char *inst = NULL;
   4699     if (strlen(RIL_getRilSocketName()) >= strlen(SOCKET_NAME_RIL)) {
   4700         inst = RIL_getRilSocketName() + strlen(SOCKET_NAME_RIL);
   4701     }
   4702 
   4703     char rildebug[MAX_DEBUG_SOCKET_NAME_LENGTH] = SOCKET_NAME_RIL_DEBUG;
   4704     if (inst != NULL) {
   4705         strlcat(rildebug, inst, MAX_DEBUG_SOCKET_NAME_LENGTH);
   4706     }
   4707 
   4708     s_fdDebug = android_get_control_socket(rildebug);
   4709     if (s_fdDebug < 0) {
   4710         RLOGE("Failed to get socket : %s errno:%d", rildebug, errno);
   4711         exit(-1);
   4712     }
   4713 
   4714     ret = listen(s_fdDebug, 4);
   4715 
   4716     if (ret < 0) {
   4717         RLOGE("Failed to listen on ril debug socket '%d': %s",
   4718              s_fdDebug, strerror(errno));
   4719         exit(-1);
   4720     }
   4721 
   4722     ril_event_set (&s_debug_event, s_fdDebug, true,
   4723                 debugCallback, NULL);
   4724 
   4725     rilEventAddWakeup (&s_debug_event);
   4726 #endif
   4727 
   4728 }
   4729 
   4730 extern "C" void
   4731 RIL_register_socket (RIL_RadioFunctions *(*Init)(const struct RIL_Env *, int, char **),RIL_SOCKET_TYPE socketType, int argc, char **argv) {
   4732 
   4733     RIL_RadioFunctions* UimFuncs = NULL;
   4734 
   4735     if(Init) {
   4736         UimFuncs = Init(&RilSapSocket::uimRilEnv, argc, argv);
   4737 
   4738         switch(socketType) {
   4739             case RIL_SAP_SOCKET:
   4740                 RilSapSocket::initSapSocket("sap_uim_socket1", UimFuncs);
   4741 
   4742 #if (SIM_COUNT >= 2)
   4743                 RilSapSocket::initSapSocket("sap_uim_socket2", UimFuncs);
   4744 #endif
   4745 
   4746 #if (SIM_COUNT >= 3)
   4747                 RilSapSocket::initSapSocket("sap_uim_socket3", UimFuncs);
   4748 #endif
   4749 
   4750 #if (SIM_COUNT >= 4)
   4751                 RilSapSocket::initSapSocket("sap_uim_socket4", UimFuncs);
   4752 #endif
   4753         }
   4754     }
   4755 }
   4756 
   4757 // Check and remove RequestInfo if its a response and not just ack sent back
   4758 static int
   4759 checkAndDequeueRequestInfoIfAck(struct RequestInfo *pRI, bool isAck) {
   4760     int ret = 0;
   4761     /* Hook for current context
   4762        pendingRequestsMutextHook refer to &s_pendingRequestsMutex */
   4763     pthread_mutex_t* pendingRequestsMutexHook = &s_pendingRequestsMutex;
   4764     /* pendingRequestsHook refer to &s_pendingRequests */
   4765     RequestInfo ** pendingRequestsHook = &s_pendingRequests;
   4766 
   4767     if (pRI == NULL) {
   4768         return 0;
   4769     }
   4770 
   4771 #if (SIM_COUNT >= 2)
   4772     if (pRI->socket_id == RIL_SOCKET_2) {
   4773         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket2;
   4774         pendingRequestsHook = &s_pendingRequests_socket2;
   4775     }
   4776 #if (SIM_COUNT >= 3)
   4777         if (pRI->socket_id == RIL_SOCKET_3) {
   4778             pendingRequestsMutexHook = &s_pendingRequestsMutex_socket3;
   4779             pendingRequestsHook = &s_pendingRequests_socket3;
   4780         }
   4781 #endif
   4782 #if (SIM_COUNT >= 4)
   4783     if (pRI->socket_id == RIL_SOCKET_4) {
   4784         pendingRequestsMutexHook = &s_pendingRequestsMutex_socket4;
   4785         pendingRequestsHook = &s_pendingRequests_socket4;
   4786     }
   4787 #endif
   4788 #endif
   4789     pthread_mutex_lock(pendingRequestsMutexHook);
   4790 
   4791     for(RequestInfo **ppCur = pendingRequestsHook
   4792         ; *ppCur != NULL
   4793         ; ppCur = &((*ppCur)->p_next)
   4794     ) {
   4795         if (pRI == *ppCur) {
   4796             ret = 1;
   4797             if (isAck) { // Async ack
   4798                 if (pRI->wasAckSent == 1) {
   4799                     RLOGD("Ack was already sent for %s", requestToString(pRI->pCI->requestNumber));
   4800                 } else {
   4801                     pRI->wasAckSent = 1;
   4802                 }
   4803             } else {
   4804                 *ppCur = (*ppCur)->p_next;
   4805             }
   4806             break;
   4807         }
   4808     }
   4809 
   4810     pthread_mutex_unlock(pendingRequestsMutexHook);
   4811 
   4812     return ret;
   4813 }
   4814 
   4815 static int findFd(int socket_id) {
   4816     int fd = s_ril_param_socket.fdCommand;
   4817 #if (SIM_COUNT >= 2)
   4818     if (socket_id == RIL_SOCKET_2) {
   4819         fd = s_ril_param_socket2.fdCommand;
   4820     }
   4821 #if (SIM_COUNT >= 3)
   4822     if (socket_id == RIL_SOCKET_3) {
   4823         fd = s_ril_param_socket3.fdCommand;
   4824     }
   4825 #endif
   4826 #if (SIM_COUNT >= 4)
   4827     if (socket_id == RIL_SOCKET_4) {
   4828         fd = s_ril_param_socket4.fdCommand;
   4829     }
   4830 #endif
   4831 #endif
   4832     return fd;
   4833 }
   4834 
   4835 extern "C" void
   4836 RIL_onRequestAck(RIL_Token t) {
   4837     RequestInfo *pRI;
   4838     int ret, fd;
   4839 
   4840     size_t errorOffset;
   4841     RIL_SOCKET_ID socket_id = RIL_SOCKET_1;
   4842 
   4843     pRI = (RequestInfo *)t;
   4844 
   4845     if (!checkAndDequeueRequestInfoIfAck(pRI, true)) {
   4846         RLOGE ("RIL_onRequestAck: invalid RIL_Token");
   4847         return;
   4848     }
   4849 
   4850     socket_id = pRI->socket_id;
   4851     fd = findFd(socket_id);
   4852 
   4853 #if VDBG
   4854     RLOGD("Request Ack, %s", rilSocketIdToString(socket_id));
   4855 #endif
   4856 
   4857     appendPrintBuf("Ack [%04d]< %s", pRI->token, requestToString(pRI->pCI->requestNumber));
   4858 
   4859     if (pRI->cancelled == 0) {
   4860         Parcel p;
   4861 
   4862         p.writeInt32 (RESPONSE_SOLICITED_ACK);
   4863         p.writeInt32 (pRI->token);
   4864 
   4865         if (fd < 0) {
   4866             RLOGD ("RIL onRequestComplete: Command channel closed");
   4867         }
   4868 
   4869         sendResponse(p, socket_id);
   4870     }
   4871 }
   4872 
   4873 extern "C" void
   4874 RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen) {
   4875     RequestInfo *pRI;
   4876     int ret;
   4877     int fd;
   4878     size_t errorOffset;
   4879     RIL_SOCKET_ID socket_id = RIL_SOCKET_1;
   4880 
   4881     pRI = (RequestInfo *)t;
   4882 
   4883     if (!checkAndDequeueRequestInfoIfAck(pRI, false)) {
   4884         RLOGE ("RIL_onRequestComplete: invalid RIL_Token");
   4885         return;
   4886     }
   4887 
   4888     socket_id = pRI->socket_id;
   4889     fd = findFd(socket_id);
   4890 
   4891 #if VDBG
   4892     RLOGD("RequestComplete, %s", rilSocketIdToString(socket_id));
   4893 #endif
   4894 
   4895     if (pRI->local > 0) {
   4896         // Locally issued command...void only!
   4897         // response does not go back up the command socket
   4898         RLOGD("C[locl]< %s", requestToString(pRI->pCI->requestNumber));
   4899 
   4900         goto done;
   4901     }
   4902 
   4903     appendPrintBuf("[%04d]< %s",
   4904         pRI->token, requestToString(pRI->pCI->requestNumber));
   4905 
   4906     if (pRI->cancelled == 0) {
   4907         Parcel p;
   4908 
   4909         if (s_callbacks.version >= 13 && pRI->wasAckSent == 1) {
   4910             // If ack was already sent, then this call is an asynchronous response. So we need to
   4911             // send id indicating that we expect an ack from RIL.java as we acquire wakelock here.
   4912             p.writeInt32 (RESPONSE_SOLICITED_ACK_EXP);
   4913             grabPartialWakeLock();
   4914         } else {
   4915             p.writeInt32 (RESPONSE_SOLICITED);
   4916         }
   4917         p.writeInt32 (pRI->token);
   4918         errorOffset = p.dataPosition();
   4919 
   4920         p.writeInt32 (e);
   4921 
   4922         if (response != NULL) {
   4923             // there is a response payload, no matter success or not.
   4924             ret = pRI->pCI->responseFunction(p, response, responselen);
   4925 
   4926             /* if an error occurred, rewind and mark it */
   4927             if (ret != 0) {
   4928                 RLOGE ("responseFunction error, ret %d", ret);
   4929                 p.setDataPosition(errorOffset);
   4930                 p.writeInt32 (ret);
   4931             }
   4932         }
   4933 
   4934         if (e != RIL_E_SUCCESS) {
   4935             appendPrintBuf("%s fails by %s", printBuf, failCauseToString(e));
   4936         }
   4937 
   4938         if (fd < 0) {
   4939             RLOGD ("RIL onRequestComplete: Command channel closed");
   4940         }
   4941         sendResponse(p, socket_id);
   4942     }
   4943 
   4944 done:
   4945     free(pRI);
   4946 }
   4947 
   4948 static void
   4949 grabPartialWakeLock() {
   4950     if (s_callbacks.version >= 13) {
   4951         int ret;
   4952         ret = pthread_mutex_lock(&s_wakeLockCountMutex);
   4953         assert(ret == 0);
   4954         acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
   4955 
   4956         UserCallbackInfo *p_info =
   4957                 internalRequestTimedCallback(wakeTimeoutCallback, NULL, &TIMEVAL_WAKE_TIMEOUT);
   4958         if (p_info == NULL) {
   4959             release_wake_lock(ANDROID_WAKE_LOCK_NAME);
   4960         } else {
   4961             s_wakelock_count++;
   4962             if (s_last_wake_timeout_info != NULL) {
   4963                 s_last_wake_timeout_info->userParam = (void *)1;
   4964             }
   4965             s_last_wake_timeout_info = p_info;
   4966         }
   4967         ret = pthread_mutex_unlock(&s_wakeLockCountMutex);
   4968         assert(ret == 0);
   4969     } else {
   4970         acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
   4971     }
   4972 }
   4973 
   4974 static void
   4975 releaseWakeLock() {
   4976     if (s_callbacks.version >= 13) {
   4977         int ret;
   4978         ret = pthread_mutex_lock(&s_wakeLockCountMutex);
   4979         assert(ret == 0);
   4980 
   4981         if (s_wakelock_count > 1) {
   4982             s_wakelock_count--;
   4983         } else {
   4984             s_wakelock_count = 0;
   4985             release_wake_lock(ANDROID_WAKE_LOCK_NAME);
   4986             if (s_last_wake_timeout_info != NULL) {
   4987                 s_last_wake_timeout_info->userParam = (void *)1;
   4988             }
   4989         }
   4990 
   4991         ret = pthread_mutex_unlock(&s_wakeLockCountMutex);
   4992         assert(ret == 0);
   4993     } else {
   4994         release_wake_lock(ANDROID_WAKE_LOCK_NAME);
   4995     }
   4996 }
   4997 
   4998 /**
   4999  * Timer callback to put us back to sleep before the default timeout
   5000  */
   5001 static void
   5002 wakeTimeoutCallback (void *param) {
   5003     // We're using "param != NULL" as a cancellation mechanism
   5004     if (s_callbacks.version >= 13) {
   5005         if (param == NULL) {
   5006             int ret;
   5007             ret = pthread_mutex_lock(&s_wakeLockCountMutex);
   5008             assert(ret == 0);
   5009             s_wakelock_count = 0;
   5010             release_wake_lock(ANDROID_WAKE_LOCK_NAME);
   5011             ret = pthread_mutex_unlock(&s_wakeLockCountMutex);
   5012             assert(ret == 0);
   5013         }
   5014     } else {
   5015         if (param == NULL) {
   5016             releaseWakeLock();
   5017         }
   5018     }
   5019 }
   5020 
   5021 static int
   5022 decodeVoiceRadioTechnology (RIL_RadioState radioState) {
   5023     switch (radioState) {
   5024         case RADIO_STATE_SIM_NOT_READY:
   5025         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
   5026         case RADIO_STATE_SIM_READY:
   5027             return RADIO_TECH_UMTS;
   5028 
   5029         case RADIO_STATE_RUIM_NOT_READY:
   5030         case RADIO_STATE_RUIM_READY:
   5031         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
   5032         case RADIO_STATE_NV_NOT_READY:
   5033         case RADIO_STATE_NV_READY:
   5034             return RADIO_TECH_1xRTT;
   5035 
   5036         default:
   5037             RLOGD("decodeVoiceRadioTechnology: Invoked with incorrect RadioState");
   5038             return -1;
   5039     }
   5040 }
   5041 
   5042 static int
   5043 decodeCdmaSubscriptionSource (RIL_RadioState radioState) {
   5044     switch (radioState) {
   5045         case RADIO_STATE_SIM_NOT_READY:
   5046         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
   5047         case RADIO_STATE_SIM_READY:
   5048         case RADIO_STATE_RUIM_NOT_READY:
   5049         case RADIO_STATE_RUIM_READY:
   5050         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
   5051             return CDMA_SUBSCRIPTION_SOURCE_RUIM_SIM;
   5052 
   5053         case RADIO_STATE_NV_NOT_READY:
   5054         case RADIO_STATE_NV_READY:
   5055             return CDMA_SUBSCRIPTION_SOURCE_NV;
   5056 
   5057         default:
   5058             RLOGD("decodeCdmaSubscriptionSource: Invoked with incorrect RadioState");
   5059             return -1;
   5060     }
   5061 }
   5062 
   5063 static int
   5064 decodeSimStatus (RIL_RadioState radioState) {
   5065    switch (radioState) {
   5066        case RADIO_STATE_SIM_NOT_READY:
   5067        case RADIO_STATE_RUIM_NOT_READY:
   5068        case RADIO_STATE_NV_NOT_READY:
   5069        case RADIO_STATE_NV_READY:
   5070            return -1;
   5071        case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
   5072        case RADIO_STATE_SIM_READY:
   5073        case RADIO_STATE_RUIM_READY:
   5074        case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
   5075            return radioState;
   5076        default:
   5077            RLOGD("decodeSimStatus: Invoked with incorrect RadioState");
   5078            return -1;
   5079    }
   5080 }
   5081 
   5082 static bool is3gpp2(int radioTech) {
   5083     switch (radioTech) {
   5084         case RADIO_TECH_IS95A:
   5085         case RADIO_TECH_IS95B:
   5086         case RADIO_TECH_1xRTT:
   5087         case RADIO_TECH_EVDO_0:
   5088         case RADIO_TECH_EVDO_A:
   5089         case RADIO_TECH_EVDO_B:
   5090         case RADIO_TECH_EHRPD:
   5091             return true;
   5092         default:
   5093             return false;
   5094     }
   5095 }
   5096 
   5097 /* If RIL sends SIM states or RUIM states, store the voice radio
   5098  * technology and subscription source information so that they can be
   5099  * returned when telephony framework requests them
   5100  */
   5101 static RIL_RadioState
   5102 processRadioState(RIL_RadioState newRadioState, RIL_SOCKET_ID socket_id) {
   5103 
   5104     if((newRadioState > RADIO_STATE_UNAVAILABLE) && (newRadioState < RADIO_STATE_ON)) {
   5105         int newVoiceRadioTech;
   5106         int newCdmaSubscriptionSource;
   5107         int newSimStatus;
   5108 
   5109         /* This is old RIL. Decode Subscription source and Voice Radio Technology
   5110            from Radio State and send change notifications if there has been a change */
   5111         newVoiceRadioTech = decodeVoiceRadioTechnology(newRadioState);
   5112         if(newVoiceRadioTech != voiceRadioTech) {
   5113             voiceRadioTech = newVoiceRadioTech;
   5114             RIL_UNSOL_RESPONSE(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
   5115                         &voiceRadioTech, sizeof(voiceRadioTech), socket_id);
   5116         }
   5117         if(is3gpp2(newVoiceRadioTech)) {
   5118             newCdmaSubscriptionSource = decodeCdmaSubscriptionSource(newRadioState);
   5119             if(newCdmaSubscriptionSource != cdmaSubscriptionSource) {
   5120                 cdmaSubscriptionSource = newCdmaSubscriptionSource;
   5121                 RIL_UNSOL_RESPONSE(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
   5122                         &cdmaSubscriptionSource, sizeof(cdmaSubscriptionSource), socket_id);
   5123             }
   5124         }
   5125         newSimStatus = decodeSimStatus(newRadioState);
   5126         if(newSimStatus != simRuimStatus) {
   5127             simRuimStatus = newSimStatus;
   5128             RIL_UNSOL_RESPONSE(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0, socket_id);
   5129         }
   5130 
   5131         /* Send RADIO_ON to telephony */
   5132         newRadioState = RADIO_STATE_ON;
   5133     }
   5134 
   5135     return newRadioState;
   5136 }
   5137 
   5138 
   5139 #if defined(ANDROID_MULTI_SIM)
   5140 extern "C"
   5141 void RIL_onUnsolicitedResponse(int unsolResponse, const void *data,
   5142                                 size_t datalen, RIL_SOCKET_ID socket_id)
   5143 #else
   5144 extern "C"
   5145 void RIL_onUnsolicitedResponse(int unsolResponse, const void *data,
   5146                                 size_t datalen)
   5147 #endif
   5148 {
   5149     int unsolResponseIndex;
   5150     int ret;
   5151     int64_t timeReceived = 0;
   5152     bool shouldScheduleTimeout = false;
   5153     RIL_RadioState newState;
   5154     RIL_SOCKET_ID soc_id = RIL_SOCKET_1;
   5155 
   5156 #if defined(ANDROID_MULTI_SIM)
   5157     soc_id = socket_id;
   5158 #endif
   5159 
   5160 
   5161     if (s_registerCalled == 0) {
   5162         // Ignore RIL_onUnsolicitedResponse before RIL_register
   5163         RLOGW("RIL_onUnsolicitedResponse called before RIL_register");
   5164         return;
   5165     }
   5166 
   5167     unsolResponseIndex = unsolResponse - RIL_UNSOL_RESPONSE_BASE;
   5168 
   5169     if ((unsolResponseIndex < 0)
   5170         || (unsolResponseIndex >= (int32_t)NUM_ELEMS(s_unsolResponses))) {
   5171         RLOGE("unsupported unsolicited response code %d", unsolResponse);
   5172         return;
   5173     }
   5174 
   5175     // Grab a wake lock if needed for this reponse,
   5176     // as we exit we'll either release it immediately
   5177     // or set a timer to release it later.
   5178     switch (s_unsolResponses[unsolResponseIndex].wakeType) {
   5179         case WAKE_PARTIAL:
   5180             grabPartialWakeLock();
   5181             shouldScheduleTimeout = true;
   5182         break;
   5183 
   5184         case DONT_WAKE:
   5185         default:
   5186             // No wake lock is grabed so don't set timeout
   5187             shouldScheduleTimeout = false;
   5188             break;
   5189     }
   5190 
   5191     // Mark the time this was received, doing this
   5192     // after grabing the wakelock incase getting
   5193     // the elapsedRealTime might cause us to goto
   5194     // sleep.
   5195     if (unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
   5196         timeReceived = elapsedRealtime();
   5197     }
   5198 
   5199     appendPrintBuf("[UNSL]< %s", requestToString(unsolResponse));
   5200 
   5201     Parcel p;
   5202     if (s_callbacks.version >= 13
   5203                 && s_unsolResponses[unsolResponseIndex].wakeType == WAKE_PARTIAL) {
   5204         p.writeInt32 (RESPONSE_UNSOLICITED_ACK_EXP);
   5205     } else {
   5206         p.writeInt32 (RESPONSE_UNSOLICITED);
   5207     }
   5208     p.writeInt32 (unsolResponse);
   5209 
   5210     ret = s_unsolResponses[unsolResponseIndex]
   5211                 .responseFunction(p, const_cast<void*>(data), datalen);
   5212     if (ret != 0) {
   5213         // Problem with the response. Don't continue;
   5214         goto error_exit;
   5215     }
   5216 
   5217     // some things get more payload
   5218     switch(unsolResponse) {
   5219         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
   5220             newState = processRadioState(CALL_ONSTATEREQUEST(soc_id), soc_id);
   5221             p.writeInt32(newState);
   5222             appendPrintBuf("%s {%s}", printBuf,
   5223                 radioStateToString(CALL_ONSTATEREQUEST(soc_id)));
   5224         break;
   5225 
   5226 
   5227         case RIL_UNSOL_NITZ_TIME_RECEIVED:
   5228             // Store the time that this was received so the
   5229             // handler of this message can account for
   5230             // the time it takes to arrive and process. In
   5231             // particular the system has been known to sleep
   5232             // before this message can be processed.
   5233             p.writeInt64(timeReceived);
   5234         break;
   5235     }
   5236 
   5237     if (s_callbacks.version < 13) {
   5238         if (shouldScheduleTimeout) {
   5239             UserCallbackInfo *p_info = internalRequestTimedCallback(wakeTimeoutCallback, NULL,
   5240                     &TIMEVAL_WAKE_TIMEOUT);
   5241 
   5242             if (p_info == NULL) {
   5243                 goto error_exit;
   5244             } else {
   5245                 // Cancel the previous request
   5246                 if (s_last_wake_timeout_info != NULL) {
   5247                     s_last_wake_timeout_info->userParam = (void *)1;
   5248                 }
   5249                 s_last_wake_timeout_info = p_info;
   5250             }
   5251         }
   5252     }
   5253 
   5254 #if VDBG
   5255     RLOGI("%s UNSOLICITED: %s length:%d", rilSocketIdToString(soc_id), requestToString(unsolResponse), p.dataSize());
   5256 #endif
   5257     ret = sendResponse(p, soc_id);
   5258     if (ret != 0 && unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
   5259 
   5260         // Unfortunately, NITZ time is not poll/update like everything
   5261         // else in the system. So, if the upstream client isn't connected,
   5262         // keep a copy of the last NITZ response (with receive time noted
   5263         // above) around so we can deliver it when it is connected
   5264 
   5265         if (s_lastNITZTimeData != NULL) {
   5266             free (s_lastNITZTimeData);
   5267             s_lastNITZTimeData = NULL;
   5268         }
   5269 
   5270         s_lastNITZTimeData = calloc(p.dataSize(), 1);
   5271         if (s_lastNITZTimeData == NULL) {
   5272              RLOGE("Memory allocation failed in RIL_onUnsolicitedResponse");
   5273              goto error_exit;
   5274         }
   5275         s_lastNITZTimeDataSize = p.dataSize();
   5276         memcpy(s_lastNITZTimeData, p.data(), p.dataSize());
   5277     }
   5278 
   5279     // Normal exit
   5280     return;
   5281 
   5282 error_exit:
   5283     if (shouldScheduleTimeout) {
   5284         releaseWakeLock();
   5285     }
   5286 }
   5287 
   5288 /** FIXME generalize this if you track UserCAllbackInfo, clear it
   5289     when the callback occurs
   5290 */
   5291 static UserCallbackInfo *
   5292 internalRequestTimedCallback (RIL_TimedCallback callback, void *param,
   5293                                 const struct timeval *relativeTime)
   5294 {
   5295     struct timeval myRelativeTime;
   5296     UserCallbackInfo *p_info;
   5297 
   5298     p_info = (UserCallbackInfo *) calloc(1, sizeof(UserCallbackInfo));
   5299     if (p_info == NULL) {
   5300         RLOGE("Memory allocation failed in internalRequestTimedCallback");
   5301         return p_info;
   5302 
   5303     }
   5304 
   5305     p_info->p_callback = callback;
   5306     p_info->userParam = param;
   5307 
   5308     if (relativeTime == NULL) {
   5309         /* treat null parameter as a 0 relative time */
   5310         memset (&myRelativeTime, 0, sizeof(myRelativeTime));
   5311     } else {
   5312         /* FIXME I think event_add's tv param is really const anyway */
   5313         memcpy (&myRelativeTime, relativeTime, sizeof(myRelativeTime));
   5314     }
   5315 
   5316     ril_event_set(&(p_info->event), -1, false, userTimerCallback, p_info);
   5317 
   5318     ril_timer_add(&(p_info->event), &myRelativeTime);
   5319 
   5320     triggerEvLoop();
   5321     return p_info;
   5322 }
   5323 
   5324 
   5325 extern "C" void
   5326 RIL_requestTimedCallback (RIL_TimedCallback callback, void *param,
   5327                                 const struct timeval *relativeTime) {
   5328     internalRequestTimedCallback (callback, param, relativeTime);
   5329 }
   5330 
   5331 const char *
   5332 failCauseToString(RIL_Errno e) {
   5333     switch(e) {
   5334         case RIL_E_SUCCESS: return "E_SUCCESS";
   5335         case RIL_E_RADIO_NOT_AVAILABLE: return "E_RADIO_NOT_AVAILABLE";
   5336         case RIL_E_GENERIC_FAILURE: return "E_GENERIC_FAILURE";
   5337         case RIL_E_PASSWORD_INCORRECT: return "E_PASSWORD_INCORRECT";
   5338         case RIL_E_SIM_PIN2: return "E_SIM_PIN2";
   5339         case RIL_E_SIM_PUK2: return "E_SIM_PUK2";
   5340         case RIL_E_REQUEST_NOT_SUPPORTED: return "E_REQUEST_NOT_SUPPORTED";
   5341         case RIL_E_CANCELLED: return "E_CANCELLED";
   5342         case RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL: return "E_OP_NOT_ALLOWED_DURING_VOICE_CALL";
   5343         case RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW: return "E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW";
   5344         case RIL_E_SMS_SEND_FAIL_RETRY: return "E_SMS_SEND_FAIL_RETRY";
   5345         case RIL_E_SIM_ABSENT:return "E_SIM_ABSENT";
   5346         case RIL_E_ILLEGAL_SIM_OR_ME:return "E_ILLEGAL_SIM_OR_ME";
   5347 #ifdef FEATURE_MULTIMODE_ANDROID
   5348         case RIL_E_SUBSCRIPTION_NOT_AVAILABLE:return "E_SUBSCRIPTION_NOT_AVAILABLE";
   5349         case RIL_E_MODE_NOT_SUPPORTED:return "E_MODE_NOT_SUPPORTED";
   5350 #endif
   5351         case RIL_E_FDN_CHECK_FAILURE: return "E_FDN_CHECK_FAILURE";
   5352         case RIL_E_MISSING_RESOURCE: return "E_MISSING_RESOURCE";
   5353         case RIL_E_NO_SUCH_ELEMENT: return "E_NO_SUCH_ELEMENT";
   5354         case RIL_E_DIAL_MODIFIED_TO_USSD: return "E_DIAL_MODIFIED_TO_USSD";
   5355         case RIL_E_DIAL_MODIFIED_TO_SS: return "E_DIAL_MODIFIED_TO_SS";
   5356         case RIL_E_DIAL_MODIFIED_TO_DIAL: return "E_DIAL_MODIFIED_TO_DIAL";
   5357         case RIL_E_USSD_MODIFIED_TO_DIAL: return "E_USSD_MODIFIED_TO_DIAL";
   5358         case RIL_E_USSD_MODIFIED_TO_SS: return "E_USSD_MODIFIED_TO_SS";
   5359         case RIL_E_USSD_MODIFIED_TO_USSD: return "E_USSD_MODIFIED_TO_USSD";
   5360         case RIL_E_SS_MODIFIED_TO_DIAL: return "E_SS_MODIFIED_TO_DIAL";
   5361         case RIL_E_SS_MODIFIED_TO_USSD: return "E_SS_MODIFIED_TO_USSD";
   5362         case RIL_E_SUBSCRIPTION_NOT_SUPPORTED: return "E_SUBSCRIPTION_NOT_SUPPORTED";
   5363         case RIL_E_SS_MODIFIED_TO_SS: return "E_SS_MODIFIED_TO_SS";
   5364         case RIL_E_LCE_NOT_SUPPORTED: return "E_LCE_NOT_SUPPORTED";
   5365         case RIL_E_NO_MEMORY: return "E_NO_MEMORY";
   5366         case RIL_E_INTERNAL_ERR: return "E_INTERNAL_ERR";
   5367         case RIL_E_SYSTEM_ERR: return "E_SYSTEM_ERR";
   5368         case RIL_E_MODEM_ERR: return "E_MODEM_ERR";
   5369         case RIL_E_INVALID_STATE: return "E_INVALID_STATE";
   5370         case RIL_E_NO_RESOURCES: return "E_NO_RESOURCES";
   5371         case RIL_E_SIM_ERR: return "E_SIM_ERR";
   5372         case RIL_E_INVALID_ARGUMENTS: return "E_INVALID_ARGUMENTS";
   5373         case RIL_E_INVALID_SIM_STATE: return "E_INVALID_SIM_STATE";
   5374         case RIL_E_INVALID_MODEM_STATE: return "E_INVALID_MODEM_STATE";
   5375         case RIL_E_INVALID_CALL_ID: return "E_INVALID_CALL_ID";
   5376         case RIL_E_NO_SMS_TO_ACK: return "E_NO_SMS_TO_ACK";
   5377         case RIL_E_NETWORK_ERR: return "E_NETWORK_ERR";
   5378         case RIL_E_REQUEST_RATE_LIMITED: return "E_REQUEST_RATE_LIMITED";
   5379         case RIL_E_SIM_BUSY: return "E_SIM_BUSY";
   5380         case RIL_E_SIM_FULL: return "E_SIM_FULL";
   5381         case RIL_E_NETWORK_REJECT: return "E_NETWORK_REJECT";
   5382         case RIL_E_OPERATION_NOT_ALLOWED: return "E_OPERATION_NOT_ALLOWED";
   5383         case RIL_E_EMPTY_RECORD: "E_EMPTY_RECORD";
   5384         case RIL_E_INVALID_SMS_FORMAT: return "E_INVALID_SMS_FORMAT";
   5385         case RIL_E_ENCODING_ERR: return "E_ENCODING_ERR";
   5386         case RIL_E_INVALID_SMSC_ADDRESS: return "E_INVALID_SMSC_ADDRESS";
   5387         case RIL_E_NO_SUCH_ENTRY: return "E_NO_SUCH_ENTRY";
   5388         case RIL_E_NETWORK_NOT_READY: return "E_NETWORK_NOT_READY";
   5389         case RIL_E_NOT_PROVISIONED: return "E_NOT_PROVISIONED";
   5390         case RIL_E_NO_SUBSCRIPTION: return "E_NO_SUBSCRIPTION";
   5391         case RIL_E_NO_NETWORK_FOUND: return "E_NO_NETWORK_FOUND";
   5392         case RIL_E_DEVICE_IN_USE: return "E_DEVICE_IN_USE";
   5393         case RIL_E_ABORTED: return "E_ABORTED";
   5394         case RIL_E_OEM_ERROR_1: return "E_OEM_ERROR_1";
   5395         case RIL_E_OEM_ERROR_2: return "E_OEM_ERROR_2";
   5396         case RIL_E_OEM_ERROR_3: return "E_OEM_ERROR_3";
   5397         case RIL_E_OEM_ERROR_4: return "E_OEM_ERROR_4";
   5398         case RIL_E_OEM_ERROR_5: return "E_OEM_ERROR_5";
   5399         case RIL_E_OEM_ERROR_6: return "E_OEM_ERROR_6";
   5400         case RIL_E_OEM_ERROR_7: return "E_OEM_ERROR_7";
   5401         case RIL_E_OEM_ERROR_8: return "E_OEM_ERROR_8";
   5402         case RIL_E_OEM_ERROR_9: return "E_OEM_ERROR_9";
   5403         case RIL_E_OEM_ERROR_10: return "E_OEM_ERROR_10";
   5404         case RIL_E_OEM_ERROR_11: return "E_OEM_ERROR_11";
   5405         case RIL_E_OEM_ERROR_12: return "E_OEM_ERROR_12";
   5406         case RIL_E_OEM_ERROR_13: return "E_OEM_ERROR_13";
   5407         case RIL_E_OEM_ERROR_14: return "E_OEM_ERROR_14";
   5408         case RIL_E_OEM_ERROR_15: return "E_OEM_ERROR_15";
   5409         case RIL_E_OEM_ERROR_16: return "E_OEM_ERROR_16";
   5410         case RIL_E_OEM_ERROR_17: return "E_OEM_ERROR_17";
   5411         case RIL_E_OEM_ERROR_18: return "E_OEM_ERROR_18";
   5412         case RIL_E_OEM_ERROR_19: return "E_OEM_ERROR_19";
   5413         case RIL_E_OEM_ERROR_20: return "E_OEM_ERROR_20";
   5414         case RIL_E_OEM_ERROR_21: return "E_OEM_ERROR_21";
   5415         case RIL_E_OEM_ERROR_22: return "E_OEM_ERROR_22";
   5416         case RIL_E_OEM_ERROR_23: return "E_OEM_ERROR_23";
   5417         case RIL_E_OEM_ERROR_24: return "E_OEM_ERROR_24";
   5418         case RIL_E_OEM_ERROR_25: return "E_OEM_ERROR_25";
   5419         default: return "<unknown error>";
   5420     }
   5421 }
   5422 
   5423 const char *
   5424 radioStateToString(RIL_RadioState s) {
   5425     switch(s) {
   5426         case RADIO_STATE_OFF: return "RADIO_OFF";
   5427         case RADIO_STATE_UNAVAILABLE: return "RADIO_UNAVAILABLE";
   5428         case RADIO_STATE_SIM_NOT_READY: return "RADIO_SIM_NOT_READY";
   5429         case RADIO_STATE_SIM_LOCKED_OR_ABSENT: return "RADIO_SIM_LOCKED_OR_ABSENT";
   5430         case RADIO_STATE_SIM_READY: return "RADIO_SIM_READY";
   5431         case RADIO_STATE_RUIM_NOT_READY:return"RADIO_RUIM_NOT_READY";
   5432         case RADIO_STATE_RUIM_READY:return"RADIO_RUIM_READY";
   5433         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:return"RADIO_RUIM_LOCKED_OR_ABSENT";
   5434         case RADIO_STATE_NV_NOT_READY:return"RADIO_NV_NOT_READY";
   5435         case RADIO_STATE_NV_READY:return"RADIO_NV_READY";
   5436         case RADIO_STATE_ON:return"RADIO_ON";
   5437         default: return "<unknown state>";
   5438     }
   5439 }
   5440 
   5441 const char *
   5442 callStateToString(RIL_CallState s) {
   5443     switch(s) {
   5444         case RIL_CALL_ACTIVE : return "ACTIVE";
   5445         case RIL_CALL_HOLDING: return "HOLDING";
   5446         case RIL_CALL_DIALING: return "DIALING";
   5447         case RIL_CALL_ALERTING: return "ALERTING";
   5448         case RIL_CALL_INCOMING: return "INCOMING";
   5449         case RIL_CALL_WAITING: return "WAITING";
   5450         default: return "<unknown state>";
   5451     }
   5452 }
   5453 
   5454 const char *
   5455 requestToString(int request) {
   5456 /*
   5457  cat libs/telephony/ril_commands.h \
   5458  | egrep "^ *{RIL_" \
   5459  | sed -re 's/\{RIL_([^,]+),[^,]+,([^}]+).+/case RIL_\1: return "\1";/'
   5460 
   5461 
   5462  cat libs/telephony/ril_unsol_commands.h \
   5463  | egrep "^ *{RIL_" \
   5464  | sed -re 's/\{RIL_([^,]+),([^}]+).+/case RIL_\1: return "\1";/'
   5465 
   5466 */
   5467     switch(request) {
   5468         case RIL_REQUEST_GET_SIM_STATUS: return "GET_SIM_STATUS";
   5469         case RIL_REQUEST_ENTER_SIM_PIN: return "ENTER_SIM_PIN";
   5470         case RIL_REQUEST_ENTER_SIM_PUK: return "ENTER_SIM_PUK";
   5471         case RIL_REQUEST_ENTER_SIM_PIN2: return "ENTER_SIM_PIN2";
   5472         case RIL_REQUEST_ENTER_SIM_PUK2: return "ENTER_SIM_PUK2";
   5473         case RIL_REQUEST_CHANGE_SIM_PIN: return "CHANGE_SIM_PIN";
   5474         case RIL_REQUEST_CHANGE_SIM_PIN2: return "CHANGE_SIM_PIN2";
   5475         case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: return "ENTER_NETWORK_DEPERSONALIZATION";
   5476         case RIL_REQUEST_GET_CURRENT_CALLS: return "GET_CURRENT_CALLS";
   5477         case RIL_REQUEST_DIAL: return "DIAL";
   5478         case RIL_REQUEST_GET_IMSI: return "GET_IMSI";
   5479         case RIL_REQUEST_HANGUP: return "HANGUP";
   5480         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: return "HANGUP_WAITING_OR_BACKGROUND";
   5481         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: return "HANGUP_FOREGROUND_RESUME_BACKGROUND";
   5482         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: return "SWITCH_WAITING_OR_HOLDING_AND_ACTIVE";
   5483         case RIL_REQUEST_CONFERENCE: return "CONFERENCE";
   5484         case RIL_REQUEST_UDUB: return "UDUB";
   5485         case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: return "LAST_CALL_FAIL_CAUSE";
   5486         case RIL_REQUEST_SIGNAL_STRENGTH: return "SIGNAL_STRENGTH";
   5487         case RIL_REQUEST_VOICE_REGISTRATION_STATE: return "VOICE_REGISTRATION_STATE";
   5488         case RIL_REQUEST_DATA_REGISTRATION_STATE: return "DATA_REGISTRATION_STATE";
   5489         case RIL_REQUEST_OPERATOR: return "OPERATOR";
   5490         case RIL_REQUEST_RADIO_POWER: return "RADIO_POWER";
   5491         case RIL_REQUEST_DTMF: return "DTMF";
   5492         case RIL_REQUEST_SEND_SMS: return "SEND_SMS";
   5493         case RIL_REQUEST_SEND_SMS_EXPECT_MORE: return "SEND_SMS_EXPECT_MORE";
   5494         case RIL_REQUEST_SETUP_DATA_CALL: return "SETUP_DATA_CALL";
   5495         case RIL_REQUEST_SIM_IO: return "SIM_IO";
   5496         case RIL_REQUEST_SEND_USSD: return "SEND_USSD";
   5497         case RIL_REQUEST_CANCEL_USSD: return "CANCEL_USSD";
   5498         case RIL_REQUEST_GET_CLIR: return "GET_CLIR";
   5499         case RIL_REQUEST_SET_CLIR: return "SET_CLIR";
   5500         case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: return "QUERY_CALL_FORWARD_STATUS";
   5501         case RIL_REQUEST_SET_CALL_FORWARD: return "SET_CALL_FORWARD";
   5502         case RIL_REQUEST_QUERY_CALL_WAITING: return "QUERY_CALL_WAITING";
   5503         case RIL_REQUEST_SET_CALL_WAITING: return "SET_CALL_WAITING";
   5504         case RIL_REQUEST_SMS_ACKNOWLEDGE: return "SMS_ACKNOWLEDGE";
   5505         case RIL_REQUEST_GET_IMEI: return "GET_IMEI";
   5506         case RIL_REQUEST_GET_IMEISV: return "GET_IMEISV";
   5507         case RIL_REQUEST_ANSWER: return "ANSWER";
   5508         case RIL_REQUEST_DEACTIVATE_DATA_CALL: return "DEACTIVATE_DATA_CALL";
   5509         case RIL_REQUEST_QUERY_FACILITY_LOCK: return "QUERY_FACILITY_LOCK";
   5510         case RIL_REQUEST_SET_FACILITY_LOCK: return "SET_FACILITY_LOCK";
   5511         case RIL_REQUEST_CHANGE_BARRING_PASSWORD: return "CHANGE_BARRING_PASSWORD";
   5512         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: return "QUERY_NETWORK_SELECTION_MODE";
   5513         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: return "SET_NETWORK_SELECTION_AUTOMATIC";
   5514         case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: return "SET_NETWORK_SELECTION_MANUAL";
   5515         case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : return "QUERY_AVAILABLE_NETWORKS ";
   5516         case RIL_REQUEST_DTMF_START: return "DTMF_START";
   5517         case RIL_REQUEST_DTMF_STOP: return "DTMF_STOP";
   5518         case RIL_REQUEST_BASEBAND_VERSION: return "BASEBAND_VERSION";
   5519         case RIL_REQUEST_SEPARATE_CONNECTION: return "SEPARATE_CONNECTION";
   5520         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: return "SET_PREFERRED_NETWORK_TYPE";
   5521         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: return "GET_PREFERRED_NETWORK_TYPE";
   5522         case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: return "GET_NEIGHBORING_CELL_IDS";
   5523         case RIL_REQUEST_SET_MUTE: return "SET_MUTE";
   5524         case RIL_REQUEST_GET_MUTE: return "GET_MUTE";
   5525         case RIL_REQUEST_QUERY_CLIP: return "QUERY_CLIP";
   5526         case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE: return "LAST_DATA_CALL_FAIL_CAUSE";
   5527         case RIL_REQUEST_DATA_CALL_LIST: return "DATA_CALL_LIST";
   5528         case RIL_REQUEST_RESET_RADIO: return "RESET_RADIO";
   5529         case RIL_REQUEST_OEM_HOOK_RAW: return "OEM_HOOK_RAW";
   5530         case RIL_REQUEST_OEM_HOOK_STRINGS: return "OEM_HOOK_STRINGS";
   5531         case RIL_REQUEST_SET_BAND_MODE: return "SET_BAND_MODE";
   5532         case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: return "QUERY_AVAILABLE_BAND_MODE";
   5533         case RIL_REQUEST_STK_GET_PROFILE: return "STK_GET_PROFILE";
   5534         case RIL_REQUEST_STK_SET_PROFILE: return "STK_SET_PROFILE";
   5535         case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: return "STK_SEND_ENVELOPE_COMMAND";
   5536         case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: return "STK_SEND_TERMINAL_RESPONSE";
   5537         case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: return "STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM";
   5538         case RIL_REQUEST_SCREEN_STATE: return "SCREEN_STATE";
   5539         case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: return "EXPLICIT_CALL_TRANSFER";
   5540         case RIL_REQUEST_SET_LOCATION_UPDATES: return "SET_LOCATION_UPDATES";
   5541         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:return"CDMA_SET_SUBSCRIPTION_SOURCE";
   5542         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:return"CDMA_SET_ROAMING_PREFERENCE";
   5543         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:return"CDMA_QUERY_ROAMING_PREFERENCE";
   5544         case RIL_REQUEST_SET_TTY_MODE:return"SET_TTY_MODE";
   5545         case RIL_REQUEST_QUERY_TTY_MODE:return"QUERY_TTY_MODE";
   5546         case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE";
   5547         case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE";
   5548         case RIL_REQUEST_CDMA_FLASH:return"CDMA_FLASH";
   5549         case RIL_REQUEST_CDMA_BURST_DTMF:return"CDMA_BURST_DTMF";
   5550         case RIL_REQUEST_CDMA_SEND_SMS:return"CDMA_SEND_SMS";
   5551         case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:return"CDMA_SMS_ACKNOWLEDGE";
   5552         case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:return"GSM_GET_BROADCAST_SMS_CONFIG";
   5553         case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:return"GSM_SET_BROADCAST_SMS_CONFIG";
   5554         case RIL_REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG:return "CDMA_GET_BROADCAST_SMS_CONFIG";
   5555         case RIL_REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG:return "CDMA_SET_BROADCAST_SMS_CONFIG";
   5556         case RIL_REQUEST_CDMA_SMS_BROADCAST_ACTIVATION:return "CDMA_SMS_BROADCAST_ACTIVATION";
   5557         case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY: return"CDMA_VALIDATE_AND_WRITE_AKEY";
   5558         case RIL_REQUEST_CDMA_SUBSCRIPTION: return"CDMA_SUBSCRIPTION";
   5559         case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM: return "CDMA_WRITE_SMS_TO_RUIM";
   5560         case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM: return "CDMA_DELETE_SMS_ON_RUIM";
   5561         case RIL_REQUEST_DEVICE_IDENTITY: return "DEVICE_IDENTITY";
   5562         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE: return "EXIT_EMERGENCY_CALLBACK_MODE";
   5563         case RIL_REQUEST_GET_SMSC_ADDRESS: return "GET_SMSC_ADDRESS";
   5564         case RIL_REQUEST_SET_SMSC_ADDRESS: return "SET_SMSC_ADDRESS";
   5565         case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS: return "REPORT_SMS_MEMORY_STATUS";
   5566         case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING: return "REPORT_STK_SERVICE_IS_RUNNING";
   5567         case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE: return "CDMA_GET_SUBSCRIPTION_SOURCE";
   5568         case RIL_REQUEST_ISIM_AUTHENTICATION: return "ISIM_AUTHENTICATION";
   5569         case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU: return "RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU";
   5570         case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS: return "RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS";
   5571         case RIL_REQUEST_VOICE_RADIO_TECH: return "VOICE_RADIO_TECH";
   5572         case RIL_REQUEST_WRITE_SMS_TO_SIM: return "WRITE_SMS_TO_SIM";
   5573         case RIL_REQUEST_GET_CELL_INFO_LIST: return"GET_CELL_INFO_LIST";
   5574         case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE: return"SET_UNSOL_CELL_INFO_LIST_RATE";
   5575         case RIL_REQUEST_SET_INITIAL_ATTACH_APN: return "RIL_REQUEST_SET_INITIAL_ATTACH_APN";
   5576         case RIL_REQUEST_IMS_REGISTRATION_STATE: return "IMS_REGISTRATION_STATE";
   5577         case RIL_REQUEST_IMS_SEND_SMS: return "IMS_SEND_SMS";
   5578         case RIL_REQUEST_SIM_TRANSMIT_APDU_BASIC: return "SIM_TRANSMIT_APDU_BASIC";
   5579         case RIL_REQUEST_SIM_OPEN_CHANNEL: return "SIM_OPEN_CHANNEL";
   5580         case RIL_REQUEST_SIM_CLOSE_CHANNEL: return "SIM_CLOSE_CHANNEL";
   5581         case RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL: return "SIM_TRANSMIT_APDU_CHANNEL";
   5582         case RIL_REQUEST_GET_RADIO_CAPABILITY: return "RIL_REQUEST_GET_RADIO_CAPABILITY";
   5583         case RIL_REQUEST_SET_RADIO_CAPABILITY: return "RIL_REQUEST_SET_RADIO_CAPABILITY";
   5584         case RIL_REQUEST_SET_UICC_SUBSCRIPTION: return "SET_UICC_SUBSCRIPTION";
   5585         case RIL_REQUEST_ALLOW_DATA: return "ALLOW_DATA";
   5586         case RIL_REQUEST_GET_HARDWARE_CONFIG: return "GET_HARDWARE_CONFIG";
   5587         case RIL_REQUEST_SIM_AUTHENTICATION: return "SIM_AUTHENTICATION";
   5588         case RIL_REQUEST_GET_DC_RT_INFO: return "GET_DC_RT_INFO";
   5589         case RIL_REQUEST_SET_DC_RT_INFO_RATE: return "SET_DC_RT_INFO_RATE";
   5590         case RIL_REQUEST_SET_DATA_PROFILE: return "SET_DATA_PROFILE";
   5591         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
   5592         case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
   5593         case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED";
   5594         case RIL_UNSOL_RESPONSE_NEW_SMS: return "UNSOL_RESPONSE_NEW_SMS";
   5595         case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT: return "UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT";
   5596         case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM: return "UNSOL_RESPONSE_NEW_SMS_ON_SIM";
   5597         case RIL_UNSOL_ON_USSD: return "UNSOL_ON_USSD";
   5598         case RIL_UNSOL_ON_USSD_REQUEST: return "UNSOL_ON_USSD_REQUEST(obsolete)";
   5599         case RIL_UNSOL_NITZ_TIME_RECEIVED: return "UNSOL_NITZ_TIME_RECEIVED";
   5600         case RIL_UNSOL_SIGNAL_STRENGTH: return "UNSOL_SIGNAL_STRENGTH";
   5601         case RIL_UNSOL_SUPP_SVC_NOTIFICATION: return "UNSOL_SUPP_SVC_NOTIFICATION";
   5602         case RIL_UNSOL_STK_SESSION_END: return "UNSOL_STK_SESSION_END";
   5603         case RIL_UNSOL_STK_PROACTIVE_COMMAND: return "UNSOL_STK_PROACTIVE_COMMAND";
   5604         case RIL_UNSOL_STK_EVENT_NOTIFY: return "UNSOL_STK_EVENT_NOTIFY";
   5605         case RIL_UNSOL_STK_CALL_SETUP: return "UNSOL_STK_CALL_SETUP";
   5606         case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FUL";
   5607         case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH";
   5608         case RIL_UNSOL_DATA_CALL_LIST_CHANGED: return "UNSOL_DATA_CALL_LIST_CHANGED";
   5609         case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING";
   5610         case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED: return "UNSOL_RESPONSE_SIM_STATUS_CHANGED";
   5611         case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS: return "UNSOL_NEW_CDMA_SMS";
   5612         case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS: return "UNSOL_NEW_BROADCAST_SMS";
   5613         case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL: return "UNSOL_CDMA_RUIM_SMS_STORAGE_FULL";
   5614         case RIL_UNSOL_RESTRICTED_STATE_CHANGED: return "UNSOL_RESTRICTED_STATE_CHANGED";
   5615         case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE: return "UNSOL_ENTER_EMERGENCY_CALLBACK_MODE";
   5616         case RIL_UNSOL_CDMA_CALL_WAITING: return "UNSOL_CDMA_CALL_WAITING";
   5617         case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS: return "UNSOL_CDMA_OTA_PROVISION_STATUS";
   5618         case RIL_UNSOL_CDMA_INFO_REC: return "UNSOL_CDMA_INFO_REC";
   5619         case RIL_UNSOL_OEM_HOOK_RAW: return "UNSOL_OEM_HOOK_RAW";
   5620         case RIL_UNSOL_RINGBACK_TONE: return "UNSOL_RINGBACK_TONE";
   5621         case RIL_UNSOL_RESEND_INCALL_MUTE: return "UNSOL_RESEND_INCALL_MUTE";
   5622         case RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED: return "UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED";
   5623         case RIL_UNSOL_CDMA_PRL_CHANGED: return "UNSOL_CDMA_PRL_CHANGED";
   5624         case RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE: return "UNSOL_EXIT_EMERGENCY_CALLBACK_MODE";
   5625         case RIL_UNSOL_RIL_CONNECTED: return "UNSOL_RIL_CONNECTED";
   5626         case RIL_UNSOL_VOICE_RADIO_TECH_CHANGED: return "UNSOL_VOICE_RADIO_TECH_CHANGED";
   5627         case RIL_UNSOL_CELL_INFO_LIST: return "UNSOL_CELL_INFO_LIST";
   5628         case RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED: return "RESPONSE_IMS_NETWORK_STATE_CHANGED";
   5629         case RIL_UNSOL_UICC_SUBSCRIPTION_STATUS_CHANGED: return "UNSOL_UICC_SUBSCRIPTION_STATUS_CHANGED";
   5630         case RIL_UNSOL_SRVCC_STATE_NOTIFY: return "UNSOL_SRVCC_STATE_NOTIFY";
   5631         case RIL_UNSOL_HARDWARE_CONFIG_CHANGED: return "HARDWARE_CONFIG_CHANGED";
   5632         case RIL_UNSOL_DC_RT_INFO_CHANGED: return "UNSOL_DC_RT_INFO_CHANGED";
   5633         case RIL_REQUEST_SHUTDOWN: return "SHUTDOWN";
   5634         case RIL_UNSOL_RADIO_CAPABILITY: return "RIL_UNSOL_RADIO_CAPABILITY";
   5635         case RIL_RESPONSE_ACKNOWLEDGEMENT: return "RIL_RESPONSE_ACKNOWLEDGEMENT";
   5636         default: return "<unknown request>";
   5637     }
   5638 }
   5639 
   5640 const char *
   5641 rilSocketIdToString(RIL_SOCKET_ID socket_id)
   5642 {
   5643     switch(socket_id) {
   5644         case RIL_SOCKET_1:
   5645             return "RIL_SOCKET_1";
   5646 #if (SIM_COUNT >= 2)
   5647         case RIL_SOCKET_2:
   5648             return "RIL_SOCKET_2";
   5649 #endif
   5650 #if (SIM_COUNT >= 3)
   5651         case RIL_SOCKET_3:
   5652             return "RIL_SOCKET_3";
   5653 #endif
   5654 #if (SIM_COUNT >= 4)
   5655         case RIL_SOCKET_4:
   5656             return "RIL_SOCKET_4";
   5657 #endif
   5658         default:
   5659             return "not a valid RIL";
   5660     }
   5661 }
   5662 
   5663 /*
   5664  * Returns true for a debuggable build.
   5665  */
   5666 static bool isDebuggable() {
   5667     char debuggable[PROP_VALUE_MAX];
   5668     property_get("ro.debuggable", debuggable, "0");
   5669     if (strcmp(debuggable, "1") == 0) {
   5670         return true;
   5671     }
   5672     return false;
   5673 }
   5674 
   5675 } /* namespace android */
   5676 
   5677 void rilEventAddWakeup_helper(struct ril_event *ev) {
   5678     android::rilEventAddWakeup(ev);
   5679 }
   5680 
   5681 void listenCallback_helper(int fd, short flags, void *param) {
   5682     android::listenCallback(fd, flags, param);
   5683 }
   5684 
   5685 int blockingWrite_helper(int fd, void *buffer, size_t len) {
   5686     return android::blockingWrite(fd, buffer, len);
   5687 }
   5688