pbdump.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // pbdump is a tool for decoding the wire format for protocol buffer messages.
  5. package main
  6. import (
  7. "bytes"
  8. "flag"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "os"
  13. "path/filepath"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "google.golang.org/protobuf/internal/encoding/pack"
  18. "google.golang.org/protobuf/internal/encoding/wire"
  19. "google.golang.org/protobuf/internal/errors"
  20. "google.golang.org/protobuf/proto"
  21. "google.golang.org/protobuf/reflect/protodesc"
  22. "google.golang.org/protobuf/reflect/protoreflect"
  23. "google.golang.org/protobuf/types/descriptorpb"
  24. )
  25. func main() {
  26. log.SetFlags(0)
  27. log.SetOutput(os.Stderr)
  28. var fs fields
  29. var flagUsages []string
  30. flagVar := func(value flag.Value, name, usage string) {
  31. flagUsages = append(flagUsages, fmt.Sprintf(" -%-16v %v", name+" "+value.String(), usage))
  32. flag.Var(value, name, usage)
  33. }
  34. flagBool := func(name, usage string) *bool {
  35. flagUsages = append(flagUsages, fmt.Sprintf(" -%-16v %v", name, usage))
  36. return flag.Bool(name, false, usage)
  37. }
  38. flagVar(fieldsFlag{&fs, protoreflect.BoolKind}, "bools", "List of bool fields")
  39. flagVar(fieldsFlag{&fs, protoreflect.Int64Kind}, "ints", "List of int32 or int64 fields")
  40. flagVar(fieldsFlag{&fs, protoreflect.Sint64Kind}, "sints", "List of sint32 or sint64 fields")
  41. flagVar(fieldsFlag{&fs, protoreflect.Uint64Kind}, "uints", "List of enum, uint32, or uint64 fields")
  42. flagVar(fieldsFlag{&fs, protoreflect.Fixed32Kind}, "uint32s", "List of fixed32 fields")
  43. flagVar(fieldsFlag{&fs, protoreflect.Sfixed32Kind}, "int32s", "List of sfixed32 fields")
  44. flagVar(fieldsFlag{&fs, protoreflect.FloatKind}, "float32s", "List of float fields")
  45. flagVar(fieldsFlag{&fs, protoreflect.Fixed64Kind}, "uint64s", "List of fixed64 fields")
  46. flagVar(fieldsFlag{&fs, protoreflect.Sfixed64Kind}, "int64s", "List of sfixed64 fields")
  47. flagVar(fieldsFlag{&fs, protoreflect.DoubleKind}, "float64s", "List of double fields")
  48. flagVar(fieldsFlag{&fs, protoreflect.StringKind}, "strings", "List of string fields")
  49. flagVar(fieldsFlag{&fs, protoreflect.BytesKind}, "bytes", "List of bytes fields")
  50. flagVar(fieldsFlag{&fs, protoreflect.MessageKind}, "messages", "List of message fields")
  51. flagVar(fieldsFlag{&fs, protoreflect.GroupKind}, "groups", "List of group fields")
  52. printDesc := flagBool("print_descriptor", "Print the message descriptor")
  53. printSource := flagBool("print_source", "Print the output in valid Go syntax")
  54. flag.Usage = func() {
  55. fmt.Printf("Usage: %s [OPTIONS]... [INPUTS]...\n\n%s\n", filepath.Base(os.Args[0]), strings.Join(append([]string{
  56. "Print structured representations of encoded protocol buffer messages.",
  57. "Since the protobuf wire format is not fully self-describing, type information",
  58. "about the proto message can be provided using flags (e.g., -messages).",
  59. "Each field list is a comma-separated list of field identifiers,",
  60. "where each field identifier is a dot-separated list of field numbers,",
  61. "identifying each field relative to the root message.",
  62. "",
  63. "For example, \"-messages 1,3,3.1 -float32s 1.2 -bools 3.1.2\" represents:",
  64. "",
  65. " message M {",
  66. " optional M1 f1 = 1; // -messages 1",
  67. " message M1 {",
  68. " repeated float f2 = 2; // -float32s 1.2",
  69. " }",
  70. " optional M3 f3 = 3; // -messages 3",
  71. " message M3 {",
  72. " optional M1 f1 = 1; // -messages 3.1",
  73. " message M1 {",
  74. " repeated bool f2 = 2; // -bools 3.1.2",
  75. " }",
  76. " }",
  77. " }",
  78. "",
  79. "Arbitrarily complex message schemas can be represented using these flags.",
  80. "Scalar field types are marked as repeated so that pbdump can decode",
  81. "the packed representations of such field types.",
  82. "",
  83. "If no inputs are specified, the wire data is read in from stdin, otherwise",
  84. "the contents of each specified input file is concatenated and",
  85. "treated as one large message.",
  86. "",
  87. "Options:",
  88. }, flagUsages...), "\n"))
  89. }
  90. flag.Parse()
  91. // Create message types.
  92. var desc protoreflect.MessageDescriptor
  93. if len(fs) > 0 {
  94. var err error
  95. desc, err = fs.Descriptor()
  96. if err != nil {
  97. log.Fatalf("Descriptor error: %v", err)
  98. }
  99. if *printDesc {
  100. fmt.Printf("%#v\n", desc)
  101. }
  102. }
  103. // Read message input.
  104. var buf []byte
  105. if flag.NArg() == 0 {
  106. b, err := ioutil.ReadAll(os.Stdin)
  107. if err != nil {
  108. log.Fatalf("ReadAll error: %v", err)
  109. }
  110. buf = b
  111. }
  112. for _, f := range flag.Args() {
  113. b, err := ioutil.ReadFile(f)
  114. if err != nil {
  115. log.Fatalf("ReadFile error: %v", err)
  116. }
  117. buf = append(buf, b...)
  118. }
  119. // Parse and print message structure.
  120. defer log.Printf("fatal input: %q", buf) // debug printout if panic occurs
  121. var m pack.Message
  122. m.UnmarshalDescriptor(buf, desc)
  123. if *printSource {
  124. fmt.Printf("%#v\n", m)
  125. } else {
  126. fmt.Printf("%+v\n", m)
  127. }
  128. if !bytes.Equal(buf, m.Marshal()) || len(buf) != m.Size() {
  129. log.Fatalf("roundtrip mismatch:\n\tgot: %d %x\n\twant: %d %x", m.Size(), m, len(buf), buf)
  130. }
  131. os.Exit(0) // exit cleanly, avoid debug printout
  132. }
  133. // fields is a tree of fields, keyed by a field number.
  134. // Fields representing messages or groups have sub-fields.
  135. type fields map[wire.Number]*field
  136. type field struct {
  137. kind protoreflect.Kind
  138. sub fields // only for MessageKind or GroupKind
  139. }
  140. // Set parses s as a comma-separated list (see the help above for the format)
  141. // and treats each field identifier as the specified kind.
  142. func (fs *fields) Set(s string, k protoreflect.Kind) error {
  143. if *fs == nil {
  144. *fs = make(fields)
  145. }
  146. for _, s := range strings.Split(s, ",") {
  147. if err := fs.set("", strings.TrimSpace(s), k); err != nil {
  148. return err
  149. }
  150. }
  151. return nil
  152. }
  153. func (fs fields) set(prefix, s string, k protoreflect.Kind) error {
  154. if s == "" {
  155. return nil
  156. }
  157. // Parse next field number.
  158. i := strings.IndexByte(s, '.')
  159. if i < 0 {
  160. i = len(s)
  161. }
  162. prefix = strings.TrimPrefix(prefix+"."+s[:i], ".")
  163. n, _ := strconv.ParseInt(s[:i], 10, 32)
  164. num := wire.Number(n)
  165. if num < wire.MinValidNumber || wire.MaxValidNumber < num {
  166. return errors.New("invalid field: %v", prefix)
  167. }
  168. s = strings.TrimPrefix(s[i:], ".")
  169. // Handle the current field.
  170. if fs[num] == nil {
  171. fs[num] = &field{0, make(fields)}
  172. }
  173. if len(s) == 0 {
  174. if fs[num].kind.IsValid() {
  175. return errors.New("field %v already set as %v type", prefix, fs[num].kind)
  176. }
  177. fs[num].kind = k
  178. }
  179. if err := fs[num].sub.set(prefix, s, k); err != nil {
  180. return err
  181. }
  182. // Verify that only messages or groups can have sub-fields.
  183. k2 := fs[num].kind
  184. if k2 > 0 && k2 != protoreflect.MessageKind && k2 != protoreflect.GroupKind && len(fs[num].sub) > 0 {
  185. return errors.New("field %v of %v type cannot have sub-fields", prefix, k2)
  186. }
  187. return nil
  188. }
  189. // Descriptor returns the field tree as a message descriptor.
  190. func (fs fields) Descriptor() (protoreflect.MessageDescriptor, error) {
  191. fd, err := protodesc.NewFile(&descriptorpb.FileDescriptorProto{
  192. Name: proto.String("dump.proto"),
  193. Syntax: proto.String("proto2"),
  194. MessageType: []*descriptorpb.DescriptorProto{fs.messageDescriptor("X")},
  195. }, nil)
  196. if err != nil {
  197. return nil, err
  198. }
  199. return fd.Messages().Get(0), nil
  200. }
  201. func (fs fields) messageDescriptor(name protoreflect.FullName) *descriptorpb.DescriptorProto {
  202. m := &descriptorpb.DescriptorProto{Name: proto.String(string(name.Name()))}
  203. for _, n := range fs.sortedNums() {
  204. k := fs[n].kind
  205. if !k.IsValid() {
  206. k = protoreflect.MessageKind
  207. }
  208. f := &descriptorpb.FieldDescriptorProto{
  209. Name: proto.String(fmt.Sprintf("x%d", n)),
  210. Number: proto.Int32(int32(n)),
  211. Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
  212. Type: descriptorpb.FieldDescriptorProto_Type(k).Enum(),
  213. }
  214. switch k {
  215. case protoreflect.BoolKind, protoreflect.EnumKind,
  216. protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Uint32Kind,
  217. protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Uint64Kind,
  218. protoreflect.Sfixed32Kind, protoreflect.Fixed32Kind, protoreflect.FloatKind,
  219. protoreflect.Sfixed64Kind, protoreflect.Fixed64Kind, protoreflect.DoubleKind:
  220. f.Label = descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum()
  221. f.Options = &descriptorpb.FieldOptions{Packed: proto.Bool(true)}
  222. case protoreflect.MessageKind, protoreflect.GroupKind:
  223. s := name.Append(protoreflect.Name(fmt.Sprintf("X%d", n)))
  224. f.TypeName = proto.String(string("." + s))
  225. m.NestedType = append(m.NestedType, fs[n].sub.messageDescriptor(s))
  226. }
  227. m.Field = append(m.Field, f)
  228. }
  229. return m
  230. }
  231. func (fs fields) sortedNums() (ns []wire.Number) {
  232. for n := range fs {
  233. ns = append(ns, n)
  234. }
  235. sort.Slice(ns, func(i, j int) bool { return ns[i] < ns[j] })
  236. return ns
  237. }
  238. // fieldsFlag is an implementation of flag.Value that is keyed a specific kind.
  239. type fieldsFlag struct {
  240. f *fields
  241. k protoreflect.Kind
  242. }
  243. func (fs fieldsFlag) String() string { return "FIELDS" }
  244. func (fs fieldsFlag) Set(s string) error { return fs.f.Set(s, fs.k) }