diff --git a/CHANGELOG.next.asciidoc b/CHANGELOG.next.asciidoc index fe4d43eb179..97c726e7d78 100644 --- a/CHANGELOG.next.asciidoc +++ b/CHANGELOG.next.asciidoc @@ -196,6 +196,7 @@ https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD d - Add `aws_ec2` provider for autodiscover. {issue}12518[12518] {pull}14823[14823] - Add monitoring variable `libbeat.config.scans` to distinguish scans of the configuration directory from actual reloads of its contents. {pull}16440[16440] - Add support for multiple password in redis output. {issue}16058[16058] {pull}16206[16206] +- Windows .exe files now have embedded file version info. {issue}15232[15232]t - Remove experimental flag from `setup.template.append_fields` {pull}16576[16576] - Add `add_cloudfoundry_metadata` processor to annotate events with Cloud Foundry application data. {pull}16621[16621] - Add `translate_sid` processor on Windows for converting Windows security identifier (SID) values to names. {issue}7451[7451] {pull}16013[16013] diff --git a/NOTICE.txt b/NOTICE.txt index 5c90121a48e..93998dfa106 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -284,6 +284,34 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-------------------------------------------------------------------- +Dependency: github.com/akavel/rsrc +Version: v0.8.0 +License type (autodetected): MIT +./vendor/github.com/akavel/rsrc/LICENSE.txt: +-------------------------------------------------------------------- +The MIT License (MIT) + +Copyright (c) 2013-2017 The rsrc Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + -------------------------------------------------------------------- Dependency: github.com/andrewkroh/sys Revision: 287798fe3e43 @@ -4451,6 +4479,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-------------------------------------------------------------------- +Dependency: github.com/josephspurrier/goversioninfo +Revision: 14b0ab84c6ca +License type (autodetected): MIT +./vendor/github.com/josephspurrier/goversioninfo/LICENSE: +-------------------------------------------------------------------- +The MIT License (MIT) + +Copyright (c) 2016 Joseph Spurrier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + -------------------------------------------------------------------- Dependency: github.com/jpillora/backoff Version: v1.0.0 diff --git a/dev-tools/mage/build.go b/dev-tools/mage/build.go index 74fe4f1214d..33ebba2e815 100644 --- a/dev-tools/mage/build.go +++ b/dev-tools/mage/build.go @@ -25,6 +25,7 @@ import ( "path/filepath" "strings" + "github.com/josephspurrier/goversioninfo" "github.com/magefile/mage/sh" "github.com/pkg/errors" ) @@ -32,15 +33,16 @@ import ( // BuildArgs are the arguments used for the "build" target and they define how // "go build" is invoked. type BuildArgs struct { - Name string // Name of binary. (On Windows '.exe' is appended.) - InputFiles []string - OutputDir string - CGO bool - Static bool - Env map[string]string - LDFlags []string - Vars map[string]string // Vars that are passed as -X key=value with the ldflags. - ExtraFlags []string + Name string // Name of binary. (On Windows '.exe' is appended.) + InputFiles []string + OutputDir string + CGO bool + Static bool + Env map[string]string + LDFlags []string + Vars map[string]string // Vars that are passed as -X key=value with the ldflags. + ExtraFlags []string + WinMetadata bool // Add resource metadata to Windows binaries (like add the version number to the .exe properties). } // DefaultBuildArgs returns the default BuildArgs for use in builds. @@ -55,6 +57,7 @@ func DefaultBuildArgs() BuildArgs { "github.com/elastic/beats/libbeat/version.buildTime": "{{ date }}", "github.com/elastic/beats/libbeat/version.commit": "{{ commit }}", }, + WinMetadata: true, } if versionQualified { args.Vars["github.com/elastic/beats/libbeat/version.qualifier"] = "{{ .Qualifier }}" @@ -150,6 +153,64 @@ func Build(params BuildArgs) error { args = append(args, params.InputFiles...) } + if GOOS == "windows" && params.WinMetadata { + log.Println("Generating a .syso containing Windows file metadata.") + syso, err := MakeWindowsSysoFile() + if err != nil { + return errors.Wrap(err, "failed generating Windows .syso metadata file") + } + defer os.Remove(syso) + } + log.Println("Adding build environment vars:", env) return sh.RunWith(env, "go", args...) } + +// MakeWindowsSysoFile generates a .syso file containing metadata about the +// executable file like vendor, version, copyright. The linker automatically +// discovers the .syso file and incorporates it into the Windows exe. This +// allows users to view metadata about the exe in the Details tab of the file +// properties viewer. +func MakeWindowsSysoFile() (string, error) { + version, err := BeatQualifiedVersion() + if err != nil { + return "", err + } + + commit, err := CommitHash() + if err != nil { + return "", err + } + + major, minor, patch, err := ParseVersion(version) + if err != nil { + return "", err + } + fileVersion := goversioninfo.FileVersion{Major: major, Minor: minor, Patch: patch} + + vi := &goversioninfo.VersionInfo{ + FixedFileInfo: goversioninfo.FixedFileInfo{ + FileVersion: fileVersion, + ProductVersion: fileVersion, + FileType: "01", // Application + }, + StringFileInfo: goversioninfo.StringFileInfo{ + CompanyName: BeatVendor, + ProductName: strings.Title(BeatName), + ProductVersion: version, + FileVersion: version, + FileDescription: BeatDescription, + OriginalFilename: BeatName + ".exe", + LegalCopyright: "Copyright " + BeatVendor + ", License " + BeatLicense, + Comments: "commit=" + commit, + }, + } + + vi.Build() + vi.Walk() + sysoFile := BeatName + "_windows_" + GOARCH + ".syso" + if err = vi.WriteSyso(sysoFile, GOARCH); err != nil { + return "", errors.Wrap(err, "failed to generate syso file with Windows metadata") + } + return sysoFile, nil +} diff --git a/dev-tools/mage/common.go b/dev-tools/mage/common.go index 603624eb9f6..80f73384636 100644 --- a/dev-tools/mage/common.go +++ b/dev-tools/mage/common.go @@ -781,3 +781,25 @@ func listModuleDir(modpath string) (string, error) { } return gotool.ListModuleCacheDir(modpath) } + +var parseVersionRegex = regexp.MustCompile(`(?m)^[^\d]*(?P\d)+\.(?P\d)+(?:\.(?P\d)+.*)?$`) + +// ParseVersion extracts the major, minor, and optional patch number from a +// version string. +func ParseVersion(version string) (major, minor, patch int, err error) { + names := parseVersionRegex.SubexpNames() + matches := parseVersionRegex.FindStringSubmatch(version) + if len(matches) == 0 { + err = errors.Errorf("failed to parse version '%v'", version) + return + } + + data := map[string]string{} + for i, match := range matches { + data[names[i]] = match + } + major, _ = strconv.Atoi(data["major"]) + minor, _ = strconv.Atoi(data["minor"]) + patch, _ = strconv.Atoi(data["patch"]) + return +} diff --git a/dev-tools/mage/common_test.go b/dev-tools/mage/common_test.go new file mode 100644 index 00000000000..e4ce81505ad --- /dev/null +++ b/dev-tools/mage/common_test.go @@ -0,0 +1,47 @@ +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package mage + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseVersion(t *testing.T) { + var tests = []struct { + Version string + Major, Minor, Patch int + }{ + {"v1.2.3", 1, 2, 3}, + {"1.2.3", 1, 2, 3}, + {"1.2.3-SNAPSHOT", 1, 2, 3}, + {"1.2.3rc1", 1, 2, 3}, + {"1.2", 1, 2, 0}, + } + + for _, tc := range tests { + major, minor, patch, err := ParseVersion(tc.Version) + if err != nil { + t.Fatal(err) + } + assert.Equal(t, tc.Major, major) + assert.Equal(t, tc.Minor, minor) + assert.Equal(t, tc.Patch, patch) + } +} diff --git a/go.mod b/go.mod index 359ec5354ab..4b8aafc664b 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( github.com/Shopify/sarama v0.0.0-00010101000000-000000000000 github.com/StackExchange/wmi v0.0.0-20170221213301-9f32b5905fd6 github.com/aerospike/aerospike-client-go v1.27.1-0.20170612174108-0f3b54da6bdc + github.com/akavel/rsrc v0.8.0 // indirect github.com/andrewkroh/sys v0.0.0-20151128191922-287798fe3e43 github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/aws/aws-lambda-go v1.6.0 @@ -93,6 +94,7 @@ require ( github.com/jcmturner/gofork v1.0.0 // indirect github.com/jmoiron/sqlx v1.2.1-0.20190826204134-d7d95172beb5 github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 + github.com/josephspurrier/goversioninfo v0.0.0-20200309025242-14b0ab84c6ca github.com/jpillora/backoff v1.0.0 // indirect github.com/jstemmer/go-junit-report v0.9.1 github.com/klauspost/compress v1.9.3-0.20191122130757-c099ac9f21dd // indirect diff --git a/go.sum b/go.sum index 2e357c91fca..063ef12fa81 100644 --- a/go.sum +++ b/go.sum @@ -96,6 +96,8 @@ github.com/adriansr/fsnotify v0.0.0-20180417234312-c9bbe1f46f1d h1:g0M6kedfjDpyA github.com/adriansr/fsnotify v0.0.0-20180417234312-c9bbe1f46f1d/go.mod h1:VykaKG/ofkKje+MSvqjrDsz1wfyHIvEVFljhq2EOZ4g= github.com/aerospike/aerospike-client-go v1.27.1-0.20170612174108-0f3b54da6bdc h1:9iW/Fbn/R/nyUOiqo6AgwBe8uirqUIoTGF3vKG8qjoc= github.com/aerospike/aerospike-client-go v1.27.1-0.20170612174108-0f3b54da6bdc/go.mod h1:zj8LBEnWBDOVEIJt8LvaRvDG5ARAoa5dBeHaB472NRc= +github.com/akavel/rsrc v0.8.0 h1:zjWn7ukO9Kc5Q62DOJCcxGpXC18RawVtYAGdz2aLlfw= +github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -407,6 +409,8 @@ github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 h1:rp+c0RAYOWj8 github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901/go.mod h1:Z86h9688Y0wesXCyonoVr47MasHilkuLMqGhRZ4Hpak= github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/josephspurrier/goversioninfo v0.0.0-20200309025242-14b0ab84c6ca h1:ozPUX9TKQZVek4lZWYRsQo7uS8vJ+q4OOHvRhHiCLfU= +github.com/josephspurrier/goversioninfo v0.0.0-20200309025242-14b0ab84c6ca/go.mod h1:eJTEwMjXb7kZ633hO3Ln9mBUCOjX2+FlTljvpl9SYdE= github.com/jpillora/backoff v0.0.0-20180909062703-3050d21c67d7/go.mod h1:2iMrUgbbvHEiQClaW2NsSzMyGHqN+rDFqY705q49KG0= github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= diff --git a/vendor/github.com/akavel/rsrc/AUTHORS b/vendor/github.com/akavel/rsrc/AUTHORS new file mode 100644 index 00000000000..c57b056cdda --- /dev/null +++ b/vendor/github.com/akavel/rsrc/AUTHORS @@ -0,0 +1,3 @@ +Mateusz Czapliński +Quentin Renard +shnmng diff --git a/vendor/github.com/akavel/rsrc/LICENSE.txt b/vendor/github.com/akavel/rsrc/LICENSE.txt new file mode 100644 index 00000000000..5c1511ec152 --- /dev/null +++ b/vendor/github.com/akavel/rsrc/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2017 The rsrc Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/akavel/rsrc/binutil/plain.go b/vendor/github.com/akavel/rsrc/binutil/plain.go new file mode 100644 index 00000000000..ddf5238b949 --- /dev/null +++ b/vendor/github.com/akavel/rsrc/binutil/plain.go @@ -0,0 +1,13 @@ +package binutil + +import ( + "reflect" +) + +func Plain(kind reflect.Kind) bool { + switch kind { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + return true + } + return false +} diff --git a/vendor/github.com/akavel/rsrc/binutil/sizedfile.go b/vendor/github.com/akavel/rsrc/binutil/sizedfile.go new file mode 100644 index 00000000000..3a6606fd857 --- /dev/null +++ b/vendor/github.com/akavel/rsrc/binutil/sizedfile.go @@ -0,0 +1,35 @@ +package binutil + +import ( + "io" + "os" +) + +type SizedReader interface { + io.Reader + Size() int64 +} + +type SizedFile struct { + f *os.File + s *io.SectionReader // helper, for Size() +} + +func (r *SizedFile) Read(p []byte) (n int, err error) { return r.s.Read(p) } +func (r *SizedFile) Size() int64 { return r.s.Size() } +func (r *SizedFile) Close() error { return r.f.Close() } + +func SizedOpen(filename string) (*SizedFile, error) { + f, err := os.Open(filename) + if err != nil { + return nil, err + } + info, err := f.Stat() + if err != nil { + return nil, err + } + return &SizedFile{ + f: f, + s: io.NewSectionReader(f, 0, info.Size()), + }, nil +} diff --git a/vendor/github.com/akavel/rsrc/binutil/walk.go b/vendor/github.com/akavel/rsrc/binutil/walk.go new file mode 100644 index 00000000000..4aa4ad30e83 --- /dev/null +++ b/vendor/github.com/akavel/rsrc/binutil/walk.go @@ -0,0 +1,63 @@ +package binutil + +import ( + "errors" + "fmt" + "path" + "reflect" +) + +var ( + WALK_SKIP = errors.New("") +) + +type Walker func(v reflect.Value, path string) error + +func Walk(value interface{}, walker Walker) error { + err := walk(reflect.ValueOf(value), "/", walker) + if err == WALK_SKIP { + err = nil + } + return err +} + +func stopping(err error) bool { + return err != nil && err != WALK_SKIP +} + +func walk(v reflect.Value, spath string, walker Walker) error { + err := walker(v, spath) + if err != nil { + return err + } + v = reflect.Indirect(v) + switch v.Kind() { + case reflect.Slice, reflect.Array: + for i := 0; i < v.Len(); i++ { + err = walk(v.Index(i), spath+fmt.Sprintf("[%d]", i), walker) + if stopping(err) { + return err + } + } + case reflect.Interface: + err = walk(v.Elem(), spath, walker) + if stopping(err) { + return err + } + case reflect.Struct: + //t := v.Type() + for i := 0; i < v.NumField(); i++ { + //f := t.Field(i) //TODO: handle unexported fields + vv := v.Field(i) + err = walk(vv, path.Join(spath, v.Type().Field(i).Name), walker) + if stopping(err) { + return err + } + } + default: + // FIXME: handle other special cases too + // String + return nil + } + return nil +} diff --git a/vendor/github.com/akavel/rsrc/binutil/writer.go b/vendor/github.com/akavel/rsrc/binutil/writer.go new file mode 100644 index 00000000000..cd2ef97818b --- /dev/null +++ b/vendor/github.com/akavel/rsrc/binutil/writer.go @@ -0,0 +1,33 @@ +package binutil + +import ( + "encoding/binary" + "io" + "reflect" +) + +type Writer struct { + W io.Writer + Offset uint32 //FIXME: int64? + Err error +} + +func (w *Writer) WriteLE(v interface{}) { + if w.Err != nil { + return + } + w.Err = binary.Write(w.W, binary.LittleEndian, v) + if w.Err != nil { + return + } + w.Offset += uint32(reflect.TypeOf(v).Size()) +} + +func (w *Writer) WriteFromSized(r SizedReader) { + if w.Err != nil { + return + } + var n int64 + n, w.Err = io.CopyN(w.W, r, r.Size()) + w.Offset += uint32(n) +} diff --git a/vendor/github.com/akavel/rsrc/coff/coff.go b/vendor/github.com/akavel/rsrc/coff/coff.go new file mode 100644 index 00000000000..a9dad22195a --- /dev/null +++ b/vendor/github.com/akavel/rsrc/coff/coff.go @@ -0,0 +1,417 @@ +package coff + +import ( + "debug/pe" + "encoding/binary" + "errors" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + + "github.com/akavel/rsrc/binutil" +) + +type Dir struct { // struct IMAGE_RESOURCE_DIRECTORY + Characteristics uint32 + TimeDateStamp uint32 + MajorVersion uint16 + MinorVersion uint16 + NumberOfNamedEntries uint16 + NumberOfIdEntries uint16 + DirEntries + Dirs +} + +type DirEntries []DirEntry +type Dirs []Dir + +type DirEntry struct { // struct IMAGE_RESOURCE_DIRECTORY_ENTRY + NameOrId uint32 + OffsetToData uint32 +} + +type DataEntry struct { // struct IMAGE_RESOURCE_DATA_ENTRY + OffsetToData uint32 + Size1 uint32 + CodePage uint32 //FIXME: what value here? for now just using 0 + Reserved uint32 +} + +type RelocationEntry struct { + RVA uint32 // "offset within the Section's raw data where the address starts." + SymbolIndex uint32 // "(zero based) index in the Symbol table to which the reference refers." + Type uint16 +} + +// Values reverse-engineered from windres output; names from teh Internets. +// Teh googlies Internets don't seem to have much to say about the AMD64 one, +// unfortunately :/ but it works... +const ( + _IMAGE_REL_AMD64_ADDR32NB = 0x03 + _IMAGE_REL_I386_DIR32NB = 0x07 +) + +type Auxiliary [18]byte + +type Symbol struct { + Name [8]byte + Value uint32 + SectionNumber uint16 + Type uint16 + StorageClass uint8 + AuxiliaryCount uint8 + Auxiliaries []Auxiliary +} + +type StringsHeader struct { + Length uint32 +} + +const ( + MASK_SUBDIRECTORY = 1 << 31 + + RT_ICON = 3 + RT_GROUP_ICON = 3 + 11 + RT_MANIFEST = 24 +) + +// http://www.delorie.com/djgpp/doc/coff/symtab.html +const ( + DT_PTR = 1 + T_UCHAR = 12 +) + +var ( + STRING_RSRC = [8]byte{'.', 'r', 's', 'r', 'c', 0, 0, 0} + STRING_RDATA = [8]byte{'.', 'r', 'd', 'a', 't', 'a', 0, 0} + + LANG_ENTRY = DirEntry{NameOrId: 0x0409} //FIXME: language; what value should be here? +) + +type Sizer interface { + Size() int64 //NOTE: must not exceed limits of uint32, or behavior is undefined +} + +type Coff struct { + pe.FileHeader + pe.SectionHeader32 + + *Dir + DataEntries []DataEntry + Data []Sizer + + Relocations []RelocationEntry + Symbols []Symbol + StringsHeader + Strings []Sizer +} + +func NewRDATA() *Coff { + return &Coff{ + pe.FileHeader{ + Machine: pe.IMAGE_FILE_MACHINE_I386, + NumberOfSections: 1, // .data + TimeDateStamp: 0, + NumberOfSymbols: 2, // starting only with '.rdata', will increase; must include auxiliaries, apparently + SizeOfOptionalHeader: 0, + Characteristics: 0x0105, //http://www.delorie.com/djgpp/doc/coff/filhdr.html + }, + pe.SectionHeader32{ + Name: STRING_RDATA, + Characteristics: 0x40000040, // "INITIALIZED_DATA MEM_READ" ? + }, + + // "directory hierarchy" of .rsrc section; empty for .data function + nil, + []DataEntry{}, + + []Sizer{}, + + []RelocationEntry{}, + + []Symbol{Symbol{ + Name: STRING_RDATA, + Value: 0, + SectionNumber: 1, + Type: 0, // FIXME: wtf? + StorageClass: 3, // FIXME: is it ok? and uint8? and what does the value mean? + AuxiliaryCount: 1, + Auxiliaries: []Auxiliary{{}}, //http://www6.cptec.inpe.br/sx4/sx4man2/g1af01e/chap5.html + }}, + + StringsHeader{ + Length: uint32(binary.Size(StringsHeader{})), // empty strings table for now -- but we must still show size of the table's header... + }, + []Sizer{}, + } +} + +// NOTE: must be called immediately after NewRSRC, before any other +// functions. +func (coff *Coff) Arch(arch string) error { + switch arch { + case "386": + coff.Machine = pe.IMAGE_FILE_MACHINE_I386 + case "amd64": + // Sources: + // https://github.com/golang/go/blob/0e23ca41d99c82d301badf1b762888e2c69e6c57/src/debug/pe/pe.go#L116 + // https://github.com/yasm/yasm/blob/7160679eee91323db98b0974596c7221eeff772c/modules/objfmts/coff/coff-objfmt.c#L38 + // FIXME: currently experimental -- not sure if something more doesn't need to be changed + coff.Machine = pe.IMAGE_FILE_MACHINE_AMD64 + default: + return errors.New("coff: unknown architecture: " + arch) + } + return nil +} + +//NOTE: only usable for Coff created using NewRDATA +//NOTE: symbol names must be probably >8 characters long +//NOTE: symbol names should not contain embedded zeroes +func (coff *Coff) AddData(symbol string, data Sizer) { + coff.addSymbol(symbol) + coff.Data = append(coff.Data, data) + coff.SectionHeader32.SizeOfRawData += uint32(data.Size()) +} + +// addSymbol appends a symbol to Coff.Symbols and to Coff.Strings. +//NOTE: symbol s must be probably >8 characters long +//NOTE: symbol s should not contain embedded zeroes +func (coff *Coff) addSymbol(s string) { + coff.FileHeader.NumberOfSymbols++ + + buf := strings.NewReader(s + "\000") // ASCIIZ + r := io.NewSectionReader(buf, 0, int64(len(s)+1)) + coff.Strings = append(coff.Strings, r) + + coff.StringsHeader.Length += uint32(r.Size()) + + coff.Symbols = append(coff.Symbols, Symbol{ + //Name: // will be filled in Freeze + //Value: // as above + SectionNumber: 1, + Type: 0, // why 0??? // DT_PTR<<4 | T_UCHAR, // unsigned char* // (?) or use void* ? T_VOID=1 + StorageClass: 2, // 2=C_EXT, or 5=C_EXTDEF ? + AuxiliaryCount: 0, + }) +} + +func NewRSRC() *Coff { + return &Coff{ + pe.FileHeader{ + Machine: pe.IMAGE_FILE_MACHINE_I386, + NumberOfSections: 1, // .rsrc + TimeDateStamp: 0, // was also 0 in sample data from MinGW's windres.exe + NumberOfSymbols: 1, + SizeOfOptionalHeader: 0, + Characteristics: 0x0104, //FIXME: copied from windres.exe output, find out what should be here and why + }, + pe.SectionHeader32{ + Name: STRING_RSRC, + Characteristics: 0x40000040, // "INITIALIZED_DATA MEM_READ" ? + }, + + // "directory hierarchy" of .rsrc section: top level goes resource type, then id/name, then language + &Dir{}, + + []DataEntry{}, + []Sizer{}, + + []RelocationEntry{}, + + []Symbol{Symbol{ + Name: STRING_RSRC, + Value: 0, + SectionNumber: 1, + Type: 0, // FIXME: wtf? + StorageClass: 3, // FIXME: is it ok? and uint8? and what does the value mean? + AuxiliaryCount: 0, // FIXME: wtf? + }}, + + StringsHeader{ + Length: uint32(binary.Size(StringsHeader{})), // empty strings table -- but we must still show size of the table's header... + }, + []Sizer{}, + } +} + +//NOTE: function assumes that 'id' is increasing on each entry +//NOTE: only usable for Coff created using NewRSRC +func (coff *Coff) AddResource(kind uint32, id uint16, data Sizer) { + re := RelocationEntry{ + // "(zero based) index in the Symbol table to which the + // reference refers. Once you have loaded the COFF file into + // memory and know where each symbol is, you find the new + // updated address for the given symbol and update the + // reference accordingly." + SymbolIndex: 0, + } + switch coff.Machine { + case pe.IMAGE_FILE_MACHINE_I386: + re.Type = _IMAGE_REL_I386_DIR32NB + case pe.IMAGE_FILE_MACHINE_AMD64: + re.Type = _IMAGE_REL_AMD64_ADDR32NB + } + coff.Relocations = append(coff.Relocations, re) + coff.SectionHeader32.NumberOfRelocations++ + + // find top level entry, inserting new if necessary at correct sorted position + entries0 := coff.Dir.DirEntries + dirs0 := coff.Dir.Dirs + i0 := sort.Search(len(entries0), func(i int) bool { + return entries0[i].NameOrId >= kind + }) + if i0 >= len(entries0) || entries0[i0].NameOrId != kind { + // inserting new entry & dir + entries0 = append(entries0[:i0], append([]DirEntry{{NameOrId: kind}}, entries0[i0:]...)...) + dirs0 = append(dirs0[:i0], append([]Dir{{}}, dirs0[i0:]...)...) + coff.Dir.NumberOfIdEntries++ + } + coff.Dir.DirEntries = entries0 + coff.Dir.Dirs = dirs0 + + // for second level, assume ID is always increasing, so we don't have to sort + dirs0[i0].DirEntries = append(dirs0[i0].DirEntries, DirEntry{NameOrId: uint32(id)}) + dirs0[i0].Dirs = append(dirs0[i0].Dirs, Dir{ + NumberOfIdEntries: 1, + DirEntries: DirEntries{LANG_ENTRY}, + }) + dirs0[i0].NumberOfIdEntries++ + + // calculate preceding DirEntry leaves, to find new index in Data & DataEntries + n := 0 + for _, dir0 := range dirs0[:i0+1] { + n += len(dir0.DirEntries) //NOTE: assuming 1 language here; TODO: dwell deeper if more langs added + } + n-- + + // insert new data in correct place + coff.DataEntries = append(coff.DataEntries[:n], append([]DataEntry{{Size1: uint32(data.Size())}}, coff.DataEntries[n:]...)...) + coff.Data = append(coff.Data[:n], append([]Sizer{data}, coff.Data[n:]...)...) +} + +// Freeze fills in some important offsets in resulting file. +func (coff *Coff) Freeze() { + switch coff.SectionHeader32.Name { + case STRING_RSRC: + coff.freezeRSRC() + case STRING_RDATA: + coff.freezeRDATA() + } +} + +func (coff *Coff) freezeCommon1(path string, offset, diroff uint32) (newdiroff uint32) { + switch path { + case "/Dir": + coff.SectionHeader32.PointerToRawData = offset + diroff = offset + case "/Relocations": + coff.SectionHeader32.PointerToRelocations = offset + coff.SectionHeader32.SizeOfRawData = offset - diroff + case "/Symbols": + coff.FileHeader.PointerToSymbolTable = offset + } + return diroff +} + +func freezeCommon2(v reflect.Value, offset *uint32) error { + if binutil.Plain(v.Kind()) { + *offset += uint32(binary.Size(v.Interface())) // TODO: change to v.Type().Size() ? + return nil + } + vv, ok := v.Interface().(Sizer) + if ok { + *offset += uint32(vv.Size()) + return binutil.WALK_SKIP + } + return nil +} + +func (coff *Coff) freezeRDATA() { + var offset, diroff, stringsoff uint32 + binutil.Walk(coff, func(v reflect.Value, path string) error { + diroff = coff.freezeCommon1(path, offset, diroff) + + RE := regexp.MustCompile + const N = `\[(\d+)\]` + m := matcher{} + //TODO: adjust symbol pointers + //TODO: fill Symbols.Name, .Value + switch { + case m.Find(path, RE("^/Data"+N+"$")): + n := m[0] + coff.Symbols[1+n].Value = offset - diroff // FIXME: is it ok? + sz := uint64(coff.Data[n].Size()) + binary.LittleEndian.PutUint64(coff.Symbols[0].Auxiliaries[0][0:8], binary.LittleEndian.Uint64(coff.Symbols[0].Auxiliaries[0][0:8])+sz) + case path == "/StringsHeader": + stringsoff = offset + case m.Find(path, RE("^/Strings"+N+"$")): + binary.LittleEndian.PutUint32(coff.Symbols[m[0]+1].Name[4:8], offset-stringsoff) + } + + return freezeCommon2(v, &offset) + }) + coff.SectionHeader32.PointerToRelocations = 0 +} + +func (coff *Coff) freezeRSRC() { + leafwalker := make(chan *DirEntry) + go func() { + for _, dir1 := range coff.Dir.Dirs { // resource type + for _, dir2 := range dir1.Dirs { // resource ID + for i := range dir2.DirEntries { // resource lang + leafwalker <- &dir2.DirEntries[i] + } + } + } + }() + + var offset, diroff uint32 + binutil.Walk(coff, func(v reflect.Value, path string) error { + diroff = coff.freezeCommon1(path, offset, diroff) + + RE := regexp.MustCompile + const N = `\[(\d+)\]` + m := matcher{} + switch { + case m.Find(path, RE("^/Dir/Dirs"+N+"$")): + coff.Dir.DirEntries[m[0]].OffsetToData = MASK_SUBDIRECTORY | (offset - diroff) + case m.Find(path, RE("^/Dir/Dirs"+N+"/Dirs"+N+"$")): + coff.Dir.Dirs[m[0]].DirEntries[m[1]].OffsetToData = MASK_SUBDIRECTORY | (offset - diroff) + case m.Find(path, RE("^/DataEntries"+N+"$")): + direntry := <-leafwalker + direntry.OffsetToData = offset - diroff + case m.Find(path, RE("^/DataEntries"+N+"/OffsetToData$")): + coff.Relocations[m[0]].RVA = offset - diroff + case m.Find(path, RE("^/Data"+N+"$")): + coff.DataEntries[m[0]].OffsetToData = offset - diroff + } + + return freezeCommon2(v, &offset) + }) +} + +func mustAtoi(s string) int { + i, err := strconv.Atoi(s) + if err != nil { + panic(err) + } + return i +} + +type matcher []int + +func (m *matcher) Find(s string, re *regexp.Regexp) bool { + subs := re.FindStringSubmatch(s) + if subs == nil { + return false + } + + *m = (*m)[:0] + for i := 1; i < len(subs); i++ { + *m = append(*m, mustAtoi(subs[i])) + } + return true +} diff --git a/vendor/github.com/akavel/rsrc/ico/ico.go b/vendor/github.com/akavel/rsrc/ico/ico.go new file mode 100644 index 00000000000..0d419b1272a --- /dev/null +++ b/vendor/github.com/akavel/rsrc/ico/ico.go @@ -0,0 +1,214 @@ +// Package ico describes Windows ICO file format. +package ico + +// ICO: http://msdn.microsoft.com/en-us/library/ms997538.aspx +// BMP/DIB: http://msdn.microsoft.com/en-us/library/windows/desktop/dd183562%28v=vs.85%29.aspx + +import ( + "bytes" + "encoding/binary" + "fmt" + "image" + "image/color" + "io" + "io/ioutil" + "sort" +) + +const ( + BI_RGB = 0 +) + +type ICONDIR struct { + Reserved uint16 // must be 0 + Type uint16 // Resource Type (1 for icons) + Count uint16 // How many images? +} + +type IconDirEntryCommon struct { + Width byte // Width, in pixels, of the image + Height byte // Height, in pixels, of the image + ColorCount byte // Number of colors in image (0 if >=8bpp) + Reserved byte // Reserved (must be 0) + Planes uint16 // Color Planes + BitCount uint16 // Bits per pixel + BytesInRes uint32 // How many bytes in this resource? +} + +type ICONDIRENTRY struct { + IconDirEntryCommon + ImageOffset uint32 // Where in the file is this image? [from beginning of file] +} + +type BITMAPINFOHEADER struct { + Size uint32 + Width int32 + Height int32 // NOTE: "represents the combined height of the XOR and AND masks. Remember to divide this number by two before using it to perform calculations for either of the XOR or AND masks." + Planes uint16 // [BMP/DIB]: "is always 1" + BitCount uint16 + Compression uint32 // for ico = 0 + SizeImage uint32 + XPelsPerMeter int32 // for ico = 0 + YPelsPerMeter int32 // for ico = 0 + ClrUsed uint32 // for ico = 0 + ClrImportant uint32 // for ico = 0 +} + +type RGBQUAD struct { + Blue byte + Green byte + Red byte + Reserved byte // must be 0 +} + +func skip(r io.Reader, n int64) error { + _, err := io.CopyN(ioutil.Discard, r, n) + return err +} + +type icoOffset struct { + n int + offset uint32 +} + +type rawico struct { + icoinfo ICONDIRENTRY + bmpinfo *BITMAPINFOHEADER + idx int + data []byte +} + +type byOffsets []rawico + +func (o byOffsets) Len() int { return len(o) } +func (o byOffsets) Less(i, j int) bool { return o[i].icoinfo.ImageOffset < o[j].icoinfo.ImageOffset } +func (o byOffsets) Swap(i, j int) { + tmp := o[i] + o[i] = o[j] + o[j] = tmp +} + +type ICO struct { + image.Image +} + +func DecodeHeaders(r io.Reader) ([]ICONDIRENTRY, error) { + var hdr ICONDIR + err := binary.Read(r, binary.LittleEndian, &hdr) + if err != nil { + return nil, err + } + if hdr.Reserved != 0 || hdr.Type != 1 { + return nil, fmt.Errorf("bad magic number") + } + + entries := make([]ICONDIRENTRY, hdr.Count) + for i := 0; i < len(entries); i++ { + err = binary.Read(r, binary.LittleEndian, &entries[i]) + if err != nil { + return nil, err + } + } + return entries, nil +} + +// NOTE: won't succeed on files with overlapping offsets +func unused_decodeAll(r io.Reader) ([]*ICO, error) { + var hdr ICONDIR + err := binary.Read(r, binary.LittleEndian, &hdr) + if err != nil { + return nil, err + } + if hdr.Reserved != 0 || hdr.Type != 1 { + return nil, fmt.Errorf("bad magic number") + } + + raws := make([]rawico, hdr.Count) + for i := 0; i < len(raws); i++ { + err = binary.Read(r, binary.LittleEndian, &raws[i].icoinfo) + if err != nil { + return nil, err + } + raws[i].idx = i + } + + sort.Sort(byOffsets(raws)) + + offset := uint32(binary.Size(&hdr) + len(raws)*binary.Size(ICONDIRENTRY{})) + for i := 0; i < len(raws); i++ { + err = skip(r, int64(raws[i].icoinfo.ImageOffset-offset)) + if err != nil { + return nil, err + } + offset = raws[i].icoinfo.ImageOffset + + raws[i].bmpinfo = &BITMAPINFOHEADER{} + err = binary.Read(r, binary.LittleEndian, raws[i].bmpinfo) + if err != nil { + return nil, err + } + + err = skip(r, int64(raws[i].bmpinfo.Size-uint32(binary.Size(BITMAPINFOHEADER{})))) + if err != nil { + return nil, err + } + raws[i].data = make([]byte, raws[i].icoinfo.BytesInRes-raws[i].bmpinfo.Size) + _, err = io.ReadFull(r, raws[i].data) + if err != nil { + return nil, err + } + } + + icos := make([]*ICO, len(raws)) + for i := 0; i < len(raws); i++ { + fmt.Println(i) + icos[raws[i].idx], err = decode(raws[i].bmpinfo, &raws[i].icoinfo, raws[i].data) + if err != nil { + return nil, err + } + } + return icos, nil +} + +func decode(info *BITMAPINFOHEADER, icoinfo *ICONDIRENTRY, data []byte) (*ICO, error) { + if info.Compression != BI_RGB { + return nil, fmt.Errorf("ICO compression not supported (got %d)", info.Compression) + } + + //if info.ClrUsed!=0 { + // panic(info.ClrUsed) + //} + + r := bytes.NewBuffer(data) + + bottomup := info.Height > 0 + if !bottomup { + info.Height = -info.Height + } + + switch info.BitCount { + case 8: + ncol := int(icoinfo.ColorCount) + if ncol == 0 { + ncol = 256 + } + + pal := make(color.Palette, ncol) + for i := 0; i < ncol; i++ { + var rgb RGBQUAD + err := binary.Read(r, binary.LittleEndian, &rgb) + if err != nil { + return nil, err + } + pal[i] = color.NRGBA{R: rgb.Red, G: rgb.Green, B: rgb.Blue, A: 0xff} //FIXME: is Alpha ok 0xff? + } + fmt.Println(pal) + + fmt.Println(info.SizeImage, len(data)-binary.Size(RGBQUAD{})*len(pal), info.Width, info.Height) + + default: + return nil, fmt.Errorf("unsupported ICO bit depth (BitCount) %d", info.BitCount) + } + + return nil, nil +} diff --git a/vendor/github.com/josephspurrier/goversioninfo/.gitignore b/vendor/github.com/josephspurrier/goversioninfo/.gitignore new file mode 100644 index 00000000000..d2724bfb919 --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/.gitignore @@ -0,0 +1,14 @@ +# IDE Settings +.vscode/ + +# Folders +vendor/ + +# Files +cmd/goversioninfo/goversioninfo +*.exe +*.syso + +# OS Files +.DS_Store +thumbs.db \ No newline at end of file diff --git a/vendor/github.com/josephspurrier/goversioninfo/.travis.yml b/vendor/github.com/josephspurrier/goversioninfo/.travis.yml new file mode 100644 index 00000000000..142d8ed0958 --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/.travis.yml @@ -0,0 +1,34 @@ +os: windows +sudo: false +language: go +go: + # - '1.0' + # - '1.1' + # - '1.2' + # - '1.3' + # - '1.4' + - '1.5' + - '1.6' + - '1.7' + - '1.8' + - '1.9' + - '1.10' + - '1.11' + - '1.12' + - '1.13' + - '1.14' +before_install: + - go get github.com/axw/gocov/gocov + - go get github.com/mattn/goveralls + - go get golang.org/x/tools/cmd/cover + - go get github.com/akavel/rsrc/binutil + - go get github.com/akavel/rsrc/coff + - go get github.com/akavel/rsrc/ico +script: + # Install binary. + - go install github.com/$TRAVIS_REPO_SLUG/cmd/goversioninfo + # Test building 32 and 64 on Windows. + - bash $TRAVIS_BUILD_DIR/testdata/bash/build.sh + # Run tests and send coverage info. + - cd $TRAVIS_BUILD_DIR + - $GOPATH/bin/goveralls -service=travis-ci \ No newline at end of file diff --git a/vendor/github.com/josephspurrier/goversioninfo/LICENSE b/vendor/github.com/josephspurrier/goversioninfo/LICENSE new file mode 100644 index 00000000000..85f6e7e913b --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Joseph Spurrier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/josephspurrier/goversioninfo/README.md b/vendor/github.com/josephspurrier/goversioninfo/README.md new file mode 100644 index 00000000000..b3c51c3cf9d --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/README.md @@ -0,0 +1,122 @@ +GoVersionInfo +========== +[![Build Status](https://travis-ci.org/josephspurrier/goversioninfo.svg)](https://travis-ci.org/josephspurrier/goversioninfo) [![Coverage Status](https://coveralls.io/repos/josephspurrier/goversioninfo/badge.svg)](https://coveralls.io/r/josephspurrier/goversioninfo) [![GoDoc](https://godoc.org/github.com/josephspurrier/goversioninfo?status.svg)](https://godoc.org/github.com/josephspurrier/goversioninfo) + +Microsoft Windows File Properties/Version Info and Icon Resource Generator for the Go Language + +Package creates a syso file which contains Microsoft Windows Version Information and an optional icon. When you run "go build", Go will embed the version information and an optional icon and an optional manifest in the executable. Go will automatically use the syso file if it's in the same directory as the main() function. + +Example of the file properties you can set using this package: + +![Image of File Properties](https://cloud.githubusercontent.com/assets/2394539/12073634/0b32cb04-b0f6-11e5-9d8e-f9923ca554cf.jpg) + +## Usage + +To install, run the following command: +~~~ +go get github.com/josephspurrier/goversioninfo/cmd/goversioninfo +~~~ + +Copy testdata/resource/versioninfo.json into your working directory and then modify the file with your own settings. + +Add a similar text to the top of your Go source code (-icon and -manifest are optional, but can also be specified in the versioninfo.json file): +~~~ go +//go:generate goversioninfo -icon=testdata/resource/icon.ico -manifest=testdata/resource/goversioninfo.exe.manifest +~~~ + +Run the Go commands in this order so goversioninfo will create a file called resource.syso in the same directory as the Go source code. +~~~ +go generate +go build +~~~ + +## Command-Line Flags + +Complete list of the flags for goversioninfo: + +~~~ + -charset=0: charset ID + -comment="": StringFileInfo.Comments + -company="": StringFileInfo.CompanyName + -copyright="": StringFileInfo.LegalCopyright + -description="": StringFileInfo.FileDescription + -example=false: just dump out an example versioninfo.json to stdout + -file-version="": StringFileInfo.FileVersion + -icon="": icon file name + -internal-name="": StringFileInfo.InternalName + -manifest="": manifest file name + -o="resource.syso": output file name + -platform-specific=false: output i386 and amd64 named resource.syso, ignores -o + -original-name="": StringFileInfo.OriginalFilename + -private-build="": StringFileInfo.PrivateBuild + -product-name="": StringFileInfo.ProductName + -product-version="": StringFileInfo.ProductVersion + -special-build="": StringFileInfo.SpecialBuild + -trademark="": StringFileInfo.LegalTrademarks + -translation=0: translation ID + -64:false: generate 64-bit binaries on true + -ver-major=-1: FileVersion.Major + -ver-minor=-1: FileVersion.Minor + -ver-patch=-1: FileVersion.Patch + -ver-build=-1: FileVersion.Build + -product-ver-major=-1: ProductVersion.Major + -product-ver-minor=-1: ProductVersion.Minor + -product-ver-patch=-1: ProductVersion.Patch + -product-ver-build=-1: ProductVersion.Build +~~~ + +You can look over the Microsoft Resource Information: [VERSIONINFO resource](https://msdn.microsoft.com/en-us/library/windows/desktop/aa381058(v=vs.85).aspx) + +You can look through the Microsoft Version Information structures: [Version Information Structures](https://msdn.microsoft.com/en-us/library/windows/desktop/ff468916(v=vs.85).aspx) + +## PowerShell Differences + +In PowerShell, the version components are named differently than the fields in +the versioninfo.json file: + +``` +PowerShell: versioninfo.json: +----------- ----------------- +FileMajorPart = FileVersion.Major +FileMinorPart = FileVersion.Minor +FileBuildPart = FileVersion.Patch +FilePrivatePart = FileVersion.Build +ProductMajorPart = ProductVersion.Major +ProductMinorPart = ProductVersion.Minor +ProductBuildPart = ProductVersion.Patch +ProductPrivatePart = ProductVersion.Build + +``` + +If you find any other differences, let me know. + +## Alternatives to this Tool + +You can also use [windres](https://sourceware.org/binutils/docs/binutils/windres.html) to create the syso file. The windres executable is available in either [MinGW](http://www.mingw.org/) or [tdm-gcc](http://tdm-gcc.tdragon.net/). + +Below is a sample batch file you can use to create a .syso file from a .rc file. There are sample .rc files in the testdata/rc folder. + +~~~ +@ECHO OFF + +SET PATH=C:\TDM-GCC-64\bin;%PATH% +REM SET PATH=C:\mingw64\bin;%PATH% + +windres -i testdata/rc/versioninfo.rc -O coff -o versioninfo.syso + +PAUSE +~~~ + +The information on how to create a .rc file is available [here](https://msdn.microsoft.com/en-us/library/windows/desktop/aa381043(v=vs.85).aspx). You can use the testdata/rc/versioninfo.rc file to create a .syso file that contains version info, icon, and manifest. + +## Issues + +The majority of the code for the creation of the syso file is from this package: [https://github.com/akavel/rsrc](https://github.com/akavel/rsrc) + +There is an [issue](https://github.com/akavel/rsrc/issues/12) with adding the icon resource that prevents your application from being compressed or modified with a resource editor. Please use with caution. + +## Major Contributions + +Thanks to [Tamás Gulácsi](https://github.com/tgulacsi) for his superb code additions, refactoring, and optimization to make this a solid package. + +Thanks to [Mateusz Czaplinski](https://github.com/akavel/rsrc) for his embedded binary resource package with icon and manifest functionality. diff --git a/vendor/github.com/josephspurrier/goversioninfo/goversioninfo.go b/vendor/github.com/josephspurrier/goversioninfo/goversioninfo.go new file mode 100644 index 00000000000..0eb89ac35b9 --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/goversioninfo.go @@ -0,0 +1,268 @@ +// Package goversioninfo creates a syso file which contains Microsoft Version Information and an optional icon. +package goversioninfo + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "log" + "os" + "reflect" + "strconv" + + "github.com/akavel/rsrc/binutil" + "github.com/akavel/rsrc/coff" +) + +// ***************************************************************************** +// JSON and Config +// ***************************************************************************** + +// ParseJSON parses the given bytes as a VersionInfo JSON. +func (vi *VersionInfo) ParseJSON(jsonBytes []byte) error { + return json.Unmarshal([]byte(jsonBytes), &vi) +} + +// VersionInfo data container +type VersionInfo struct { + FixedFileInfo `json:"FixedFileInfo"` + StringFileInfo `json:"StringFileInfo"` + VarFileInfo `json:"VarFileInfo"` + Timestamp bool + Buffer bytes.Buffer + Structure VSVersionInfo + IconPath string `json:"IconPath"` + ManifestPath string `json:"ManifestPath"` +} + +// Translation with langid and charsetid. +type Translation struct { + LangID `json:"LangID"` + CharsetID `json:"CharsetID"` +} + +// FileVersion with 3 parts. +type FileVersion struct { + Major int + Minor int + Patch int + Build int +} + +// FixedFileInfo contains file characteristics - leave most of them at the defaults. +type FixedFileInfo struct { + FileVersion `json:"FileVersion"` + ProductVersion FileVersion + FileFlagsMask string + FileFlags string + FileOS string + FileType string + FileSubType string +} + +// VarFileInfo is the translation container. +type VarFileInfo struct { + Translation `json:"Translation"` +} + +// StringFileInfo is what you want to change. +type StringFileInfo struct { + Comments string + CompanyName string + FileDescription string + FileVersion string + InternalName string + LegalCopyright string + LegalTrademarks string + OriginalFilename string + PrivateBuild string + ProductName string + ProductVersion string + SpecialBuild string +} + +// ***************************************************************************** +// Helpers +// ***************************************************************************** + +// SizedReader is a *bytes.Buffer. +type SizedReader struct { + *bytes.Buffer +} + +// Size returns the length of the buffer. +func (s SizedReader) Size() int64 { + return int64(s.Buffer.Len()) +} + +func str2Uint32(s string) uint32 { + if s == "" { + return 0 + } + u, err := strconv.ParseUint(s, 16, 32) + if err != nil { + log.Printf("Error parsing %q as uint32: %v", s, err) + return 0 + } + + return uint32(u) +} + +func padString(s string, zeros int) []byte { + b := make([]byte, 0, len([]rune(s))*2) + for _, x := range s { + tt := int32(x) + + b = append(b, byte(tt)) + if tt > 255 { + tt = tt >> 8 + b = append(b, byte(tt)) + } else { + b = append(b, byte(0)) + } + } + + for i := 0; i < zeros; i++ { + b = append(b, 0x00) + } + + return b +} + +func padBytes(i int) []byte { + return make([]byte, i) +} + +func (f FileVersion) getVersionHighString() string { + return fmt.Sprintf("%04x%04x", f.Major, f.Minor) +} + +func (f FileVersion) getVersionLowString() string { + return fmt.Sprintf("%04x%04x", f.Patch, f.Build) +} + +// GetVersionString returns a string representation of the version +func (f FileVersion) GetVersionString() string { + return fmt.Sprintf("%d.%d.%d.%d", f.Major, f.Minor, f.Patch, f.Build) +} + +func (t Translation) getTranslationString() string { + return fmt.Sprintf("%04X%04X", t.LangID, t.CharsetID) +} + +func (t Translation) getTranslation() string { + return fmt.Sprintf("%04x%04x", t.CharsetID, t.LangID) +} + +// ***************************************************************************** +// IO Methods +// ***************************************************************************** + +// Walk writes the data buffer with hexidecimal data from the structs +func (vi *VersionInfo) Walk() { + // Create a buffer + var b bytes.Buffer + w := binutil.Writer{W: &b} + + // Write to the buffer + binutil.Walk(vi.Structure, func(v reflect.Value, path string) error { + if binutil.Plain(v.Kind()) { + w.WriteLE(v.Interface()) + } + return nil + }) + + vi.Buffer = b +} + +// WriteSyso creates a resource file from the version info and optionally an icon. +// arch must be an architecture string accepted by coff.Arch, like "386" or "amd64" +func (vi *VersionInfo) WriteSyso(filename string, arch string) error { + + // Channel for generating IDs + newID := make(chan uint16) + go func() { + for i := uint16(1); ; i++ { + newID <- i + } + }() + + // Create a new RSRC section + coff := coff.NewRSRC() + + // Set the architechture + err := coff.Arch(arch) + if err != nil { + return err + } + + // ID 16 is for Version Information + coff.AddResource(16, 1, SizedReader{bytes.NewBuffer(vi.Buffer.Bytes())}) + + // If manifest is enabled + if vi.ManifestPath != "" { + + manifest, err := binutil.SizedOpen(vi.ManifestPath) + if err != nil { + return err + } + defer manifest.Close() + + id := <-newID + coff.AddResource(rtManifest, id, manifest) + } + + // If icon is enabled + if vi.IconPath != "" { + if err := addIcon(coff, vi.IconPath, newID); err != nil { + return err + } + } + + coff.Freeze() + + // Write to file + return writeCoff(coff, filename) +} + +// WriteHex creates a hex file for debugging version info +func (vi *VersionInfo) WriteHex(filename string) error { + return ioutil.WriteFile(filename, vi.Buffer.Bytes(), 0655) +} + +func writeCoff(coff *coff.Coff, fnameout string) error { + out, err := os.Create(fnameout) + if err != nil { + return err + } + if err = writeCoffTo(out, coff); err != nil { + return fmt.Errorf("error writing %q: %v", fnameout, err) + } + return nil +} + +func writeCoffTo(w io.WriteCloser, coff *coff.Coff) error { + bw := binutil.Writer{W: w} + + // write the resulting file to disk + binutil.Walk(coff, func(v reflect.Value, path string) error { + if binutil.Plain(v.Kind()) { + bw.WriteLE(v.Interface()) + return nil + } + vv, ok := v.Interface().(binutil.SizedReader) + if ok { + bw.WriteFromSized(vv) + return binutil.WALK_SKIP + } + return nil + }) + + err := bw.Err + if closeErr := w.Close(); closeErr != nil && err == nil { + err = closeErr + } + return err +} diff --git a/vendor/github.com/josephspurrier/goversioninfo/icon.go b/vendor/github.com/josephspurrier/goversioninfo/icon.go new file mode 100644 index 00000000000..87e27b71ba3 --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/icon.go @@ -0,0 +1,103 @@ +package goversioninfo + +import ( + "bytes" + "encoding/binary" + "os" + + "github.com/akavel/rsrc/coff" + "github.com/akavel/rsrc/ico" +) + +// ***************************************************************************** +/* +Code from https://github.com/akavel/rsrc + +The MIT License (MIT) + +Copyright (c) 2013-2014 The rsrc Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +// ***************************************************************************** + +const ( + rtIcon = coff.RT_ICON + rtGroupIcon = coff.RT_GROUP_ICON + rtManifest = coff.RT_MANIFEST +) + +// on storing icons, see: http://blogs.msdn.com/b/oldnewthing/archive/2012/07/20/10331787.aspx +type gRPICONDIR struct { + ico.ICONDIR + Entries []gRPICONDIRENTRY +} + +func (group gRPICONDIR) Size() int64 { + return int64(binary.Size(group.ICONDIR) + len(group.Entries)*binary.Size(group.Entries[0])) +} + +type gRPICONDIRENTRY struct { + ico.IconDirEntryCommon + ID uint16 +} + +func addIcon(coff *coff.Coff, fname string, newID <-chan uint16) error { + f, err := os.Open(fname) + if err != nil { + return err + } + defer f.Close() + + icons, err := ico.DecodeHeaders(f) + if err != nil { + return err + } + + if len(icons) > 0 { + // RT_ICONs + group := gRPICONDIR{ICONDIR: ico.ICONDIR{ + Reserved: 0, // magic num. + Type: 1, // magic num. + Count: uint16(len(icons)), + }} + gid := <-newID + for _, icon := range icons { + id := <-newID + buff, err := bufferIcon(f, int64(icon.ImageOffset), int(icon.BytesInRes)) + if err != nil { + return err + } + coff.AddResource(rtIcon, id, buff) + group.Entries = append(group.Entries, gRPICONDIRENTRY{IconDirEntryCommon: icon.IconDirEntryCommon, ID: id}) + } + coff.AddResource(rtGroupIcon, gid, group) + } + + return nil +} + +func bufferIcon(f *os.File, offset int64, size int) (*bytes.Reader, error) { + data := make([]byte, size) + _, err := f.ReadAt(data, offset) + if err != nil { + return nil, err + } + return bytes.NewReader(data), nil +} diff --git a/vendor/github.com/josephspurrier/goversioninfo/lang_cs.go b/vendor/github.com/josephspurrier/goversioninfo/lang_cs.go new file mode 100644 index 00000000000..554c9fbf504 --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/lang_cs.go @@ -0,0 +1,131 @@ +// Contribution by Tamás Gulácsi + +package goversioninfo + +import ( + "encoding/json" + "strconv" +) + +// CharsetID must use be a character-set identifier from: +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa381058(v=vs.85).aspx#charsetID +type CharsetID uint16 + +// CharsetID constants +const ( + Cs7ASCII = CharsetID(0) // Cs7ASCII: 0 0000 7-bit ASCII + CsJIS = CharsetID(932) // CsJIS: 932 03A4 Japan (Shift ? JIS X-0208) + CsKSC = CharsetID(949) // CsKSC: 949 03B5 Korea (Shift ? KSC 5601) + CsBig5 = CharsetID(950) // CsBig5: 950 03B6 Taiwan (Big5) + CsUnicode = CharsetID(1200) // CsUnicode: 1200 04B0 Unicode + CsLatin2 = CharsetID(1250) // CsLatin2: 1250 04E2 Latin-2 (Eastern European) + CsCyrillic = CharsetID(1251) // CsCyrillic: 1251 04E3 Cyrillic + CsMultilingual = CharsetID(1252) // CsMultilingual: 1252 04E4 Multilingual + CsGreek = CharsetID(1253) // CsGreek: 1253 04E5 Greek + CsTurkish = CharsetID(1254) // CsTurkish: 1254 04E6 Turkish + CsHebrew = CharsetID(1255) // CsHebrew: 1255 04E7 Hebrew + CsArabic = CharsetID(1256) // CsArabic: 1256 04E8 Arabic +) + +// UnmarshalJSON converts the string to a CharsetID +func (cs *CharsetID) UnmarshalJSON(p []byte) error { + if len(p) == 0 { + return nil + } + if p[0] != '"' { + var u uint16 + if err := json.Unmarshal(p, &u); err != nil { + return err + } + *cs = CharsetID(u) + return nil + } + var s string + if err := json.Unmarshal(p, &s); err != nil { + return err + } + u, err := strconv.ParseUint(s, 16, 16) + if err != nil { + return err + } + *cs = CharsetID(u) + return nil +} + +// LangID must use be a character-set identifier from: +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa381058(v=vs.85).aspx#langID +type LangID uint16 + +// UnmarshalJSON converts the string to a LangID +func (lng *LangID) UnmarshalJSON(p []byte) error { + if len(p) == 0 { + return nil + } + if p[0] != '"' { + var u uint16 + if err := json.Unmarshal(p, &u); err != nil { + return err + } + *lng = LangID(u) + return nil + } + var s string + if err := json.Unmarshal(p, &s); err != nil { + return err + } + u, err := strconv.ParseUint(s, 16, 16) + if err != nil { + return err + } + *lng = LangID(u) + return nil +} + +// LangID constants +const ( + LngArabic = LangID(0x0401) // LngArabic: 0x0401 Arabic + LngBulgarian = LangID(0x0402) // LngBulgarian: 0x0402 Bulgarian + LngCatalan = LangID(0x0403) // LngCatalan: 0x0403 Catalan + LngTraditionalChinese = LangID(0x0404) // LngTraditionalChinese: 0x0404 Traditional Chinese + LngCzech = LangID(0x0405) // LngCzech: 0x0405 Czech + LngDanish = LangID(0x0406) // LngDanish: 0x0406 Danish + LngGerman = LangID(0x0407) // LngGerman: 0x0407 German + LngGreek = LangID(0x0408) // LngGreek: 0x0408 Greek + LngUSEnglish = LangID(0x0409) // LngUSEnglish: 0x0409 U.S. English + LngCastilianSpanish = LangID(0x040A) // LngCastilianSpanish: 0x040A Castilian Spanish + LngFinnish = LangID(0x040B) // LngFinnish: 0x040B Finnish + LngFrench = LangID(0x040C) // LngFrench: 0x040C French + LngHebrew = LangID(0x040D) // LngHebrew: 0x040D Hebrew + LngHungarian = LangID(0x040E) // LngHungarian: 0x040E Hungarian + LngIcelandic = LangID(0x040F) // LngIcelandic: 0x040F Icelandic + LngItalian = LangID(0x0410) // LngItalian: 0x0410 Italian + LngJapanese = LangID(0x0411) // LngJapanese: 0x0411 Japanese + LngKorean = LangID(0x0412) // LngKorean: 0x0412 Korean + LngDutch = LangID(0x0413) // LngDutch: 0x0413 Dutch + LngNorwegianBokmal = LangID(0x0414) // LngNorwegianBokmal: 0x0414 Norwegian ? Bokmal + LngPolish = LangID(0x0415) // LngPolish: 0x0415 Polish + LngPortugueseBrazil = LangID(0x0416) // LngPortugueseBrazil: 0x0416 Portuguese (Brazil) + LngRhaetoRomanic = LangID(0x0417) // LngRhaetoRomanic: 0x0417 Rhaeto-Romanic + LngRomanian = LangID(0x0418) // LngRomanian: 0x0418 Romanian + LngRussian = LangID(0x0419) // LngRussian: 0x0419 Russian + LngCroatoSerbianLatin = LangID(0x041A) // LngCroatoSerbianLatin: 0x041A Croato-Serbian (Latin) + LngSlovak = LangID(0x041B) // LngSlovak: 0x041B Slovak + LngAlbanian = LangID(0x041C) // LngAlbanian: 0x041C Albanian + LngSwedish = LangID(0x041D) // LngSwedish: 0x041D Swedish + LngThai = LangID(0x041E) // LngThai: 0x041E Thai + LngTurkish = LangID(0x041F) // LngTurkish: 0x041F Turkish + LngUrdu = LangID(0x0420) // LngUrdu: 0x0420 Urdu + LngBahasa = LangID(0x0421) // LngBahasa: 0x0421 Bahasa + LngSimplifiedChinese = LangID(0x0804) // LngSimplifiedChinese: 0x0804 Simplified Chinese + LngSwissGerman = LangID(0x0807) // LngSwiss German: 0x0807 Swiss German + LngUKEnglish = LangID(0x0809) // LngUKEnglish: 0x0809 U.K. English + LngSpanishMexico = LangID(0x080A) // LngSpanishMexico: 0x080A Spanish (Mexico) + LngBelgianFrench = LangID(0x080C) // LngBelgian French: 0x080C Belgian French + LngSwissItalian = LangID(0x0810) // LngSwiss Italian: 0x0810 Swiss Italian + LngBelgianDutch = LangID(0x0813) // LngBelgian Dutch: 0x0813 Belgian Dutch + LngNorwegianNynorsk = LangID(0x0814) // LngNorwegianNynorsk: 0x0814 Norwegian ? Nynorsk + LngPortuguesePortugal = LangID(0x0816) // LngPortuguese (Portugal): 0x0816 Portuguese (Portugal) + LngSerboCroatianCyrillic = LangID(0x081A) // LngSerboCroatianCyrillic: 0x081A Serbo-Croatian (Cyrillic) + LngCanadianFrench = LangID(0x0C0C) // LngCanadian French: 0x0C0C Canadian French + LngSwissFrench = LangID(0x100C) // LngSwiss French: 0x100C Swiss French +) diff --git a/vendor/github.com/josephspurrier/goversioninfo/structbuild.go b/vendor/github.com/josephspurrier/goversioninfo/structbuild.go new file mode 100644 index 00000000000..e5f9d8033af --- /dev/null +++ b/vendor/github.com/josephspurrier/goversioninfo/structbuild.go @@ -0,0 +1,330 @@ +package goversioninfo + +import ( + "reflect" +) + +// ***************************************************************************** +// Structure Building +// ***************************************************************************** + +/* +Version Information Structures +http://msdn.microsoft.com/en-us/library/windows/desktop/ff468916.aspx + +VersionInfo Names +http://msdn.microsoft.com/en-us/library/windows/desktop/aa381058.aspx#string-name + +Translation: LangID +http://msdn.microsoft.com/en-us/library/windows/desktop/aa381058.aspx#langid + +Translation: CharsetID +http://msdn.microsoft.com/en-us/library/windows/desktop/aa381058.aspx#charsetid + +*/ + +// VSVersionInfo is the top level version container. +type VSVersionInfo struct { + WLength uint16 + WValueLength uint16 + WType uint16 + SzKey []byte + Padding1 []byte + Value VSFixedFileInfo + Padding2 []byte + Children VSStringFileInfo + Children2 VSVarFileInfo +} + +// VSFixedFileInfo - most of these should be left at the defaults. +type VSFixedFileInfo struct { + DwSignature uint32 + DwStrucVersion uint32 + DwFileVersionMS uint32 + DwFileVersionLS uint32 + DwProductVersionMS uint32 + DwProductVersionLS uint32 + DwFileFlagsMask uint32 + DwFileFlags uint32 + DwFileOS uint32 + DwFileType uint32 + DwFileSubtype uint32 + DwFileDateMS uint32 + DwFileDateLS uint32 +} + +// VSStringFileInfo holds multiple collections of keys and values, +// only allows for 1 collection in this package. +type VSStringFileInfo struct { + WLength uint16 + WValueLength uint16 + WType uint16 + SzKey []byte + Padding []byte + Children VSStringTable +} + +// VSStringTable holds a collection of string keys and values. +type VSStringTable struct { + WLength uint16 + WValueLength uint16 + WType uint16 + SzKey []byte + Padding []byte + Children []VSString +} + +// VSString holds the keys and values. +type VSString struct { + WLength uint16 + WValueLength uint16 + WType uint16 + SzKey []byte + Padding []byte + Value []byte +} + +// VSVarFileInfo holds the translation collection of 1. +type VSVarFileInfo struct { + WLength uint16 + WValueLength uint16 + WType uint16 + SzKey []byte + Padding []byte + Value VSVar +} + +// VSVar holds the translation key. +type VSVar struct { + WLength uint16 + WValueLength uint16 + WType uint16 + SzKey []byte + Padding []byte + Value uint32 +} + +func buildString(i int, v reflect.Value) (VSString, bool) { + sValue := string(v.Field(i).Interface().(string)) + sName := v.Type().Field(i).Name + + ss := VSString{} + + // If the value is set + if sValue != "" { + // 0 for binary, 1 for text + ss.WType = 0x01 + + // Create key + ss.SzKey = padString(sName, 0) + + // Align to 32-bit boundary + soFar := 2 + for (len(ss.SzKey)+6+soFar)%4 != 0 { + soFar += 2 + } + ss.Padding = padBytes(soFar) + soFar += len(ss.SzKey) + + // Align zeros to 32-bit boundary + zeros := 2 + for (6+soFar+(len(padString(sValue, 0)))+zeros)%4 != 0 { + zeros += 2 + } + + // Create value + ss.Value = padString(sValue, zeros) + + // Length of text in words (2 bytes) plus zero terminate word + ss.WValueLength = uint16(len(padString(sValue, 0))/2) + 1 + + // Length of structure + //ss.WLength = 6 + uint16(soFar) + (ss.WValueLength * 2) + ss.WLength = uint16(6 + soFar + len(ss.Value)) + + return ss, true + } + + return ss, false +} + +func buildStringTable(vi *VersionInfo) VSStringTable { + st := VSStringTable{} + + // Always set to 0 + st.WValueLength = 0x00 + + // 0 for binary, 1 for text + st.WType = 0x01 + + // Language identifier and Code page + st.SzKey = padString(vi.VarFileInfo.Translation.getTranslationString(), 0) + + // Align to 32-bit boundary + soFar := 2 + for (len(st.SzKey)+6+soFar)%4 != 0 { + soFar += 2 + } + st.Padding = padBytes(soFar) + soFar += len(st.SzKey) + + // Loop through the struct fields + v := reflect.ValueOf(vi.StringFileInfo) + for i := 0; i < v.NumField(); i++ { + // If the struct is valid + if r, ok := buildString(i, v); ok { + st.Children = append(st.Children, r) + st.WLength += r.WLength + } + } + + st.WLength += 6 + uint16(soFar) + + return st +} + +func buildStringFileInfo(vi *VersionInfo) VSStringFileInfo { + sf := VSStringFileInfo{} + + // Always set to 0 + sf.WValueLength = 0x00 + + // 0 for binary, 1 for text + sf.WType = 0x01 + + sf.SzKey = padString("StringFileInfo", 0) + + // Align to 32-bit boundary + soFar := 2 + for (len(sf.SzKey)+6+soFar)%4 != 0 { + soFar += 2 + } + sf.Padding = padBytes(soFar) + soFar += len(sf.SzKey) + + // Allows for more than one string table + st := buildStringTable(vi) + sf.Children = st + + sf.WLength = 6 + uint16(soFar) + st.WLength + + return sf +} + +func buildVar(vfi VarFileInfo) VSVar { + vs := VSVar{} + + // 0 for binary, 1 for text + vs.WType = 0x00 + + // Create key + vs.SzKey = padString("Translation", 0) + + // Align to 32-bit boundary + soFar := 2 + for (len(vs.SzKey)+6+soFar)%4 != 0 { + soFar += 2 + } + vs.Padding = padBytes(soFar) + soFar += len(vs.SzKey) + + // Create value + vs.Value = str2Uint32(vfi.Translation.getTranslation()) + + // Length of text in bytes + vs.WValueLength = 4 + + // Length of structure + vs.WLength = 6 + vs.WValueLength + uint16(soFar) + + return vs +} + +func buildVarFileInfo(vfi VarFileInfo) VSVarFileInfo { + vf := VSVarFileInfo{} + + // Always set to 0 + vf.WValueLength = 0x00 + + // 0 for binary, 1 for text + vf.WType = 0x01 + + vf.SzKey = padString("VarFileInfo", 0) + + // Align to 32-bit boundary + soFar := 2 + for (len(vf.SzKey)+6+soFar)%4 != 0 { + soFar += 2 + } + vf.Padding = padBytes(soFar) + soFar += len(vf.SzKey) + + // TODO Allow for more than one var table + st := buildVar(vfi) + vf.Value = st + vf.WLength = 6 + st.WLength + uint16(soFar) + + return vf +} + +func buildFixedFileInfo(vi *VersionInfo) VSFixedFileInfo { + ff := VSFixedFileInfo{} + ff.DwSignature = 0xFEEF04BD + ff.DwStrucVersion = 0x00010000 + ff.DwFileVersionMS = str2Uint32(vi.FixedFileInfo.FileVersion.getVersionHighString()) + ff.DwFileVersionLS = str2Uint32(vi.FixedFileInfo.FileVersion.getVersionLowString()) + ff.DwProductVersionMS = str2Uint32(vi.FixedFileInfo.ProductVersion.getVersionHighString()) + ff.DwProductVersionLS = str2Uint32(vi.FixedFileInfo.ProductVersion.getVersionLowString()) + ff.DwFileFlagsMask = str2Uint32(vi.FixedFileInfo.FileFlagsMask) + ff.DwFileFlags = str2Uint32(vi.FixedFileInfo.FileFlags) + ff.DwFileOS = str2Uint32(vi.FixedFileInfo.FileOS) + ff.DwFileType = str2Uint32(vi.FixedFileInfo.FileType) + ff.DwFileSubtype = str2Uint32(vi.FixedFileInfo.FileSubType) + + // According to the spec, these should be zero...ugh + /*if vi.Timestamp { + now := syscall.NsecToFiletime(time.Now().UnixNano()) + ff.DwFileDateMS = now.HighDateTime + ff.DwFileDateLS = now.LowDateTime + }*/ + + return ff +} + +// Build fills the structs with data from the config file +func (v *VersionInfo) Build() { + vi := VSVersionInfo{} + + // 0 for binary, 1 for text + vi.WType = 0x00 + + vi.SzKey = padString("VS_VERSION_INFO", 0) + + // Align to 32-bit boundary + // 6 is for the size of WLength, WValueLength, and WType (each is 1 word or 2 bytes: FF FF) + soFar := 2 + for (len(vi.SzKey)+6+soFar)%4 != 0 { + soFar += 2 + } + vi.Padding1 = padBytes(soFar) + soFar += len(vi.SzKey) + + vi.Value = buildFixedFileInfo(v) + + // Length of VSFixedFileInfo (always the same) + vi.WValueLength = 0x34 + + // Never needs padding, not included in WLength + vi.Padding2 = []byte{} + + // Build strings + vi.Children = buildStringFileInfo(v) + + // Build translation + vi.Children2 = buildVarFileInfo(v.VarFileInfo) + + // Calculate the total size + vi.WLength += 6 + uint16(soFar) + vi.WValueLength + vi.Children.WLength + vi.Children2.WLength + + v.Structure = vi +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 69220b43afc..9bed6e67fc0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -110,6 +110,10 @@ github.com/aerospike/aerospike-client-go/types/atomic github.com/aerospike/aerospike-client-go/types/particle_type github.com/aerospike/aerospike-client-go/types/rand github.com/aerospike/aerospike-client-go/utils/buffer +# github.com/akavel/rsrc v0.8.0 +github.com/akavel/rsrc/binutil +github.com/akavel/rsrc/coff +github.com/akavel/rsrc/ico # github.com/andrewkroh/sys v0.0.0-20151128191922-287798fe3e43 github.com/andrewkroh/sys/windows/svc/eventlog # github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 @@ -595,6 +599,8 @@ github.com/jmoiron/sqlx github.com/jmoiron/sqlx/reflectx # github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 github.com/joeshaw/multierror +# github.com/josephspurrier/goversioninfo v0.0.0-20200309025242-14b0ab84c6ca +github.com/josephspurrier/goversioninfo # github.com/jpillora/backoff v1.0.0 github.com/jpillora/backoff # github.com/json-iterator/go v1.1.7