lib: Add -v23.metadata, which dumps metadata for the binary.

The metadata package is a map from string ids to string values,
and provides a mechanism to set the ldflags on the go toolchain
to get metadata linked into your binary during build time.  It
also provides utilities to insert more metadata in package init
functions, and to convert into XML and base64.

Every binary built with the metadata package will now
automatically get a flag -v23.metadata, which dumps the metadata
for the program binary in XML.

The format looks like this:

<metadata>
<md id="build.Manifest"><![CDATA[
<manifest label="">
<imports></imports>
<projects>
<project exclude="false" name="release.go.v23"...
...
</projects>
<tools></tools>
</manifest>
]]></md>
<md id="build.Platform">amd64unknown-linux-unknown</md>
<md id="build.Pristine">false</md>
<md id="build.Time">2015-05-04T08:40:22Z</md>
<md id="build.User">Todd Wang</md>
<md id="go.Arch">amd64</md>
<md id="go.OS">linux</md>
<md id="go.Version">go1.4.1</md>
<md id="v23.RPCEndpointVersion">5</md>
<md id="v23.RPCVersionMax">10</md>
<md id="v23.RPCVersionMin">9</md>
</metadata>

This addresses one part of vanadium/issues#407

MultiPart: 2/3

Change-Id: I234a1dee1221dcda8bc7cfb445a6f53c14857777
diff --git a/buildinfo/.api b/buildinfo/.api
index 5162586..e69de29 100644
--- a/buildinfo/.api
+++ b/buildinfo/.api
@@ -1,9 +0,0 @@
-pkg buildinfo, func Info() *T
-pkg buildinfo, method (*T) String() string
-pkg buildinfo, type T struct
-pkg buildinfo, type T struct, BuildPlatform string
-pkg buildinfo, type T struct, BuildTimestamp time.Time
-pkg buildinfo, type T struct, BuildUser string
-pkg buildinfo, type T struct, GoVersion string
-pkg buildinfo, type T struct, Manifest string
-pkg buildinfo, type T struct, Pristine bool
diff --git a/buildinfo/buildinfo.go b/buildinfo/buildinfo.go
deleted file mode 100644
index 2c3579b..0000000
--- a/buildinfo/buildinfo.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2015 The Vanadium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package buildinfo implements a mechanism for injecting build-time
-// metadata into executable binaries.
-package buildinfo
-
-import (
-	"encoding/base64"
-	"encoding/json"
-	"fmt"
-	"runtime"
-	"strconv"
-	"time"
-)
-
-var (
-	manifest  string
-	platform  string
-	pristine  string
-	timestamp string
-	username  string
-)
-
-// T describes binary metadata.
-type T struct {
-	// BuildPlatform records the target platform of the build.
-	BuildPlatform string
-	// BuildTimestamp records the time of the build.
-	BuildTimestamp time.Time
-	// BuildUser records the name of user who executed the build.
-	BuildUser string
-	// GoVersion records the Go version used for the build.
-	GoVersion string
-	// Manifest records the project manifest that identifies the state
-	// of Vanadium projects used for the build.
-	Manifest string
-	// Pristine records whether the build was executed using pristine
-	// master branches of Vanadium projects (or not).
-	Pristine bool
-}
-
-var info T
-
-func init() {
-	info.BuildPlatform = platform
-	if timestamp != "" {
-		var err error
-		info.BuildTimestamp, err = time.Parse(time.RFC3339, timestamp)
-		if err != nil {
-			panic(fmt.Sprintf("Parse(%v) failed: %v", timestamp, err))
-		}
-	}
-	info.BuildUser = username
-	info.GoVersion = runtime.Version()
-	if manifest != "" {
-		decodedBytes, err := base64.StdEncoding.DecodeString(manifest)
-		if err != nil {
-			panic(fmt.Sprintf("DecodeString() failed: %v", err))
-		}
-		info.Manifest = string(decodedBytes)
-	}
-	if pristine != "" {
-		b, err := strconv.ParseBool(pristine)
-		if err != nil {
-			panic(fmt.Sprintf("ParseBool(%v) failed: %v", pristine, err))
-		}
-		info.Pristine = b
-	}
-}
-
-// Info returns metadata about the current binary.
-func Info() *T {
-	return &info
-}
-
-// String returns the binary metadata as a JSON-encoded string, under the
-// expectation that clients may want to parse it for specific bits of metadata.
-func (t *T) String() string {
-	jsonT, err := json.Marshal(t)
-	if err != nil {
-		return ""
-	}
-	return string(jsonT)
-}
diff --git a/cmdline/cmdline.go b/cmdline/cmdline.go
index ede3236..5e133d6 100644
--- a/cmdline/cmdline.go
+++ b/cmdline/cmdline.go
@@ -63,6 +63,7 @@
 	"unicode"
 	"unicode/utf8"
 
