Merge branch 'security-aosp-tm-release' into int/13/fp3

* security-aosp-tm-release:
  DO NOT MERGE Block access to sms/mms db from work profile.

Change-Id: I3c57c7f76ffcf7bdd308822528529bcbe864c161
diff --git a/assets/latest_carrier_id/carrier_list.pb b/assets/latest_carrier_id/carrier_list.pb
index 7c46449..1dfa0ff 100644
--- a/assets/latest_carrier_id/carrier_list.pb
+++ b/assets/latest_carrier_id/carrier_list.pb
Binary files differ
diff --git a/assets/latest_carrier_id/carrier_list.textpb b/assets/latest_carrier_id/carrier_list.textpb
index 5b521f2..c155df7 100644
--- a/assets/latest_carrier_id/carrier_list.textpb
+++ b/assets/latest_carrier_id/carrier_list.textpb
Binary files differ
diff --git a/assets/sdk28_carrier_id/carrier_list.pb b/assets/sdk28_carrier_id/carrier_list.pb
index ff06545..36f0b3d 100644
--- a/assets/sdk28_carrier_id/carrier_list.pb
+++ b/assets/sdk28_carrier_id/carrier_list.pb
Binary files differ
diff --git a/assets/sdk28_carrier_id/carrier_list.textpb b/assets/sdk28_carrier_id/carrier_list.textpb
index 881a66a..9ca54e6 100644
--- a/assets/sdk28_carrier_id/carrier_list.textpb
+++ b/assets/sdk28_carrier_id/carrier_list.textpb
Binary files differ
diff --git a/assets/sdk29_carrier_id/carrier_list.pb b/assets/sdk29_carrier_id/carrier_list.pb
index fd32451..c989c0f 100644
--- a/assets/sdk29_carrier_id/carrier_list.pb
+++ b/assets/sdk29_carrier_id/carrier_list.pb
Binary files differ
diff --git a/assets/sdk29_carrier_id/carrier_list.textpb b/assets/sdk29_carrier_id/carrier_list.textpb
index 4a2a263..d1be30b 100644
--- a/assets/sdk29_carrier_id/carrier_list.textpb
+++ b/assets/sdk29_carrier_id/carrier_list.textpb
Binary files differ
diff --git a/assets/sdk30_carrier_id/carrier_list.pb b/assets/sdk30_carrier_id/carrier_list.pb
index be5d8f5..9cbae5e 100644
--- a/assets/sdk30_carrier_id/carrier_list.pb
+++ b/assets/sdk30_carrier_id/carrier_list.pb
Binary files differ
diff --git a/assets/sdk30_carrier_id/carrier_list.textpb b/assets/sdk30_carrier_id/carrier_list.textpb
index ef71379..8974b10 100644
--- a/assets/sdk30_carrier_id/carrier_list.textpb
+++ b/assets/sdk30_carrier_id/carrier_list.textpb
Binary files differ
diff --git a/assets/sdk31_carrier_id/carrier_list.pb b/assets/sdk31_carrier_id/carrier_list.pb
index 11e2628..6410005 100644
--- a/assets/sdk31_carrier_id/carrier_list.pb
+++ b/assets/sdk31_carrier_id/carrier_list.pb
Binary files differ
diff --git a/assets/sdk31_carrier_id/carrier_list.textpb b/assets/sdk31_carrier_id/carrier_list.textpb
index fe1806f..d799d4b 100644
--- a/assets/sdk31_carrier_id/carrier_list.textpb
+++ b/assets/sdk31_carrier_id/carrier_list.textpb
Binary files differ
diff --git a/res/values-te/strings.xml b/res/values-te/strings.xml
index 0bbaa47..2da01b2 100644
--- a/res/values-te/strings.xml
+++ b/res/values-te/strings.xml
@@ -17,5 +17,5 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <string name="app_label" product="tablet" msgid="9194799012395299737">"మొబైల్ నెట్‌వర్క్ కాన్ఫిగరేషన్"</string>
-    <string name="app_label" product="default" msgid="8338087656149558019">"ఫోన్ మరియు సందేశ నిల్వ"</string>
+    <string name="app_label" product="default" msgid="8338087656149558019">"ఫోన్ మరియు సందేశ స్టోరేజ్‌"</string>
 </resources>
