upb: check message field shapes before assigning well-known types

PiperOrigin-RevId: 1026073605
diff --git a/upb/json/BUILD b/upb/json/BUILD
index bb9b048..d8679dc 100644
--- a/upb/json/BUILD
+++ b/upb/json/BUILD
@@ -59,9 +59,11 @@
         "//:struct_upb_proto",
         "//:timestamp_upb_proto",
         "//:timestamp_upb_reflection_proto",
+        "//src/google/protobuf:descriptor_upb_c_proto",
         "//upb/base",
         "//upb/mem",
         "//upb/message",
+        "//upb/mini_table",
         "//upb/reflection",
         "//upb/reflection:internal_cc",
         "//upb/reflection:reflection_cc",
diff --git a/upb/json/decode.c b/upb/json/decode.c
index 6a78580..c7a44d6 100644
--- a/upb/json/decode.c
+++ b/upb/json/decode.c
@@ -64,8 +64,6 @@
 static void jsondec_wellknown(jsondec* d, upb_Message* msg,
                               const upb_MessageDef* m);
 static upb_JsonMessageValue jsondec_value(jsondec* d, const upb_FieldDef* f);
-static void jsondec_wellknownvalue(jsondec* d, upb_Message* msg,
-                                   const upb_MessageDef* m);
 static void jsondec_object(jsondec* d, upb_Message* msg,
                            const upb_MessageDef* m);
 
@@ -1243,7 +1241,7 @@
     upb_MessageValue value;
     value.msg_val = value_msg;
     jsondec_checkoom(d, upb_Array_Append(values, value, d->arena));
-    jsondec_wellknownvalue(d, value_msg, value_m);
+    jsondec_tomsg(d, value_msg, value_m);
   }
   jsondec_arrend(d);
 }
@@ -1268,7 +1266,7 @@
     value.msg_val = value_msg;
     jsondec_checkoom(d, upb_Map_Set(fields, key, value, d->arena));
     jsondec_entrysep(d);
-    jsondec_wellknownvalue(d, value_msg, value_m);
+    jsondec_tomsg(d, value_msg, value_m);
   }
   jsondec_objend(d);
 }
@@ -1315,14 +1313,14 @@
       f = upb_MessageDef_FindFieldByNumber(m, 5);
       submsg = upb_Message_Mutable(msg, f, d->arena).msg;
       jsondec_checkoom(d, submsg);
-      jsondec_struct(d, submsg, upb_FieldDef_MessageSubDef(f));
+      jsondec_tomsg(d, submsg, upb_FieldDef_MessageSubDef(f));
       return;
     case JD_ARRAY:
       /* ListValue list_value = 6; */
       f = upb_MessageDef_FindFieldByNumber(m, 6);
       submsg = upb_Message_Mutable(msg, f, d->arena).msg;
       jsondec_checkoom(d, submsg);
-      jsondec_listvalue(d, submsg, upb_FieldDef_MessageSubDef(f));
+      jsondec_tomsg(d, submsg, upb_FieldDef_MessageSubDef(f));
       return;
     default:
       UPB_UNREACHABLE();
diff --git a/upb/json/decode_test.cc b/upb/json/decode_test.cc
index d6b5a77..a0ec244 100644
--- a/upb/json/decode_test.cc
+++ b/upb/json/decode_test.cc
@@ -14,16 +14,20 @@
 
 #include "google/protobuf/timestamp.upb.h"
 #include "google/protobuf/timestamp.upbdefs.h"
+#include "google/protobuf/descriptor.upb.h"
 #include <gtest/gtest.h>
 #include "google/protobuf/json/json_enumval_custom_string.upb.h"
 #include "google/protobuf/json/json_enumval_custom_string.upbdefs.h"
 #include "upb/base/status.hpp"
+#include "upb/base/string_view.h"
 #include "upb/base/upcast.h"