+	_ "v.io/x/lib/metadata" // for the -v23.metadata flag
 	"v.io/x/lib/textutil"
 )
 
diff --git a/metadata/.api b/metadata/.api
new file mode 100644
index 0000000..a873379
--- /dev/null
+++ b/metadata/.api
@@ -0,0 +1,18 @@
+pkg metadata, func FromBase64([]byte) (*T, error)
+pkg metadata, func FromMap(map[string]string) *T
+pkg metadata, func FromXML([]byte) (*T, error)
+pkg metadata, func Insert(string, string) string
+pkg metadata, func LDFlag(*T) string
+pkg metadata, func LDFlagExternal(string, string, *T) string
+pkg metadata, func Lookup(string) string
+pkg metadata, func ToBase64() string
+pkg metadata, func ToMap() map[string]string
+pkg metadata, func ToXML() string
+pkg metadata, method (*T) Insert(string, string) string
+pkg metadata, method (*T) Lookup(string) string
+pkg metadata, method (*T) String() string
+pkg metadata, method (*T) ToBase64() string
+pkg metadata, method (*T) ToMap() map[string]string
+pkg metadata, method (*T) ToXML() string
+pkg metadata, type T struct
+pkg metadata, var BuiltIn T
diff --git a/metadata/metadata.go b/metadata/metadata.go
new file mode 100644
index 0000000..2510b42
--- /dev/null
+++ b/metadata/metadata.go
@@ -0,0 +1,327 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package metadata implements a mechanism for setting and retrieving metadata
+// stored in program binaries.
+//
+// Metadata is a flat mapping of unique string identifiers to their associated
+// string values.  Both the ids and the values should be human-readable strings,
+// since many uses of metadata involve textual output for humans; e.g. dumping
+// metadata from the program on the command-line, or prepending metadata to log
+// files.
+//
+// The ids must be unique, and avoiding collisions is up to the users of this
+// package; it is recommended to prefix your identifiers with your project name.
+//
+// There are typically two sources for metadata, both supported by this package:
+//
+// 1) External metadata gathered by a build tool, e.g. the build timestamp.
+//
+// 2) Internal metadata compiled into the program, e.g. version numbers.
+//
+// External metadata is injected into the program binary by the linker.  The Go
+// ld linker provides a -X option that may be used for this purpose; see LDFlag
+// for more details.
+//
+// Internal metadata is already compiled into the program binary, but the
+// metadata package must still be made aware of it.  Call the Insert function in
+// an init function to accomplish this:
+//
+//   package mypkg
+//   import "v.io/x/lib/metadata"
+//
+//   func init() {
+//     metadata.Insert("myproject.myid", "value")
+//   }
+//
+// The built-in metadata comes pre-populated with the Go architecture, operating
+// system and version.
+//
+// This package registers a flag -v23.metadata via an init function.  Setting
+// -v23.metadata on the command-line causes the program to dump metadata in the
+// XML format and exit.
+package metadata
+
+import (
+	"bytes"
+	"compress/zlib"
+	"encoding/base64"
+	"encoding/xml"
+	"flag"
+	"fmt"
+	"io"
+	"os"
+	"reflect"
+	"runtime"
+	"sort"
+	"strings"
+)
+
+// T represents the metadata for a program binary.
+type T struct {
+	entries map[string]string
+}
+
+// String returns a human-readable representation; the same as ToXML.
+func (x *T) String() string {
+	return x.ToXML()
+}
+
+// Insert sets the metadata entry for id to value, and returns the previous
+// value.  Whitespace is trimmed from either end of the value.
+func (x *T) Insert(id, value string) string {
+	if x.entries == nil {
+		x.entries = make(map[string]string)
+	}
+	old := x.entries[id]
+	x.entries[id] = strings.TrimSpace(value)
+	return old
+}
+
+// Lookup retrieves the value for the given id from x.
+func (x *T) Lookup(id string) string {
+	return x.entries[id]
+}
+
+// FromMap returns new metadata initialized with the given entries.  Calls
+// Insert on each element of entries.
+func FromMap(entries map[string]string) *T {
+	x := new(T)
+	for id, value := range entries {
+		x.Insert(id, value)
+	}
+	return x
+}
+
+// ToMap returns a copy of the entries in x.  Mutating the returned map has no
+// effect on x.
+func (x *T) ToMap() map[string]string {
+	if len(x.entries) == 0 {
+		return nil
+	}
+	ret := make(map[string]string, len(x.entries))
+	for id, value := range x.entries {
+		ret[id] = value
+	}
+	return ret
+}
+
+type xmlMetaData struct {
+	XMLName struct{}   `xml:"metadata"`
+	Entries []xmlEntry `xml:"md"`
+}
+
+type xmlEntry struct {
+	ID string `xml:"id,attr"`
+	// When marshalling only one of Value or ValueCDATA is set; Value is normally
+	// used, and ValueCDATA is used to add explicit "<![CDATA[...]]>" wrapping.
+	//
+	// When unmarshalling Value is set to the unescaped data, while ValueCDATA is
+	// set to the raw XML.
+	Value      string `xml:",chardata"`
+	ValueCDATA string `xml:",innerxml"`
+}
+
+// FromXML returns new metadata initialized with the given XML encoded data.
+// The expected schema is described in ToXML.
+func FromXML(data []byte) (*T, error) {
+	x := new(T)
+	if len(data) == 0 {
+		return x, nil
+	}
+	var xmlData xmlMetaData
+	if err := xml.Unmarshal(data, &xmlData); err != nil {
+		return nil, err
+	}
+	for _, entry := range xmlData.Entries {
+		x.Insert(entry.ID, entry.Value)
+	}
+	return x, nil
+}
+
+// ToXML returns the XML encoding of x, using the schema described below.
+//
+//   <metadata>
+//     <md id="A">a value</md>
+//     <md id="B"><![CDATA[
+//       foo
+//       bar
+//     ]]></md>
+//     <md id="C">c value</md>
+//   </metadata>
+func (x *T) ToXML() string {
+	return x.toXML(true)
+}
+
+func (x *T) toXML(indent bool) string {
+	// Write each XML <md> entry ordered by id.
+	var ids []string
+	for id, _ := range x.entries {
+		ids = append(ids, id)
+	}
+	sort.Strings(ids)
+	var data xmlMetaData
+	for _, id := range ids {
+		entry := xmlEntry{ID: id}
+		value := x.entries[id]
+		if xmlUseCDATASection(value) {
+			entry.ValueCDATA = cdataStart + "\n" + value + "\n  " + cdataEnd
+		} else {
+			entry.Value = value
+		}
+		data.Entries = append(data.Entries, entry)
+	}
+	var dataXML []byte
+	if indent {
+		dataXML, _ = xml.MarshalIndent(data, "", "  ")
+	} else {
+		dataXML, _ = xml.Marshal(data)
+	}
+	return string(dataXML)
+}
+
+const (
+	cdataStart = "<![CDATA["
+	cdataEnd   = "]]>"
+)
+
+func xmlUseCDATASection(value string) bool {
+	// Cannot use CDATA if "]]>" appears since that's the CDATA terminator.
+	if strings.Contains(value, cdataEnd) {
+		return false
+	}
+	// The choice at this point is a heuristic; it only determines how "pretty"
+	// the output looks.
+	b := []byte(value)
+	var buf bytes.Buffer
+	xml.EscapeText(&buf, b)
+	return !bytes.Equal(buf.Bytes(), b)
+}
+
+// FromBase64 returns new metadata initialized with the given base64 encoded
+// data.  The data is expected to have started as a valid XML representation of
+// metadata, then zlib compressed, and finally base64 encoded.
+func FromBase64(data []byte) (*T, error) {
+	if len(data) == 0 {
+		return new(T), nil
+	}
+	dataXML := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
+	n, err := base64.StdEncoding.Decode(dataXML, data)
+	if err != nil {
+		return nil, err
+	}
+	var b bytes.Buffer
+	r, err := zlib.NewReader(bytes.NewReader(dataXML[:n]))
+	if err != nil {
+		return nil, err
+	}
+	_, errCopy := io.Copy(&b, r)
+	errClose := r.Close()
+	switch {
+	case errCopy != nil:
+		return nil, err
+	case errClose != nil:
+		return nil, err
+	}
+	return FromXML(b.Bytes())
+}
+
+// ToBase64 returns the base64 encoding of x.  First x is XML encoded, then zlib
+// compressed, and finally base64 encoded.
+func (x *T) ToBase64() string {
+	var b bytes.Buffer
+	w := zlib.NewWriter(&b)
+	w.Write([]byte(x.toXML(false)))
+	w.Close()
+	return base64.StdEncoding.EncodeToString(b.Bytes())
+}
+
+var thisPkgPath = reflect.TypeOf(T{}).PkgPath()
+
+// LDFlag returns the flag to pass to the Go ld linker to initialize the
+// built-in metadata with x.  Calls LDFlagExternal with the appropriate package
+// path and unexported variable name to initialize BuiltIn.
+func LDFlag(x *T) string {
+	return LDFlagExternal(thisPkgPath, "initBuiltIn", x)
+}
+
+// LDFlagExternal returns the flag to pass to the Go ld linker to initialize the
+// string variable defined in pkgpath to the base64 encoding of x.  See the
+// documentation of the -X option at https://golang.org/cmd/ld
+//
+// The base64 encoding is used to avoid quoting and escaping issues when passing
+// the flag through the go toolchain.  An example of using the result to install
+// a Go binary with metadata x:
+//
+//   LDFlagExternal("main", "myvar", x) == "-X main.myvar eJwBAAD//wAAAAE="
+//
+//   $ go install -ldflags="-X main.myvar eJwBAAD//wAAAAE=" mypackage
+func LDFlagExternal(pkgpath, variable string, x *T) string {
+	return fmt.Sprintf("-X %s.%s %s", pkgpath, variable, x.ToBase64())
+}
+
+// Insert sets the built-in metadata entry for id to value, and returns the
+// previous value.  Whitespace is trimmed from either end of the value.
+//
+// The built-in metadata is initialized by the Go ld linker.  See the LDFlag
+// function for more details.
+func Insert(id, value string) string { return BuiltIn.Insert(id, value) }
+
+// Lookup retrieves the value for the given id from the built-in metadata.
+func Lookup(id string) string { return BuiltIn.Lookup(id) }
+
+// ToBase64 returns the base64 encoding of the built-in metadata.  First the
+// metadata is XML encoded, then zlib compressed, and finally base64 encoded.
+func ToBase64() string { return BuiltIn.ToBase64() }
+
+// ToXML returns the XML encoding of the built-in metadata.  The schema is
+// defined in T.ToXML.
+func ToXML() string { return BuiltIn.ToXML() }
+
+// ToMap returns a copy of the entries in the built-in metadata.  Mutating the
+// returned map has no effect on the built-in metadata.
+func ToMap() map[string]string { return BuiltIn.ToMap() }
+
+// BuiltIn represents the metadata built-in to the Go program.  The top-level
+// functions such as Insert, ToBase64, and so on are wrappers for the methods of
+// BuiltIn.
+var BuiltIn T
+
+// initBuiltIn is expected to be initialized by the Go ld linker.
+var initBuiltIn string
+
+func init() {
+	// First initialize the BuiltIn metadata based on linker-injected metadata.
+	if x, err := FromBase64([]byte(initBuiltIn)); err != nil {
+		// Don't panic, since a binary without metadata is more useful than a binary
+		// that always panics with invalid metadata.
+		fmt.Fprintf(os.Stderr, `
+metadata: built-in initialization failed (%v) from base64 data: %v
+`, err, initBuiltIn)
+	} else {
+		BuiltIn = *x
+	}
+	// Now set values from the runtime.  These may not be overridden by the
+	// linker-injected metadata, and should not be overridden by user packages.
+	BuiltIn.Insert("go.Arch", runtime.GOARCH)
+	BuiltIn.Insert("go.OS", runtime.GOOS)
+	BuiltIn.Insert("go.Version", runtime.Version())
+
+	flag.Var(metadataFlag{}, "v23.metadata", "Displays metadata for the program and exits.")
+}
+
+// metadataFlag implements a flag that dumps the default metadata and exits the
+// program when it is set.
+type metadataFlag struct{}
+
+func (metadataFlag) IsBoolFlag() bool { return true }
+func (metadataFlag) String() string   { return "<just specify -v23.metadata to activate>" }
+func (metadataFlag) Set(string) error {
+	fmt.Println(BuiltIn.String())
+	os.Exit(0)
+	// TODO(toddw): change os.Exit(0) to return ErrFlag instead.  This needs to
+	// wait on a bugfix where the standard Go flag package doesn't check the error
+	// returned from Set for boolean flags.
+	return nil
+}
diff --git a/metadata/metadata_test.go b/metadata/metadata_test.go
new file mode 100644
index 0000000..5dbc47a
--- /dev/null
+++ b/metadata/metadata_test.go
@@ -0,0 +1,257 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package metadata
+
+import (
+	"os/exec"
+	"reflect"
+	"runtime"
+	"testing"
+)
+
+var allTests = []struct {
+	MD  *T
+	XML string
+	B64 string
+}{
+	{
+		MD:  FromMap(nil),
+		XML: `<metadata></metadata>`,
+		B64: `eJyyyU0tSUxJLEm0s9GHMwEBAAD//1RmB6Y=`,
+	},
+	{
+		MD: FromMap(map[string]string{
+			"A": `a value`,
+			"B": `b value`,
+			"C": `c value`,
+		}),
+		XML: `<metadata>
+  <md id="A">a value</md>
+  <md id="B">b value</md>
+  <md id="C">c value</md>
+</metadata>`,
+		B64: `eJyyyU0tSUxJLEm0s8lNUchMsVVyVLJLVChLzClNtdHPTYELOynZJWERdlayS0YW1oebBwgAAP//H2Qc4g==`,
+	},
+	{
+		MD: FromMap(map[string]string{
+			"A": `a value`,
+			"B": `
+b value
+   has newlines
+ galore
+`,
+			"C": `c value`,
+		}),
+		XML: `<metadata>
+  <md id="A">a value</md>
+  <md id="B"><![CDATA[
+b value
+   has newlines
+ galore
+  ]]></md>
+  <md id="C">c value</md>
+</metadata>`,
+		B64: `eJyyyU0tSUxJLEm0s8lNUchMsVVyVLJLVChLzClNtdHPTYELOynZ2ShGO7s4hjhGcyVBFHApKChkJBYr5KWW52TmpRZzKaQn5uQXgcRjY+1QtDsr2SUjm6oPtxcQAAD//0qVKG0=`,
+	},
+	{
+		MD: FromMap(map[string]string{
+			"BuildPlatform": `amd64unknown-linux-unknown`,
+			"BuildTime":     `2015-05-01T01:33:35Z`,
+			"Manifest": `
+<manifest label="">
+  <projects>
+    <project exclude="false" name="release.go.v23" path="release/go/src/v.io/v23" protocol="git" remote="https://vanadium.googlesource.com/release.go.v23" revision="16889ec00eb4008849057a5e9014a025a231f836"></project>
+    <project exclude="false" name="release.go.x.devtools" path="release/go/src/v.io/x/devtools" protocol="git" remote="https://vanadium.googlesource.com/release.go.x.devtools" revision="de0bd3a5f0f9b30532c41bdb01661cfe8c24df76"></project>
+  </projects>
+</manifest>
+`,
+			"ZZZ": `zzz`,
+		}),
+		XML: `<metadata>
+  <md id="BuildPlatform">amd64unknown-linux-unknown</md>
+  <md id="BuildTime">2015-05-01T01:33:35Z</md>
+  <md id="Manifest"><![CDATA[
+<manifest label="">
+  <projects>
+    <project exclude="false" name="release.go.v23" path="release/go/src/v.io/v23" protocol="git" remote="https://vanadium.googlesource.com/release.go.v23" revision="16889ec00eb4008849057a5e9014a025a231f836"></project>
+    <project exclude="false" name="release.go.x.devtools" path="release/go/src/v.io/x/devtools" protocol="git" remote="https://vanadium.googlesource.com/release.go.x.devtools" revision="de0bd3a5f0f9b30532c41bdb01661cfe8c24df76"></project>
+  </projects>
+</manifest>
+  ]]></md>
+  <md id="ZZZ">zzz</md>
+</metadata>`,
+		B64: `eJyskjFv2zAQhff8CpW7RVKUFNmQBaTtWqCDJwcZTuTJYUvqDJFSDf/6MojhxBkKFAjA5d0d7+HDvdZjBAMRutabzJot+zpbZ346iANNnnXgTV3O4++R/owrZ8f5tLqolntz+2tnPbKuELJaifTkTsiNUhtV7W9mf8BoBwyRde2Xx2/fH3YPj3etvxQzBz26LWPdXZa1x4l+oY7hRbzJDE/azQa3bAAXkGUj+CQmdAgB8wPlS6FYdoT4fK3yA/Ewab7klvhre6JImpLXwUaWTegppi3PMR7DhvMFRjB29mkdHRwGmieNuSbPP/pMuNhgadwyWTfNGrUQ2JdCNE25FtU9VLgWsgRRVFAoOTSqTuT8wvK/ZKfc4BKJXPgX4Im/m/oEzveub7gGRW8UVIMY1r0SlSp0KXvTC1nXUg/Y6KI0w/1H3KtIZ03BuBz+pfP01N0kZb/fs+58Pr8W+TWrfwMAAP//M7rlfg==`,
+	},
+}
+
+func TestToMap(t *testing.T) {
+	for _, test := range allTests {
+		if got, want := test.MD.ToMap(), test.MD.entries; !reflect.DeepEqual(got, want) {
+			t.Errorf("got %v, want %v", got, want)
+		}
+	}
+}
+
+func TestFromMap(t *testing.T) {
+	for _, test := range allTests {
+		if got, want := FromMap(test.MD.entries), test.MD; !reflect.DeepEqual(got, want) {
+			t.Errorf("got %#v, want %#v", got, want)
+		}
+	}
+}
+
+func TestToXML(t *testing.T) {
+	for _, test := range allTests {
+		if got, want := test.MD.ToXML(), test.XML; got != want {
+			t.Errorf("got %v, want %v", got, want)
+		}
+	}
+}
+
+func TestFromXML(t *testing.T) {
+	for _, test := range allTests {
+		got, err := FromXML([]byte(test.XML))
+		if err != nil {
+			t.Errorf("%v FromXML failed: %v", test.XML, err)
+		}
+		if want := test.MD; !reflect.DeepEqual(got, want) {
+			t.Errorf("got %#v, want %#v", got, want)
+		}
+		// Add some garbage and make sure it fails.
+		bad := "<notclosed" + test.XML
+		if got, err := FromXML([]byte(bad)); got != nil || err == nil {
+			t.Errorf("%v FromXML should have failed: (%#v, %v)", bad, got, err)
+		}
+	}
+}
+
+func TestToBase64(t *testing.T) {
+	for _, test := range allTests {
+		if got, want := test.MD.ToBase64(), test.B64; got != want {
+			t.Errorf("got %v, want %v", got, want)
+		}
+	}
+}
+
+func TestFromBase64(t *testing.T) {
+	for _, test := range allTests {
+		got, err := FromBase64([]byte(test.B64))
+		if err != nil {
+			t.Errorf("%v FromBase64 failed: %v", test.B64, err)
+		}
+		if want := test.MD; !reflect.DeepEqual(got, want) {
+			t.Errorf("got %#v, want %#v", got, want)
+		}
+		// Add some garbage and make sure it fails.
+		bad := "!@#$%^&*()_+" + test.B64
+		if got, err := FromBase64([]byte(bad)); got != nil || err == nil {
+			t.Errorf("%v FromBase64 should have failed: (%#v, %v)", bad, got, err)
+		}
+	}
+}
+
+func TestInsertLookup(t *testing.T) {
+	tests := []struct {
+		ID, Value, Old string
+		Map            map[string]string
+	}{
+		{"A", "abc", "", map[string]string{"A": "abc"}},
+		{"B", "123", "", map[string]string{"A": "abc", "B": "123"}},
+		{"A", "xyz", "abc", map[string]string{"A": "xyz", "B": "123"}},
+		{"C", "s p a c e s", "", map[string]string{"A": "xyz", "B": "123", "C": "s p a c e s"}},
+	}
+	var x T
+	for _, test := range tests {
+		if got, want := x.Lookup(test.ID), test.Old; got != want {
+			t.Errorf("(%q, %q) Lookup got %q, want %q", test.ID, test.Value, got, want)
+		}
+		if got, want := x.Insert(test.ID, test.Value), test.Old; got != want {
+			t.Errorf("(%q, %q) Insert got %q, want %q", test.ID, test.Value, got, want)
+		}
+		if got, want := x.Lookup(test.ID), test.Value; got != want {
+			t.Errorf("(%q, %q) Lookup got %q, want %q", test.ID, test.Value, got, want)
+		}
+		// Add some leading and trailing spaces, which will be stripped.
+		value2 := "ZZ" + test.Value + "ZZ"
+		if got, want := x.Insert(test.ID, " \n\t"+value2+"\n\t "), test.Value; got != want {
+			t.Errorf("(%q, %q) Insert got %q, want %q", test.ID, value2, got, want)
+		}
+		if got, want := x.Lookup(test.ID), value2; got != want {
+			t.Errorf("(%q, %q) Lookup got %q, want %q", test.ID, value2, got, want)
+		}
+		// Set the value back.
+		if got, want := x.Insert(test.ID, test.Value), value2; got != want {
+			t.Errorf("(%q, %q) Insert got %q, want %q", test.ID, test.Value, got, want)
+		}
+		// Check the map form.
+		if got, want := x.ToMap(), test.Map; !reflect.DeepEqual(got, want) {
+			t.Errorf("(%q, %q) ToMap got %q, want %q", test.ID, test.Value, got, want)
+		}
+	}
+}
+
+func TestLDFlag(t *testing.T) {
+	for _, test := range allTests {
+		got, want := LDFlag(test.MD), "-X "+thisPkgPath+".initBuiltIn "+test.B64
+		if got != want {
+			t.Errorf("got %q, want %q", got, want)
+		}
+	}
+}
+
+// TestBuiltIn tests the package-level functions that operate on BuiltIn.
+func TestBuiltIn(t *testing.T) {
+	const id, value1, value2 = "TestID", "testvalue1", "testvalue2"
+	if got, want := Lookup(id), ""; got != want {
+		t.Errorf("Lookup %s got %q, want %q", id, got, want)
+	}
+	if got, want := Insert(id, value1), ""; got != want {
+		t.Errorf("Insert %s got %q, want %q", id, got, want)
+	}
+	if got, want := Lookup(id), value1; got != want {
+		t.Errorf("Lookup %s got %q, want %q", id, got, want)
+	}
+	if got, want := Insert(id, value2), value1; got != want {
+		t.Errorf("Insert %s got %q, want %q", id, got, want)
+	}
+	wantMap := map[string]string{
+		id:           value2,
+		"go.Arch":    runtime.GOARCH,
+		"go.OS":      runtime.GOOS,
+		"go.Version": runtime.Version(),
+	}
+	if got, want := ToMap(), wantMap; !reflect.DeepEqual(got, want) {
+		t.Errorf("got map %q, want %q", got, want)
+	}
+	if got, want := ToXML(), FromMap(wantMap).ToXML(); got != want {
+		t.Errorf("got xml %q, want %q", got, want)
+	}
+	if got, want := ToBase64(), FromMap(wantMap).ToBase64(); got != want {
+		t.Errorf("got base64 %q, want %q", got, want)
+	}
+}
+
+// TestInitAndFlag builds a test binary with some metadata, and invokes the
+// -v23.metadata flag to make sure it dumps the expected metadata.
+func TestInitAndFlag(t *testing.T) {
+	// Run the test binary.
+	const id, value = "zzzTestID", "abcdefg"
+	x := FromMap(map[string]string{id: value})
+	cmdRun := exec.Command("go", "run", "-ldflags="+LDFlag(x), "./testdata/testbin.go", "-v23.metadata")
+	outXML, err := cmdRun.CombinedOutput()
+	if err != nil {
+		t.Errorf("%v failed: %v\n%v", cmdRun.Args, err, outXML)
+	}
+	wantXML := `<metadata>
+  <md id="go.Arch">` + runtime.GOARCH + `</md>
+  <md id="go.OS">` + runtime.GOOS + `</md>
+  <md id="go.Version">` + runtime.Version() + `</md>
+  <md id="` + id + `">` + value + `</md>
+</metadata>
+`
+	if got, want := string(outXML), wantXML; got != want {
+		t.Errorf("got %q, want %q", got, want)
+	}
+}
diff --git a/metadata/testdata/testbin.go b/metadata/testdata/testbin.go
new file mode 100644
index 0000000..e86a1eb
--- /dev/null
+++ b/metadata/testdata/testbin.go
@@ -0,0 +1,16 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Command testbin is a test program of the -v23.metadata command line flag.
+package main
+
+import (
+	"flag"
+
+	_ "v.io/x/lib/metadata"
+)
+
+func main() {
+	flag.Parse()
+}