diff --git a/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java b/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
index 100354f..a544877 100644
--- a/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
+++ b/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
@@ -44,11 +44,13 @@
 import android.provider.Telephony.Sms;
 import android.provider.Telephony.Sms.Intents;
 import android.provider.Telephony.Threads;
+import android.telephony.AnomalyReporter;
 import android.telephony.SubscriptionManager;
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.telephony.PhoneFactory;
+import com.android.internal.telephony.TelephonyStatsLog;
 
 import com.google.android.mms.pdu.EncodedStringValue;
 import com.google.android.mms.pdu.PduHeaders;
@@ -60,6 +62,7 @@
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Iterator;
+import java.util.UUID;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
@@ -81,6 +84,14 @@
  */
 public class MmsSmsDatabaseHelper extends SQLiteOpenHelper {
     private static final String TAG = "MmsSmsDatabaseHelper";
+    private static final int SECURITY_EXCEPTION = TelephonyStatsLog
+            .MMS_SMS_DATABASE_HELPER_ON_UPGRADE_FAILED__FAILURE_CODE__FAILURE_SECURITY_EXCEPTION;
+    private static final int FAILURE_UNKNOWN = TelephonyStatsLog
+        .MMS_SMS_DATABASE_HELPER_ON_UPGRADE_FAILED__FAILURE_CODE__FAILURE_UNKNOWN;
+    private static final int SQL_EXCEPTION = TelephonyStatsLog
+            .MMS_SMS_DATABASE_HELPER_ON_UPGRADE_FAILED__FAILURE_CODE__FAILURE_SQL_EXCEPTION;
+    private static final int IO_EXCEPTION = TelephonyStatsLog
+            .MMS_SMS_DATABASE_HELPER_ON_UPGRADE_FAILED__FAILURE_CODE__FAILURE_IO_EXCEPTION;
 
     private static final String SMS_UPDATE_THREAD_READ_BODY =
                         "  UPDATE threads SET read = " +
@@ -264,6 +275,9 @@
     // cache for INITIAL_CREATE_DONE shared pref so access to it can be avoided when possible
     private static AtomicBoolean sInitialCreateDone = new AtomicBoolean(false);
 
+    private static final UUID CREATE_CALLED_MULTIPLE_TIMES_UUID = UUID.fromString(
+        "6ead002e-c001-4c05-9bca-67d7c4e29782");
+
     /**
      * The primary purpose of this DatabaseErrorHandler is to broadcast an intent on corruption and
      * print a Log.wtf so database corruption can be caught earlier.
@@ -546,7 +560,9 @@
             if (isInitialCreateDone()) {
                 // this onCreate is called after onCreate was called once initially. The db file
                 // disappeared mysteriously?
-                localLogWtf("onCreate: was already called once earlier");
+                AnomalyReporter.reportAnomaly(CREATE_CALLED_MULTIPLE_TIMES_UUID,
+                                              "MmsSmsDatabaseHelper: onCreate() was already "
+                                              + "called once earlier");
                 intent.putExtra(Intents.EXTRA_IS_INITIAL_CREATE, false);
             } else {
                 setInitialCreateDone();
@@ -653,6 +669,11 @@
     }
 
     private void createWordsTables(SQLiteDatabase db) {
+        createWordsTables(db, -1, -1, -1);
+    }
+
+    private void createWordsTables(
+            SQLiteDatabase db, int oldVersion, int currentVersion, int upgradeVersion) {
         try {
             db.execSQL("CREATE VIRTUAL TABLE words USING FTS3 (_id INTEGER PRIMARY KEY, index_text TEXT, source_id INTEGER, table_to_use INTEGER);");
 
@@ -670,6 +691,7 @@
             populateWordsTable(db);
         } catch (Exception ex) {
             Log.e(TAG, "got exception creating words table: " + ex.toString());
+            logException(ex, oldVersion, currentVersion, upgradeVersion);
         }
     }
 
@@ -681,36 +703,60 @@
     }
 
     private void createThreadIdIndex(SQLiteDatabase db) {
+        createThreadIdIndex(db, -1, -1, -1);
+    }
+
+    private void createThreadIdIndex(
+            SQLiteDatabase db, int oldVersion, int currentVersion, int upgradeVersion) {
         try {
             db.execSQL("CREATE INDEX IF NOT EXISTS typeThreadIdIndex ON sms" +
             " (type, thread_id);");
         } catch (Exception ex) {
             Log.e(TAG, "got exception creating indices: " + ex.toString());
+            logException(ex, oldVersion, currentVersion, upgradeVersion);
         }
     }
 
     private void createThreadIdDateIndex(SQLiteDatabase db) {
+        createThreadIdDateIndex(db, -1, -1, -1);
+    }
+
+    private void createThreadIdDateIndex(
+            SQLiteDatabase db, int oldVersion, int currentVersion, int upgradeVersion) {
         try {
             db.execSQL("CREATE INDEX IF NOT EXISTS threadIdDateIndex ON sms" +
             " (thread_id, date);");
         } catch (Exception ex) {
             Log.e(TAG, "got exception creating indices: " + ex.toString());
+            logException(ex, oldVersion, currentVersion, upgradeVersion);
         }
     }
 
     private void createPartMidIndex(SQLiteDatabase db) {
+        createPartMidIndex(db, -1, -1, -1);
+    }
+
+    private void createPartMidIndex(
+            SQLiteDatabase db, int oldVersion, int currentVersion, int upgradeVersion) {
         try {
             db.execSQL("CREATE INDEX IF NOT EXISTS partMidIndex ON part (mid)");
         } catch (Exception ex) {
             Log.e(TAG, "got exception creating indices: " + ex.toString());
+            logException(ex, oldVersion, currentVersion, upgradeVersion);
         }
     }
 
     private void createAddrMsgIdIndex(SQLiteDatabase db) {
+        createAddrMsgIdIndex(db, -1, -1, -1);
+    }
+
+    private void createAddrMsgIdIndex(
+            SQLiteDatabase db, int oldVersion, int currentVersion, int upgradeVersion) {
         try {
             db.execSQL("CREATE INDEX IF NOT EXISTS addrMsgIdIndex ON addr (msg_id)");
         } catch (Exception ex) {
             Log.e(TAG, "got exception creating indices: " + ex.toString());
+            logException(ex, oldVersion, currentVersion, upgradeVersion);
         }
     }
 
@@ -1266,6 +1312,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 41);
                 break;
             } finally {
                 db.endTransaction();
@@ -1282,6 +1329,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 42);
                 break;
             } finally {
                 db.endTransaction();
@@ -1298,6 +1346,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 43);
                 break;
             } finally {
                 db.endTransaction();
@@ -1314,6 +1363,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 44);
                 break;
             } finally {
                 db.endTransaction();
@@ -1330,6 +1380,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 45);
                 break;
             } finally {
                 db.endTransaction();
@@ -1341,10 +1392,11 @@
             }
             db.beginTransaction();
             try {
-                upgradeDatabaseToVersion46(db);
+                upgradeDatabaseToVersion46(db, oldVersion, currentVersion);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 46);
                 break;
             } finally {
                 db.endTransaction();
@@ -1361,6 +1413,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 47);
                 break;
             } finally {
                 db.endTransaction();
@@ -1377,6 +1430,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 48);
                 break;
             } finally {
                 db.endTransaction();
@@ -1389,10 +1443,11 @@
 
             db.beginTransaction();
             try {
-                createWordsTables(db);
+                createWordsTables(db, oldVersion, currentVersion, 49);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 49);
                 break;
             } finally {
                 db.endTransaction();
@@ -1404,10 +1459,11 @@
             }
             db.beginTransaction();
             try {
-                createThreadIdIndex(db);
+                createThreadIdIndex(db, oldVersion, currentVersion, 50);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 50);
                 break; // force to destroy all old data;
             } finally {
                 db.endTransaction();
@@ -1424,6 +1480,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 51);
                 break;
             } finally {
                 db.endTransaction();
@@ -1446,6 +1503,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 53);
                 break;
             } finally {
                 db.endTransaction();
@@ -1462,6 +1520,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 54);
                 break;
             } finally {
                 db.endTransaction();
@@ -1478,6 +1537,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 55);
                 break;
             } finally {
                 db.endTransaction();
@@ -1494,6 +1554,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 56);
                 break;
             } finally {
                 db.endTransaction();
@@ -1510,6 +1571,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 57);
                 break;
             } finally {
                 db.endTransaction();
@@ -1526,6 +1588,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 58);
                 break;
             } finally {
                 db.endTransaction();
@@ -1542,6 +1605,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 59);
                 break;
             } finally {
                 db.endTransaction();
@@ -1558,6 +1622,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 60);
                 break;
             } finally {
                 db.endTransaction();
@@ -1574,6 +1639,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 61);
                 break;
             } finally {
                 db.endTransaction();
@@ -1586,10 +1652,11 @@
 
             db.beginTransaction();
             try {
-                upgradeDatabaseToVersion62(db);
+                upgradeDatabaseToVersion62(db, oldVersion, currentVersion);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 62);
                 break;
             } finally {
                 db.endTransaction();
@@ -1603,10 +1670,11 @@
             db.beginTransaction();
             try {
                 // upgrade to 63: just add a happy little index.
-                createThreadIdDateIndex(db);
+                createThreadIdDateIndex(db, oldVersion, currentVersion, 63);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 63);
                 break;
             } finally {
                 db.endTransaction();
@@ -1623,6 +1691,7 @@
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 64);
                 break;
             } finally {
                 db.endTransaction();
@@ -1635,10 +1704,11 @@
 
             db.beginTransaction();
             try {
-                upgradeDatabaseToVersion65(db);
+                upgradeDatabaseToVersion65(db, oldVersion, currentVersion);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 65);
                 break;
             } finally {
                 db.endTransaction();
@@ -1651,10 +1721,11 @@
 
             db.beginTransaction();
             try {
-                upgradeDatabaseToVersion66(db);
+                upgradeDatabaseToVersion66(db, oldVersion, currentVersion);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 66);
                 break;
             } finally {
                 db.endTransaction();
@@ -1666,11 +1737,12 @@
             }
             db.beginTransaction();
             try {
-                createPartMidIndex(db);
-                createAddrMsgIdIndex(db);
+                createPartMidIndex(db, oldVersion, currentVersion, 67);
+                createAddrMsgIdIndex(db, oldVersion, currentVersion, 67);
                 db.setTransactionSuccessful();
             } catch (Throwable ex) {
                 Log.e(TAG, ex.getMessage(), ex);
+                logException(ex, oldVersion, currentVersion, 67);
                 break; // force to destroy all old data;
             } finally {
                 db.endTransaction();
@@ -1685,6 +1757,24 @@
         onCreate(db);
     }
 
+    private void logException(
+            Throwable ex, int oldVersion, int currentVersion, int upgradeVersion) {
+        int exception = FAILURE_UNKNOWN;
+        if (ex instanceof SQLiteException) {
+            exception = SQL_EXCEPTION;
+        } else if (ex instanceof IOException) {
+            exception = IO_EXCEPTION;
+        } else if (ex instanceof SecurityException) {
+            exception = SECURITY_EXCEPTION;
+        }
+        TelephonyStatsLog.write(
+            TelephonyStatsLog.MMS_SMS_DATABASE_HELPER_ON_UPGRADE_FAILED,
+            oldVersion,
+            currentVersion,
+            upgradeVersion,
+            exception);
+    }
+
     private void dropAll(SQLiteDatabase db) {
         // Clean the database out in order to start over from scratch.
         // We don't need to drop our triggers here because SQLite automatically
@@ -1751,7 +1841,7 @@
         db.execSQL("ALTER TABLE pdu ADD COLUMN " + Mms.LOCKED + " INTEGER DEFAULT 0");
     }
 
-    private void upgradeDatabaseToVersion46(SQLiteDatabase db) {
+    private void upgradeDatabaseToVersion46(SQLiteDatabase db, int oldVersion, int currentVersion) {
         // add the "text" column for caching inline text (e.g. strings) instead of
         // putting them in an external file
         db.execSQL("ALTER TABLE part ADD COLUMN " + Part.TEXT + " TEXT");
@@ -1789,6 +1879,7 @@
                         } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
+                            logException(e, oldVersion, currentVersion, 46);
                         }
                     }
                 }
@@ -1801,6 +1892,7 @@
                     (new File(pathToDelete)).delete();
                 } catch (SecurityException ex) {
                     Log.e(TAG, "unable to clean up old mms file for " + pathToDelete, ex);
+                    logException(ex, oldVersion, currentVersion, 46);
                 }
             }
             if (textRows != null) {
@@ -1922,7 +2014,7 @@
 
     }
 
-    private void upgradeDatabaseToVersion62(SQLiteDatabase db) {
+    private void upgradeDatabaseToVersion62(SQLiteDatabase db, int oldVersion, int currentVersion) {
         // When a non-FBE device is upgraded to N, all MMS attachment files are moved from
         // /data/data to /data/user_de. We need to update the paths stored in the parts table to
         // reflect this change.
@@ -1932,6 +2024,7 @@
         }
         catch (IOException e){
             Log.e(TAG, "openFile: check file path failed " + e, e);
+            logException(e, oldVersion, currentVersion, 62);
             return;
         }
 
@@ -1956,7 +2049,7 @@
         db.execSQL("ALTER TABLE " + SmsProvider.TABLE_RAW +" ADD COLUMN deleted INTEGER DEFAULT 0");
     }
 
-    private void upgradeDatabaseToVersion65(SQLiteDatabase db) {
+    private void upgradeDatabaseToVersion65(SQLiteDatabase db, int oldVersion, int currentVersion) {
         // aosp and internal code diverged at version 63. Aosp did createThreadIdDateIndex() on
         // upgrading to 63, whereas internal (nyc) added column 'deleted'. A device upgrading from
         // nyc will have columns deleted and message_body in raw table with version 64, but not
@@ -1966,17 +2059,19 @@
         } catch (SQLiteException e) {
             Log.w(TAG, "[upgradeDatabaseToVersion65] Exception adding column message_body; " +
                     "trying createThreadIdDateIndex() instead: " + e);
+            logException(e, oldVersion, currentVersion, 65);
             createThreadIdDateIndex(db);
         }
     }
 
-    private void upgradeDatabaseToVersion66(SQLiteDatabase db) {
+    private void upgradeDatabaseToVersion66(SQLiteDatabase db, int oldVersion, int currentVersion) {
         try {
             db.execSQL("ALTER TABLE " + SmsProvider.TABLE_RAW
                     + " ADD COLUMN display_originating_addr TEXT");
         } catch (SQLiteException e) {
             Log.e(TAG, "[upgradeDatabaseToVersion66] Exception adding column "
                     + "display_originating_addr; " + e);
+            logException(e, oldVersion, currentVersion, 66);
         }
     }
 
diff --git a/src/com/android/providers/telephony/MmsSmsProvider.java b/src/com/android/providers/telephony/MmsSmsProvider.java
index 04875a4..c3998f1 100644
--- a/src/com/android/providers/telephony/MmsSmsProvider.java
+++ b/src/com/android/providers/telephony/MmsSmsProvider.java
@@ -45,6 +45,8 @@
 import android.text.TextUtils;
 import android.util.Log;
 
+import com.android.internal.telephony.TelephonyStatsLog;
+
 import com.google.android.mms.pdu.PduHeaders;
 
 import java.io.FileDescriptor;
@@ -80,6 +82,10 @@
             new UriMatcher(UriMatcher.NO_MATCH);
     private static final String LOG_TAG = "MmsSmsProvider";
     private static final boolean DEBUG = false;
+    private static final int MULTIPLE_THREAD_IDS_FOUND = TelephonyStatsLog
+        .MMS_SMS_PROVIDER_GET_THREAD_ID_FAILED__FAILURE_CODE__FAILURE_MULTIPLE_THREAD_IDS_FOUND;
+    private static final int FAILURE_FIND_OR_CREATE_THREAD_ID_SQL = TelephonyStatsLog
+        .MMS_SMS_PROVIDER_GET_THREAD_ID_FAILED__FAILURE_CODE__FAILURE_FIND_OR_CREATE_THREAD_ID_SQL;
 
     private static final String NO_DELETES_INSERTS_OR_UPDATES =
             "MmsSmsProvider does not support deletes, inserts, or updates for this URI.";
@@ -367,8 +373,15 @@
                 if ((simple != null) && simple.equals("true")) {
                     String threadType = uri.getQueryParameter("thread_type");
                     if (!TextUtils.isEmpty(threadType)) {
-                        selection = concatSelections(
-                                selection, Threads.TYPE + "=" + threadType);
+                        try {
+                            Integer.parseInt(threadType);
+                            selection = concatSelections(
+                                    selection, Threads.TYPE + "=" + threadType);
+                        } catch (NumberFormatException ex) {
+                            Log.e(LOG_TAG, "Thread type must be int");
+                            // return empty cursor
+                            break;
+                        }
                     }
                     cursor = getSimpleConversations(
                             projection, selection, selectionArgs, sortOrder);
@@ -497,9 +510,15 @@
                 String extraSelection = (proto != -1) ?
                         (PendingMessages.PROTO_TYPE + "=" + proto) : " 0=0 ";
                 if (!TextUtils.isEmpty(msgId)) {
-                    extraSelection += " AND " + PendingMessages.MSG_ID + "=" + msgId;
+                    try {
+                        Long.parseLong(msgId);
+                        extraSelection += " AND " + PendingMessages.MSG_ID + "=" + msgId;
+                    } catch(NumberFormatException ex) {
+                        Log.e(LOG_TAG, "MSG ID must be a Long.");
+                        // return empty cursor
+                        break;
+                    }
                 }
-
                 String finalSelection = TextUtils.isEmpty(selection)
                         ? extraSelection : ("(" + extraSelection + ") AND " + selection);
                 String finalOrder = TextUtils.isEmpty(sortOrder)
@@ -698,6 +717,10 @@
         if (addressIds.size() == 0) {
             Log.e(LOG_TAG, "getThreadId: NO receipients specified -- NOT creating thread",
                     new Exception());
+            TelephonyStatsLog.write(
+                TelephonyStatsLog.MMS_SMS_PROVIDER_GET_THREAD_ID_FAILED,
+                TelephonyStatsLog
+                    .MMS_SMS_PROVIDER_GET_THREAD_ID_FAILED__FAILURE_CODE__FAILURE_NO_RECIPIENTS);
             return null;
         } else if (addressIds.size() == 1) {
             // optimize for size==1, which should be most of the cases
@@ -736,12 +759,18 @@
             db.setTransactionSuccessful();
         } catch (Throwable ex) {
             Log.e(LOG_TAG, ex.getMessage(), ex);
+            TelephonyStatsLog.write(
+                TelephonyStatsLog.MMS_SMS_PROVIDER_GET_THREAD_ID_FAILED,
+                FAILURE_FIND_OR_CREATE_THREAD_ID_SQL);
         } finally {
             db.endTransaction();
         }
 
         if (cursor != null && cursor.getCount() > 1) {
             Log.w(LOG_TAG, "getThreadId: why is cursorCount=" + cursor.getCount());
+            TelephonyStatsLog.write(
+                TelephonyStatsLog.MMS_SMS_PROVIDER_GET_THREAD_ID_FAILED,
+                MULTIPLE_THREAD_IDS_FOUND);
         }
         return cursor;
     }
@@ -1034,7 +1063,6 @@
     private Cursor getMessagesByPhoneNumber(
             String phoneNumber, String[] projection, String selection,
             String sortOrder, String smsTable, String pduTable) {
-        String escapedPhoneNumber = DatabaseUtils.sqlEscapeString(phoneNumber);
         int minMatch =
             getContext().getResources().getInteger(
                     com.android.internal.R.integer.config_phonenumber_compare_min_match);
@@ -1045,8 +1073,7 @@
         String finalSmsSelection =
                 concatSelections(
                         selection,
-                        "(address=" + escapedPhoneNumber + " OR PHONE_NUMBERS_EQUAL(address, " +
-                        escapedPhoneNumber +
+                        "(address=? OR PHONE_NUMBERS_EQUAL(address, ?" +
                         (mUseStrictPhoneNumberComparation ? ", 1))" : ", 0, " + minMatch + "))"));
         SQLiteQueryBuilder mmsQueryBuilder = new SQLiteQueryBuilder();
         SQLiteQueryBuilder smsQueryBuilder = new SQLiteQueryBuilder();
@@ -1056,9 +1083,8 @@
         mmsQueryBuilder.setTables(
                 pduTable +
                 ", (SELECT msg_id AS address_msg_id " +
-                "FROM addr WHERE (address=" + escapedPhoneNumber +
-                " OR PHONE_NUMBERS_EQUAL(addr.address, " +
-                escapedPhoneNumber +
+                "FROM addr WHERE (address=?" +
+                " OR PHONE_NUMBERS_EQUAL(addr.address, ?" +
                 (mUseStrictPhoneNumberComparation ? ", 1))) " : ", 0, " + minMatch + "))) ") +
                 "AS matching_addresses");
         smsQueryBuilder.setTables(smsTable);
@@ -1077,7 +1103,8 @@
         String unionQuery = unionQueryBuilder.buildUnionQuery(
                 new String[] { mmsSubQuery, smsSubQuery }, sortOrder, null);
 
-        return mOpenHelper.getReadableDatabase().rawQuery(unionQuery, EMPTY_STRING_ARRAY);
+        return mOpenHelper.getReadableDatabase().rawQuery(unionQuery,
+                new String[] { phoneNumber, phoneNumber, phoneNumber, phoneNumber });
     }
 
     /**
diff --git a/tests/src/com/android/providers/telephony/TelephonyProviderTest.java b/tests/src/com/android/providers/telephony/TelephonyProviderTest.java
index b3892be..d456777 100644
--- a/tests/src/com/android/providers/telephony/TelephonyProviderTest.java
+++ b/tests/src/com/android/providers/telephony/TelephonyProviderTest.java
@@ -48,7 +48,7 @@
 import android.test.suitebuilder.annotation.SmallTest;
 import android.text.TextUtils;
 import android.util.Log;
-
+import com.android.internal.telephony.LocalLog;
 import androidx.test.InstrumentationRegistry;
 
 import junit.framework.TestCase;
@@ -64,7 +64,9 @@
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
+import java.lang.reflect.Field;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.List;
 import java.util.stream.IntStream;
 
@@ -358,6 +360,12 @@
         notifyChangeRestoreCount = 0;
         // Required to access SIMINFO table
         mTelephonyProviderTestable.fakeCallingUid(Process.PHONE_UID);
+        // Ignore local log during test
+        Field field = PhoneFactory.class.getDeclaredField("sLocalLogs");
+        field.setAccessible(true);
+        HashMap<String, LocalLog> localLogs = new HashMap<>();
+        localLogs.put("TelephonyProvider", new LocalLog(0));
+        field.set(null, localLogs);
     }
 
     private void setUpMockContext(boolean isActiveSubId) {
@@ -1671,7 +1679,6 @@
         assertEquals(1, cursor.getCount());
         cursor.moveToFirst();
         assertEquals(otherName, cursor.getString(0));
-        PhoneFactory.addLocalLog("TelephonyProvider", 1);
     }
 
     /**