+#include "upb/json/encode.h"
 #include "upb/json/test.upb.h"
 #include "upb/json/test.upbdefs.h"
 #include "upb/mem/arena.h"
 #include "upb/mem/arena.hpp"
 #include "upb/message/message.h"
+#include "upb/mini_table/message.h"
 #include "upb/reflection/def.h"
 #include "upb/reflection/def.hpp"
 
@@ -482,3 +486,76 @@
         std::string::npos);
   }
 }
+
+namespace {
+
+void AddField(google_protobuf_DescriptorProto* msg, upb_Arena* arena, const char* name,
+              int32_t label, int32_t type, const char* type_name = nullptr) {
+  google_protobuf_FieldDescriptorProto* f = google_protobuf_DescriptorProto_add_field(msg, arena);
+  google_protobuf_FieldDescriptorProto_set_name(f, upb_StringView_FromString(name));
+  google_protobuf_FieldDescriptorProto_set_number(f, 1);
+  google_protobuf_FieldDescriptorProto_set_label(f, label);
+  google_protobuf_FieldDescriptorProto_set_type(f, type);
+  if (type_name != nullptr) {
+    google_protobuf_FieldDescriptorProto_set_type_name(
+        f, upb_StringView_FromString(type_name));
+  }
+}
+
+TEST(JsonTest, NonCanonicalWellKnownTypesRoundTripAsRegularMessages) {
+  upb::Arena arena;
+  upb::DefPool pool;
+  upb::Status status;
+
+  google_protobuf_FileDescriptorProto* file =
+      google_protobuf_FileDescriptorProto_new(arena.ptr());
+  google_protobuf_FileDescriptorProto_set_name(file, upb_StringView_FromString("f"));
+  google_protobuf_FileDescriptorProto_set_package(
+      file, upb_StringView_FromString("google.protobuf"));
+  google_protobuf_FileDescriptorProto_set_syntax(file,
+                                        upb_StringView_FromString("proto3"));
+
+  // Non-canonical Value (singular string field 1 instead of 6-arm kind oneof)
+  // paired with a canonical ListValue (repeated Value values = 1).
+  google_protobuf_DescriptorProto* val_m =
+      google_protobuf_FileDescriptorProto_add_message_type(file, arena.ptr());
+  google_protobuf_DescriptorProto_set_name(val_m, upb_StringView_FromString("Value"));
+  AddField(val_m, arena.ptr(), "x", google_protobuf_FieldDescriptorProto_LABEL_OPTIONAL,
+           google_protobuf_FieldDescriptorProto_TYPE_STRING);
+
+  google_protobuf_DescriptorProto* list_m =
+      google_protobuf_FileDescriptorProto_add_message_type(file, arena.ptr());
+  google_protobuf_DescriptorProto_set_name(list_m,
+                                  upb_StringView_FromString("ListValue"));
+  AddField(list_m, arena.ptr(), "values",
+           google_protobuf_FieldDescriptorProto_LABEL_REPEATED,
+           google_protobuf_FieldDescriptorProto_TYPE_MESSAGE, ".google.protobuf.Value");
+
+  ASSERT_NE(upb_DefPool_AddFile(pool.ptr(), file, status.ptr()), nullptr)
+      << status.error_message();
+
+  const upb_MessageDef* v_def =
+      upb_DefPool_FindMessageByName(pool.ptr(), "google.protobuf.Value");
+  const upb_MessageDef* l_def =
+      upb_DefPool_FindMessageByName(pool.ptr(), "google.protobuf.ListValue");
+  EXPECT_EQ(upb_MessageDef_WellKnownType(v_def), kUpb_WellKnown_Unspecified);
+  EXPECT_EQ(upb_MessageDef_WellKnownType(l_def), kUpb_WellKnown_ListValue);
+
+  const upb_MiniTable* mt = upb_MessageDef_MiniTable(l_def);
+  EXPECT_FALSE(upb_JsonDecode("[1]", 3, upb_Message_New(mt, arena.ptr()), l_def,
+                              pool.ptr(), 0, arena.ptr(), status.ptr()));
+  status.Clear();
+  upb_Message* msg = upb_Message_New(mt, arena.ptr());
+  static constexpr char kJson[] = R"([{"x":"ok"}])";
+  ASSERT_TRUE(upb_JsonDecode(kJson, strlen(kJson), msg, l_def, pool.ptr(), 0,
+                             arena.ptr(), status.ptr()))
+      << status.error_message();
+  char buf[64];
+  ASSERT_EQ(
+      upb_JsonEncode(msg, l_def, pool.ptr(), 0, buf, sizeof(buf), status.ptr()),
+      strlen(kJson))
+      << status.error_message();
+  EXPECT_STREQ(buf, kJson);
+}
+
+}  // namespace
diff --git a/upb/json/encode.c b/upb/json/encode.c
index 813a648..12ee5c6 100644
--- a/upb/json/encode.c
+++ b/upb/json/encode.c
@@ -52,8 +52,6 @@
                              const upb_MessageDef* m);
 static void jsonenc_msgfields(jsonenc* e, const upb_Message* msg,
                               const upb_MessageDef* m, bool first);
-static void jsonenc_value(jsonenc* e, const upb_Message* msg,
-                          const upb_MessageDef* m);
 static void jsonenc_string(jsonenc* e, upb_StringView str);
 
 UPB_NORETURN static void jsonenc_err(jsonenc* e, const char* msg) {
@@ -514,7 +512,7 @@
       jsonenc_putsep(e, ",", &first);
       jsonenc_string(e, key.str_val);
       jsonenc_putstr(e, ":");
-      jsonenc_value(e, val.msg_val, upb_FieldDef_MessageSubDef(value_f));
+      jsonenc_msgfield(e, val.msg_val, upb_FieldDef_MessageSubDef(value_f));
     }
   }
 
@@ -539,7 +537,7 @@
       upb_MessageValue elem = upb_Array_Get(values, i);
 
       jsonenc_putsep(e, ",", &first);
-      jsonenc_value(e, elem.msg_val, values_m);
+      jsonenc_msgfield(e, elem.msg_val, values_m);
     }
   }
 
@@ -578,10 +576,8 @@
       jsonenc_putstr(e, val.bool_val ? "true" : "false");
       break;
     case 5:
-      jsonenc_struct(e, val.msg_val, upb_FieldDef_MessageSubDef(f));
-      break;
     case 6:
-      jsonenc_listvalue(e, val.msg_val, upb_FieldDef_MessageSubDef(f));
+      jsonenc_msgfield(e, val.msg_val, upb_FieldDef_MessageSubDef(f));
       break;
   }
 }
diff --git a/upb/reflection/message_def.c b/upb/reflection/message_def.c
index 8a0e562..6699f81 100644
--- a/upb/reflection/message_def.c
+++ b/upb/reflection/message_def.c
@@ -84,46 +84,121 @@
   google_protobuf_SymbolVisibility visibility;
 };
 
+static bool has_wkt_field(const upb_MessageDef* m, uint32_t num,
+                          upb_Label label, upb_FieldType type) {
+  const upb_FieldDef* f = upb_MessageDef_FindFieldByNumber(m, num);
+  return f != NULL && upb_FieldDef_Label(f) == label &&
+         upb_FieldDef_Type(f) == type;
+}
+
+static bool has_wkt_submsg(const upb_FieldDef* f, const char* full_name) {
+  if (upb_FieldDef_Type(f) != kUpb_FieldType_Message) return false;
+  const upb_MessageDef* sub = upb_FieldDef_MessageSubDef(f);
+  return sub->containing_type == NULL && !upb_MessageDef_IsMapEntry(sub) &&
+         strcmp(sub->full_name, full_name) == 0;
+}
+
+static bool check_wkt1(const upb_MessageDef* m, upb_Label label,
+                       upb_FieldType type) {
+  return m->field_count == 1 && m->real_oneof_count == 0 &&
+         has_wkt_field(m, 1, label, type);
+}
+
+static bool check_wkt2(const upb_MessageDef* m, upb_FieldType t1,
+                       upb_FieldType t2) {
+  return m->field_count == 2 && m->real_oneof_count == 0 &&
+         has_wkt_field(m, 1, kUpb_Label_Optional, t1) &&
+         has_wkt_field(m, 2, kUpb_Label_Optional, t2);
+}
+
 static void assign_msg_wellknowntype(upb_MessageDef* m) {
-  const char* name = m->full_name;
-  if (name == NULL) {
-    m->well_known_type = kUpb_WellKnown_Unspecified;
+  m->well_known_type = kUpb_WellKnown_Unspecified;
+  if (m->full_name == NULL || m->containing_type != NULL ||
+      upb_MessageDef_IsMapEntry(m)) {
     return;
   }
-  if (!strcmp(name, "google.protobuf.Any")) {
-    m->well_known_type = kUpb_WellKnown_Any;
-  } else if (!strcmp(name, "google.protobuf.FieldMask")) {
-    m->well_known_type = kUpb_WellKnown_FieldMask;
-  } else if (!strcmp(name, "google.protobuf.Duration")) {
-    m->well_known_type = kUpb_WellKnown_Duration;
-  } else if (!strcmp(name, "google.protobuf.Timestamp")) {
-    m->well_known_type = kUpb_WellKnown_Timestamp;
-  } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
-    m->well_known_type = kUpb_WellKnown_DoubleValue;
-  } else if (!strcmp(name, "google.protobuf.FloatValue")) {
-    m->well_known_type = kUpb_WellKnown_FloatValue;
-  } else if (!strcmp(name, "google.protobuf.Int64Value")) {
-    m->well_known_type = kUpb_WellKnown_Int64Value;
-  } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
-    m->well_known_type = kUpb_WellKnown_UInt64Value;
-  } else if (!strcmp(name, "google.protobuf.Int32Value")) {
-    m->well_known_type = kUpb_WellKnown_Int32Value;
-  } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
-    m->well_known_type = kUpb_WellKnown_UInt32Value;
-  } else if (!strcmp(name, "google.protobuf.BoolValue")) {
-    m->well_known_type = kUpb_WellKnown_BoolValue;
-  } else if (!strcmp(name, "google.protobuf.StringValue")) {
-    m->well_known_type = kUpb_WellKnown_StringValue;
-  } else if (!strcmp(name, "google.protobuf.BytesValue")) {
-    m->well_known_type = kUpb_WellKnown_BytesValue;
-  } else if (!strcmp(name, "google.protobuf.Value")) {
-    m->well_known_type = kUpb_WellKnown_Value;
-  } else if (!strcmp(name, "google.protobuf.ListValue")) {
-    m->well_known_type = kUpb_WellKnown_ListValue;
-  } else if (!strcmp(name, "google.protobuf.Struct")) {
-    m->well_known_type = kUpb_WellKnown_Struct;
+  static const char kPrefix[] = "google.protobuf.";
+  if (strncmp(m->full_name, kPrefix, sizeof(kPrefix) - 1) != 0) return;
+  const char* name = m->full_name + (sizeof(kPrefix) - 1);
+
+  if (!strcmp(name, "Any")) {
+    if (check_wkt2(m, kUpb_FieldType_String, kUpb_FieldType_Bytes)) {
+      m->well_known_type = kUpb_WellKnown_Any;
+    }
+  } else if (!strcmp(name, "FieldMask")) {
+    if (check_wkt1(m, kUpb_Label_Repeated, kUpb_FieldType_String)) {
+      m->well_known_type = kUpb_WellKnown_FieldMask;
+    }
+  } else if (!strcmp(name, "Duration")) {
+    if (check_wkt2(m, kUpb_FieldType_Int64, kUpb_FieldType_Int32)) {
+      m->well_known_type = kUpb_WellKnown_Duration;
+    }
+  } else if (!strcmp(name, "Timestamp")) {
+    if (check_wkt2(m, kUpb_FieldType_Int64, kUpb_FieldType_Int32)) {
+      m->well_known_type = kUpb_WellKnown_Timestamp;
+    }
+  } else if (!strcmp(name, "ListValue")) {
+    if (check_wkt1(m, kUpb_Label_Repeated, kUpb_FieldType_Message) &&
+        has_wkt_submsg(upb_MessageDef_Field(m, 0), "google.protobuf.Value")) {
+      m->well_known_type = kUpb_WellKnown_ListValue;
+    }
+  } else if (!strcmp(name, "Struct")) {
+    const upb_FieldDef* f = upb_MessageDef_FindFieldByNumber(m, 1);
+    if (m->field_count == 1 && m->real_oneof_count == 0 && f != NULL &&
+        upb_FieldDef_IsMap(f) &&
+        upb_FieldDef_Type(f) == kUpb_FieldType_Message &&
+        strcmp(upb_FieldDef_Name(f), "fields") == 0) {
+      const upb_MessageDef* entry = upb_FieldDef_MessageSubDef(f);
+      if (entry->containing_type == m &&
+          upb_FieldDef_Type(upb_MessageDef_Field(entry, 0)) ==
+              kUpb_FieldType_String &&
+          has_wkt_submsg(upb_MessageDef_Field(entry, 1),
+                         "google.protobuf.Value")) {
+        m->well_known_type = kUpb_WellKnown_Struct;
+      }
+    }
+  } else if (!strcmp(name, "Value")) {
+    static const upb_FieldType kTypes[6] = {
+        kUpb_FieldType_Enum, kUpb_FieldType_Double,  kUpb_FieldType_String,
+        kUpb_FieldType_Bool, kUpb_FieldType_Message, kUpb_FieldType_Message,
+    };
+    if (m->field_count == 6 && m->oneof_count == 1 &&
+        m->real_oneof_count == 1 &&
+        upb_OneofDef_FieldCount(upb_MessageDef_Oneof(m, 0)) == 6) {
+      for (int i = 0; i < 6; i++) {
+        if (!has_wkt_field(m, i + 1, kUpb_Label_Optional, kTypes[i])) return;
+      }
+      if (has_wkt_submsg(upb_MessageDef_FindFieldByNumber(m, 5),
+                         "google.protobuf.Struct") &&
+          has_wkt_submsg(upb_MessageDef_FindFieldByNumber(m, 6),
+                         "google.protobuf.ListValue")) {
+        m->well_known_type = kUpb_WellKnown_Value;
+      }
+    }
   } else {
-    m->well_known_type = kUpb_WellKnown_Unspecified;
+    static const struct {
+      const char* name;
+      upb_FieldType type;
+      upb_WellKnown wkt;
+    } kWrappers[] = {
+        {"DoubleValue", kUpb_FieldType_Double, kUpb_WellKnown_DoubleValue},
+        {"FloatValue", kUpb_FieldType_Float, kUpb_WellKnown_FloatValue},
+        {"Int64Value", kUpb_FieldType_Int64, kUpb_WellKnown_Int64Value},
+        {"UInt64Value", kUpb_FieldType_UInt64, kUpb_WellKnown_UInt64Value},
+        {"Int32Value", kUpb_FieldType_Int32, kUpb_WellKnown_Int32Value},
+        {"UInt32Value", kUpb_FieldType_UInt32, kUpb_WellKnown_UInt32Value},
+        {"BoolValue", kUpb_FieldType_Bool, kUpb_WellKnown_BoolValue},
+        {"StringValue", kUpb_FieldType_String, kUpb_WellKnown_StringValue},
+        {"BytesValue", kUpb_FieldType_Bytes, kUpb_WellKnown_BytesValue},
+    };
+    for (size_t i = 0; i < sizeof(kWrappers) / sizeof(kWrappers[0]); i++) {
+      if (!strcmp(name, kWrappers[i].name)) {
+        if (check_wkt1(m, kUpb_Label_Optional, kWrappers[i].type)) {
+          m->well_known_type = kWrappers[i].wkt;
+        }
+        return;
+      }
+    }
   }
 }
 
@@ -467,6 +542,8 @@
     upb_MessageDef* n = (upb_MessageDef*)upb_MessageDef_NestedMessage(m, i);
     _upb_MessageDef_Resolve(ctx, n);
   }
+
+  assign_msg_wellknowntype(m);
 }
 
 void _upb_MessageDef_InsertField(upb_DefBuilder* ctx, upb_MessageDef* m,
@@ -820,7 +897,7 @@
   const size_t synthetic_count = _upb_OneofDefs_Finalize(ctx, m);
   m->real_oneof_count = m->oneof_count - synthetic_count;
 
-  assign_msg_wellknowntype(m);
+  m->well_known_type = kUpb_WellKnown_Unspecified;
 
   const google_protobuf_EnumDescriptorProto* const* enums =
       google_protobuf_DescriptorProto_enum_type(msg_proto, &n_enum);
diff --git a/upb/reflection/reflection_test.cc b/upb/reflection/reflection_test.cc
index 3d3bc22..279df98 100644
--- a/upb/reflection/reflection_test.cc
+++ b/upb/reflection/reflection_test.cc
@@ -1006,5 +1006,184 @@
   }
 }
 
+TEST(ReflectionTest, ValidateWellKnownTypes) {
+  absl::StatusOr<upb::DefPool> valid_pool = LoadDescriptorProto(R"(
+    syntax: "proto3" name: "wkt.proto" package: "google.protobuf"
+    enum_type { name: "NullValue" value { name: "NULL_VALUE" number: 0 } }
+    message_type { name: "Any"
+      field { name: "type_url" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING }
+      field { name: "value" number: 2 label: LABEL_OPTIONAL type: TYPE_BYTES } }
+    message_type { name: "FieldMask"
+      field { name: "paths" number: 1 label: LABEL_REPEATED type: TYPE_STRING } }
+    message_type { name: "Duration"
+      field { name: "seconds" number: 1 label: LABEL_OPTIONAL type: TYPE_INT64 }
+      field { name: "nanos" number: 2 label: LABEL_OPTIONAL type: TYPE_INT32 } }
+    message_type { name: "Timestamp"
+      field { name: "seconds" number: 1 label: LABEL_OPTIONAL type: TYPE_INT64 }
+      field { name: "nanos" number: 2 label: LABEL_OPTIONAL type: TYPE_INT32 } }
+    message_type { name: "DoubleValue"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_DOUBLE } }
+    message_type { name: "FloatValue"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_FLOAT } }
+    message_type { name: "Int64Value"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_INT64 } }
+    message_type { name: "UInt64Value"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_UINT64 } }
+    message_type { name: "Int32Value"
+      oneof_decl { name: "_value" }
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32
+              oneof_index: 0 proto3_optional: true } }
+    message_type { name: "UInt32Value"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_UINT32 } }
+    message_type { name: "BoolValue"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_BOOL } }
+    message_type { name: "StringValue"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING } }
+    message_type { name: "BytesValue"
+      field { name: "value" number: 1 label: LABEL_OPTIONAL type: TYPE_BYTES } }
+    message_type { name: "Struct"
+      field { name: "fields" number: 1 label: LABEL_REPEATED type: TYPE_MESSAGE
+              type_name: ".google.protobuf.Struct.FieldsEntry" }
+      nested_type { name: "FieldsEntry" options { map_entry: true }
+        field { name: "key" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING }
+        field { name: "value" number: 2 label: LABEL_OPTIONAL type: TYPE_MESSAGE
+                type_name: ".google.protobuf.Value" } } }
+    message_type { name: "Value" oneof_decl { name: "kind" }
+      field { name: "null_value" number: 1 label: LABEL_OPTIONAL type: TYPE_ENUM
+              type_name: ".google.protobuf.NullValue" oneof_index: 0 }
+      field { name: "number_value" number: 2 label: LABEL_OPTIONAL
+              type: TYPE_DOUBLE oneof_index: 0 }
+      field { name: "string_value" number: 3 label: LABEL_OPTIONAL
+              type: TYPE_STRING oneof_index: 0 }
+      field { name: "bool_value" number: 4 label: LABEL_OPTIONAL type: TYPE_BOOL
+              oneof_index: 0 }
+      field { name: "struct_value" number: 5 label: LABEL_OPTIONAL
+              type: TYPE_MESSAGE type_name: ".google.protobuf.Struct"
+              oneof_index: 0 }
+      field { name: "list_value" number: 6 label: LABEL_OPTIONAL
+              type: TYPE_MESSAGE type_name: ".google.protobuf.ListValue"
+              oneof_index: 0 } }
+    message_type { name: "ListValue"
+      field { name: "values" number: 1 label: LABEL_REPEATED type: TYPE_MESSAGE
+              type_name: ".google.protobuf.Value" } }
+  )");
+  ASSERT_TRUE(valid_pool.ok()) << valid_pool.status();
+
+  const struct {
+    const char* name;
+    upb_WellKnown expected;
+  } kExpected[] = {
+      {"google.protobuf.Any", kUpb_WellKnown_Any},
+      {"google.protobuf.FieldMask", kUpb_WellKnown_FieldMask},
+      {"google.protobuf.Duration", kUpb_WellKnown_Duration},
+      {"google.protobuf.Timestamp", kUpb_WellKnown_Timestamp},
+      {"google.protobuf.DoubleValue", kUpb_WellKnown_DoubleValue},
+      {"google.protobuf.FloatValue", kUpb_WellKnown_FloatValue},
+      {"google.protobuf.Int64Value", kUpb_WellKnown_Int64Value},
+      {"google.protobuf.UInt64Value", kUpb_WellKnown_UInt64Value},
+      {"google.protobuf.Int32Value", kUpb_WellKnown_Int32Value},
+      {"google.protobuf.UInt32Value", kUpb_WellKnown_UInt32Value},
+      {"google.protobuf.BoolValue", kUpb_WellKnown_BoolValue},
+      {"google.protobuf.StringValue", kUpb_WellKnown_StringValue},
+      {"google.protobuf.BytesValue", kUpb_WellKnown_BytesValue},
+      {"google.protobuf.Value", kUpb_WellKnown_Value},
+      {"google.protobuf.ListValue", kUpb_WellKnown_ListValue},
+      {"google.protobuf.Struct", kUpb_WellKnown_Struct},
+  };
+  for (const auto& tc : kExpected) {
+    SCOPED_TRACE(tc.name);
+    EXPECT_EQ(valid_pool->FindMessageByName(tc.name).wellknowntype(),
+              tc.expected);
+  }
+
+  const struct {
+    const char* name;
+    std::string_view file_body;
+  } kNonCanonicalCases[] = {
+      {"google.protobuf.Any",
+       "package: 'google.protobuf' message_type { name: 'Any' "
+       "field { name: 'type_url' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_STRING } }"},
+      {"google.protobuf.Any",
+       "package: 'google.protobuf' message_type { name: 'Any' "
+       "options { map_entry: true } "
+       "field { name: 'key' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_STRING } "
+       "field { name: 'value' number: 2 label: LABEL_OPTIONAL "
+       "type: TYPE_BYTES } }"},
+      {"google.protobuf.FieldMask",
+       "package: 'google.protobuf' message_type { name: 'FieldMask' "
+       "field { name: 'paths' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_STRING } }"},
+      {"google.protobuf.Timestamp",
+       "package: 'google.protobuf' message_type { name: 'Timestamp' "
+       "field { name: 'seconds' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_SINT64 } "
+       "field { name: 'nanos' number: 2 label: LABEL_OPTIONAL "
+       "type: TYPE_INT32 } }"},
+      {"google.protobuf.Duration",
+       "package: 'google.protobuf' message_type { name: 'Duration' "
+       "oneof_decl { name: 'o' } "
+       "field { name: 'seconds' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_INT64 oneof_index: 0 } "
+       "field { name: 'nanos' number: 2 label: LABEL_OPTIONAL "
+       "type: TYPE_INT32 } }"},
+      {"google.protobuf.Int32Value",
+       "package: 'google.protobuf' message_type { name: 'Int32Value' "
+       "field { name: 'value' number: 1 label: LABEL_REQUIRED "
+       "type: TYPE_INT32 } }"},
+      {"google.protobuf.Struct",
+       "package: 'google.protobuf' message_type { name: 'Value' } "
+       "message_type { name: 'Struct' "
+       "field { name: 'wrong_name' number: 1 label: LABEL_REPEATED "
+       "type: TYPE_MESSAGE type_name: '.google.protobuf.Struct.E' } "
+       "nested_type { name: 'E' options { map_entry: true } "
+       "field { name: 'key' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_STRING } "
+       "field { name: 'value' number: 2 label: LABEL_OPTIONAL "
+       "type: TYPE_MESSAGE type_name: '.google.protobuf.Value' } } }"},
+      {"google.protobuf.Struct",
+       "package: 'google.protobuf' message_type { name: 'Value' } "
+       "message_type { name: 'Struct' "
+       "field { name: 'fields' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_MESSAGE type_name: '.google.protobuf.Value' } }"},
+      {"google.protobuf.ListValue",
+       "package: 'google.protobuf' message_type { name: 'Sub' } "
+       "message_type { name: 'ListValue' "
+       "field { name: 'values' number: 1 label: LABEL_REPEATED "
+       "type: TYPE_MESSAGE type_name: '.google.protobuf.Sub' } }"},
+      {"google.protobuf.Value",
+       "package: 'google.protobuf' "
+       "enum_type { name: 'NullValue' value { name: 'N' number: 0 } } "
+       "message_type { name: 'ListValue' } "
+       "message_type { name: 'Value' oneof_decl { name: 'kind' } "
+       "field { name: 'a' number: 1 label: LABEL_OPTIONAL type: TYPE_ENUM "
+       "type_name: '.google.protobuf.NullValue' oneof_index: 0 } "
+       "field { name: 'b' number: 2 label: LABEL_OPTIONAL type: TYPE_DOUBLE "
+       "oneof_index: 0 } "
+       "field { name: 'c' number: 3 label: LABEL_OPTIONAL type: TYPE_STRING "
+       "oneof_index: 0 } "
+       "field { name: 'd' number: 4 label: LABEL_OPTIONAL type: TYPE_BOOL "
+       "oneof_index: 0 } "
+       "field { name: 'e' number: 5 label: LABEL_OPTIONAL type: TYPE_MESSAGE "
+       "type_name: '.google.protobuf.Value' oneof_index: 0 } "
+       "field { name: 'f' number: 6 label: LABEL_OPTIONAL type: TYPE_MESSAGE "
+       "type_name: '.google.protobuf.ListValue' oneof_index: 0 } }"},
+      {"google.protobuf.BoolValue",
+       "package: 'google' message_type { name: 'protobuf' "
+       "nested_type { name: 'BoolValue' "
+       "field { name: 'value' number: 1 label: LABEL_OPTIONAL "
+       "type: TYPE_BOOL } } }"},
+  };
+  for (const auto& tc : kNonCanonicalCases) {
+    SCOPED_TRACE(tc.file_body);
+    absl::StatusOr<upb::DefPool> pool = LoadDescriptorProto(
+        absl::StrFormat("syntax: 'proto2' name: 'f.proto' %s", tc.file_body));
+    ASSERT_TRUE(pool.ok()) << pool.status();
+    EXPECT_EQ(pool->FindMessageByName(tc.name).wellknowntype(),
+              kUpb_WellKnown_Unspecified);
+  }
+}
+
 }  // namespace
 }  // namespace upb_test