blob: bb2a70fec743bb4843f2047c7788accf4c99ba91 [file] [log] [blame]
Colin Cross2fe66872015-03-30 17:20:39 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
Dan Willemsen017d8932016-08-04 15:43:03 -070018 "bytes"
19 "compress/flate"
Jeff Gastona2976952017-08-22 17:51:25 -070020 "errors"
Colin Cross2fe66872015-03-30 17:20:39 -070021 "flag"
22 "fmt"
Dan Willemsen017d8932016-08-04 15:43:03 -070023 "hash/crc32"
Colin Cross2fe66872015-03-30 17:20:39 -070024 "io"
25 "io/ioutil"
Nan Zhang9067b042017-03-17 14:04:43 -070026 "log"
Colin Cross2fe66872015-03-30 17:20:39 -070027 "os"
28 "path/filepath"
Dan Willemsen017d8932016-08-04 15:43:03 -070029 "runtime"
30 "runtime/pprof"
31 "runtime/trace"
Jeff Gastona2976952017-08-22 17:51:25 -070032 "sort"
Colin Cross2fe66872015-03-30 17:20:39 -070033 "strings"
Dan Willemsen017d8932016-08-04 15:43:03 -070034 "sync"
Colin Cross2fe66872015-03-30 17:20:39 -070035 "time"
Dan Willemsen017d8932016-08-04 15:43:03 -070036
Jeff Gastona2976952017-08-22 17:51:25 -070037 "android/soong/jar"
Dan Willemsen017d8932016-08-04 15:43:03 -070038 "android/soong/third_party/zip"
Colin Cross2fe66872015-03-30 17:20:39 -070039)
40
Dan Willemsen017d8932016-08-04 15:43:03 -070041// Block size used during parallel compression of a single file.
42const parallelBlockSize = 1 * 1024 * 1024 // 1MB
43
44// Minimum file size to use parallel compression. It requires more
45// flate.Writer allocations, since we can't change the dictionary
46// during Reset
47const minParallelFileSize = parallelBlockSize * 6
48
49// Size of the ZIP compression window (32KB)
50const windowSize = 32 * 1024
51
52type nopCloser struct {
53 io.Writer
54}
55
56func (nopCloser) Close() error {
57 return nil
58}
59
Colin Cross2fe66872015-03-30 17:20:39 -070060type fileArg struct {
Nan Zhangf281bd82017-04-25 16:47:45 -070061 pathPrefixInZip, sourcePrefixToStrip string
62 sourceFiles []string
Nan Zhang9067b042017-03-17 14:04:43 -070063}
64
65type pathMapping struct {
66 dest, src string
Nan Zhangf281bd82017-04-25 16:47:45 -070067 zipMethod uint16
68}
69
70type uniqueSet map[string]bool
71
72func (u *uniqueSet) String() string {
73 return `""`
74}
75
76func (u *uniqueSet) Set(s string) error {
77 if _, found := (*u)[s]; found {
78 return fmt.Errorf("File %q was specified twice as a file to not deflate", s)
79 } else {
80 (*u)[s] = true
81 }
82
83 return nil
Colin Cross2fe66872015-03-30 17:20:39 -070084}
85
86type fileArgs []fileArg
87
Nan Zhangf281bd82017-04-25 16:47:45 -070088type file struct{}
89
90type listFiles struct{}
91
92func (f *file) String() string {
Colin Cross2fe66872015-03-30 17:20:39 -070093 return `""`
94}
95
Nan Zhangf281bd82017-04-25 16:47:45 -070096func (f *file) Set(s string) error {
Colin Cross2fe66872015-03-30 17:20:39 -070097 if *relativeRoot == "" {
Nan Zhang9067b042017-03-17 14:04:43 -070098 return fmt.Errorf("must pass -C before -f or -l")
Colin Cross2fe66872015-03-30 17:20:39 -070099 }
100
Nan Zhangf281bd82017-04-25 16:47:45 -0700101 fArgs = append(fArgs, fileArg{
102 pathPrefixInZip: filepath.Clean(*rootPrefix),
103 sourcePrefixToStrip: filepath.Clean(*relativeRoot),
104 sourceFiles: []string{s},
105 })
106
Colin Cross2fe66872015-03-30 17:20:39 -0700107 return nil
108}
109
Nan Zhangf281bd82017-04-25 16:47:45 -0700110func (l *listFiles) String() string {
111 return `""`
112}
113
114func (l *listFiles) Set(s string) error {
115 if *relativeRoot == "" {
116 return fmt.Errorf("must pass -C before -f or -l")
117 }
118
119 list, err := ioutil.ReadFile(s)
120 if err != nil {
121 return err
122 }
123
124 fArgs = append(fArgs, fileArg{
125 pathPrefixInZip: filepath.Clean(*rootPrefix),
126 sourcePrefixToStrip: filepath.Clean(*relativeRoot),
127 sourceFiles: strings.Split(string(list), "\n"),
128 })
129
130 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700131}
132
133var (
Dan Willemsen47ec28f2016-08-10 16:12:30 -0700134 out = flag.String("o", "", "file to write zip file to")
135 manifest = flag.String("m", "", "input jar manifest file name")
136 directories = flag.Bool("d", false, "include directories in zip")
Nan Zhang9067b042017-03-17 14:04:43 -0700137 rootPrefix = flag.String("P", "", "path prefix within the zip at which to place files")
Colin Cross2fe66872015-03-30 17:20:39 -0700138 relativeRoot = flag.String("C", "", "path to use as relative root of files in next -f or -l argument")
Dan Willemsen017d8932016-08-04 15:43:03 -0700139 parallelJobs = flag.Int("j", runtime.NumCPU(), "number of parallel threads to use")
140 compLevel = flag.Int("L", 5, "deflate compression level (0-9)")
Jeff Gastona2976952017-08-22 17:51:25 -0700141 emulateJar = flag.Bool("jar", false, "modify the resultant .zip to emulate the output of 'jar'")
Nan Zhang9067b042017-03-17 14:04:43 -0700142
Nan Zhangf281bd82017-04-25 16:47:45 -0700143 fArgs fileArgs
144 nonDeflatedFiles = make(uniqueSet)
Dan Willemsen017d8932016-08-04 15:43:03 -0700145
146 cpuProfile = flag.String("cpuprofile", "", "write cpu profile to file")
147 traceFile = flag.String("trace", "", "write trace to file")
Colin Cross2fe66872015-03-30 17:20:39 -0700148)
149
150func init() {
Nan Zhangf281bd82017-04-25 16:47:45 -0700151 flag.Var(&listFiles{}, "l", "file containing list of .class files")
152 flag.Var(&file{}, "f", "file to include in zip")
153 flag.Var(&nonDeflatedFiles, "s", "file path to be stored within the zip without compression")
Colin Cross2fe66872015-03-30 17:20:39 -0700154}
155
156func usage() {
Dan Willemsen47ec28f2016-08-10 16:12:30 -0700157 fmt.Fprintf(os.Stderr, "usage: soong_zip -o zipfile [-m manifest] -C dir [-f|-l file]...\n")
Colin Cross2fe66872015-03-30 17:20:39 -0700158 flag.PrintDefaults()
159 os.Exit(2)
160}
161
Colin Crosse19c7932015-04-24 15:08:38 -0700162type zipWriter struct {
Colin Cross2fe66872015-03-30 17:20:39 -0700163 time time.Time
164 createdDirs map[string]bool
165 directories bool
Colin Crosse19c7932015-04-24 15:08:38 -0700166
Dan Willemsen017d8932016-08-04 15:43:03 -0700167 errors chan error
168 writeOps chan chan *zipEntry
169
Jeff Gaston175f34c2017-08-17 21:43:21 -0700170 cpuRateLimiter *CPURateLimiter
171 memoryRateLimiter *MemoryRateLimiter
Dan Willemsen017d8932016-08-04 15:43:03 -0700172
173 compressorPool sync.Pool
174 compLevel int
175}
176
177type zipEntry struct {
178 fh *zip.FileHeader
179
180 // List of delayed io.Reader
181 futureReaders chan chan io.Reader
Jeff Gaston175f34c2017-08-17 21:43:21 -0700182
183 // Only used for passing into the MemoryRateLimiter to ensure we
184 // release as much memory as much as we request
185 allocatedSize int64
Colin Cross2fe66872015-03-30 17:20:39 -0700186}
187
188func main() {
189 flag.Parse()
190
Dan Willemsen017d8932016-08-04 15:43:03 -0700191 if *cpuProfile != "" {
192 f, err := os.Create(*cpuProfile)
193 if err != nil {
194 fmt.Fprintln(os.Stderr, err.Error())
195 os.Exit(1)
196 }
197 defer f.Close()
198 pprof.StartCPUProfile(f)
199 defer pprof.StopCPUProfile()
200 }
201
202 if *traceFile != "" {
203 f, err := os.Create(*traceFile)
204 if err != nil {
205 fmt.Fprintln(os.Stderr, err.Error())
206 os.Exit(1)
207 }
208 defer f.Close()
209 err = trace.Start(f)
210 if err != nil {
211 fmt.Fprintln(os.Stderr, err.Error())
212 os.Exit(1)
213 }
214 defer trace.Stop()
215 }
216
Colin Cross2fe66872015-03-30 17:20:39 -0700217 if *out == "" {
218 fmt.Fprintf(os.Stderr, "error: -o is required\n")
219 usage()
220 }
221
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700222 if *emulateJar {
223 *directories = true
224 }
225
Colin Crosse19c7932015-04-24 15:08:38 -0700226 w := &zipWriter{
Dan Willemsen77a6b862016-08-04 20:38:47 -0700227 time: time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC),
Colin Cross2fe66872015-03-30 17:20:39 -0700228 createdDirs: make(map[string]bool),
229 directories: *directories,
Dan Willemsen017d8932016-08-04 15:43:03 -0700230 compLevel: *compLevel,
Colin Cross2fe66872015-03-30 17:20:39 -0700231 }
232
Nan Zhang9067b042017-03-17 14:04:43 -0700233 pathMappings := []pathMapping{}
234 set := make(map[string]string)
235
Nan Zhangf281bd82017-04-25 16:47:45 -0700236 for _, fa := range fArgs {
237 for _, src := range fa.sourceFiles {
238 if err := fillPathPairs(fa.pathPrefixInZip,
239 fa.sourcePrefixToStrip, src, set, &pathMappings); err != nil {
Nan Zhang9067b042017-03-17 14:04:43 -0700240 log.Fatal(err)
241 }
242 }
243 }
244
Nan Zhang9067b042017-03-17 14:04:43 -0700245 err := w.write(*out, pathMappings, *manifest)
Colin Cross2fe66872015-03-30 17:20:39 -0700246 if err != nil {
247 fmt.Fprintln(os.Stderr, err.Error())
248 os.Exit(1)
249 }
250}
251
Nan Zhang9067b042017-03-17 14:04:43 -0700252func fillPathPairs(prefix, rel, src string, set map[string]string, pathMappings *[]pathMapping) error {
253 src = strings.TrimSpace(src)
254 if src == "" {
255 return nil
256 }
257 src = filepath.Clean(src)
258 dest, err := filepath.Rel(rel, src)
259 if err != nil {
260 return err
261 }
262 dest = filepath.Join(prefix, dest)
263
264 if _, found := set[dest]; found {
265 return fmt.Errorf("found two file paths to be copied into dest path: %q,"+
266 " both [%q]%q and [%q]%q!",
267 dest, dest, src, dest, set[dest])
268 } else {
269 set[dest] = src
270 }
271
Nan Zhangf281bd82017-04-25 16:47:45 -0700272 zipMethod := zip.Deflate
273 if _, found := nonDeflatedFiles[dest]; found {
274 zipMethod = zip.Store
275 }
276 *pathMappings = append(*pathMappings,
277 pathMapping{dest: dest, src: src, zipMethod: zipMethod})
Nan Zhang9067b042017-03-17 14:04:43 -0700278
279 return nil
280}
281
Jeff Gastona2976952017-08-22 17:51:25 -0700282func jarSort(mappings []pathMapping) {
283 less := func(i int, j int) (smaller bool) {
284 return jar.EntryNamesLess(mappings[i].dest, mappings[j].dest)
285 }
286 sort.SliceStable(mappings, less)
287}
288
Nan Zhang9067b042017-03-17 14:04:43 -0700289func (z *zipWriter) write(out string, pathMappings []pathMapping, manifest string) error {
Colin Cross2fe66872015-03-30 17:20:39 -0700290 f, err := os.Create(out)
291 if err != nil {
292 return err
293 }
294
295 defer f.Close()
296 defer func() {
297 if err != nil {
298 os.Remove(out)
299 }
300 }()
301
Dan Willemsen017d8932016-08-04 15:43:03 -0700302 z.errors = make(chan error)
303 defer close(z.errors)
Colin Cross2fe66872015-03-30 17:20:39 -0700304
Dan Willemsen017d8932016-08-04 15:43:03 -0700305 // This channel size can be essentially unlimited -- it's used as a fifo
306 // queue decouple the CPU and IO loads. Directories don't require any
307 // compression time, but still cost some IO. Similar with small files that
308 // can be very fast to compress. Some files that are more difficult to
309 // compress won't take a corresponding longer time writing out.
310 //
311 // The optimum size here depends on your CPU and IO characteristics, and
312 // the the layout of your zip file. 1000 was chosen mostly at random as
313 // something that worked reasonably well for a test file.
314 //
315 // The RateLimit object will put the upper bounds on the number of
316 // parallel compressions and outstanding buffers.
317 z.writeOps = make(chan chan *zipEntry, 1000)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700318 z.cpuRateLimiter = NewCPURateLimiter(int64(*parallelJobs))
319 z.memoryRateLimiter = NewMemoryRateLimiter(0)
320 defer func() {
321 z.cpuRateLimiter.Stop()
322 z.memoryRateLimiter.Stop()
323 }()
Jeff Gastona2976952017-08-22 17:51:25 -0700324
325 if manifest != "" {
326 if !*emulateJar {
327 return errors.New("must specify --jar when specifying a manifest via -m")
328 }
329 pathMappings = append(pathMappings, pathMapping{"META-INF/MANIFEST.MF", manifest, zip.Deflate})
330 }
331
332 if *emulateJar {
333 jarSort(pathMappings)
334 }
335
Dan Willemsen017d8932016-08-04 15:43:03 -0700336 go func() {
337 var err error
338 defer close(z.writeOps)
339
Nan Zhang9067b042017-03-17 14:04:43 -0700340 for _, ele := range pathMappings {
Nan Zhangf281bd82017-04-25 16:47:45 -0700341 err = z.writeFile(ele.dest, ele.src, ele.zipMethod)
Dan Willemsen017d8932016-08-04 15:43:03 -0700342 if err != nil {
343 z.errors <- err
344 return
345 }
346 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700347 }()
348
349 zipw := zip.NewWriter(f)
350
351 var currentWriteOpChan chan *zipEntry
352 var currentWriter io.WriteCloser
353 var currentReaders chan chan io.Reader
354 var currentReader chan io.Reader
355 var done bool
356
357 for !done {
358 var writeOpsChan chan chan *zipEntry
359 var writeOpChan chan *zipEntry
360 var readersChan chan chan io.Reader
361
362 if currentReader != nil {
363 // Only read and process errors
364 } else if currentReaders != nil {
365 readersChan = currentReaders
366 } else if currentWriteOpChan != nil {
367 writeOpChan = currentWriteOpChan
368 } else {
369 writeOpsChan = z.writeOps
370 }
371
372 select {
373 case writeOp, ok := <-writeOpsChan:
374 if !ok {
375 done = true
376 }
377
378 currentWriteOpChan = writeOp
379
380 case op := <-writeOpChan:
381 currentWriteOpChan = nil
382
383 if op.fh.Method == zip.Deflate {
384 currentWriter, err = zipw.CreateCompressedHeader(op.fh)
385 } else {
386 var zw io.Writer
Jeff Gastonc5eb66d2017-08-24 14:11:27 -0700387
388 op.fh.CompressedSize64 = op.fh.UncompressedSize64
389
390 zw, err = zipw.CreateHeaderAndroid(op.fh)
Dan Willemsen017d8932016-08-04 15:43:03 -0700391 currentWriter = nopCloser{zw}
392 }
393 if err != nil {
394 return err
395 }
396
397 currentReaders = op.futureReaders
398 if op.futureReaders == nil {
399 currentWriter.Close()
400 currentWriter = nil
401 }
Jeff Gaston175f34c2017-08-17 21:43:21 -0700402 z.memoryRateLimiter.Finish(op.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700403
404 case futureReader, ok := <-readersChan:
405 if !ok {
406 // Done with reading
407 currentWriter.Close()
408 currentWriter = nil
409 currentReaders = nil
410 }
411
412 currentReader = futureReader
413
414 case reader := <-currentReader:
Jeff Gaston175f34c2017-08-17 21:43:21 -0700415 _, err = io.Copy(currentWriter, reader)
Dan Willemsen017d8932016-08-04 15:43:03 -0700416 if err != nil {
417 return err
418 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700419
420 currentReader = nil
421
422 case err = <-z.errors:
Colin Cross2fe66872015-03-30 17:20:39 -0700423 return err
424 }
425 }
426
Dan Willemsen017d8932016-08-04 15:43:03 -0700427 // One last chance to catch an error
428 select {
429 case err = <-z.errors:
430 return err
431 default:
432 zipw.Close()
433 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700434 }
Colin Cross2fe66872015-03-30 17:20:39 -0700435}
436
Nan Zhangf281bd82017-04-25 16:47:45 -0700437func (z *zipWriter) writeFile(dest, src string, method uint16) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700438 var fileSize int64
Dan Willemsen10462b32017-03-15 19:02:51 -0700439 var executable bool
Dan Willemsen017d8932016-08-04 15:43:03 -0700440
Nan Zhang9067b042017-03-17 14:04:43 -0700441 if s, err := os.Lstat(src); err != nil {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700442 return err
443 } else if s.IsDir() {
Colin Cross957cc4e2015-04-24 15:10:32 -0700444 if z.directories {
Nan Zhang9067b042017-03-17 14:04:43 -0700445 return z.writeDirectory(dest)
Colin Cross957cc4e2015-04-24 15:10:32 -0700446 }
447 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700448 } else if s.Mode()&os.ModeSymlink != 0 {
Nan Zhang9067b042017-03-17 14:04:43 -0700449 return z.writeSymlink(dest, src)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700450 } else if !s.Mode().IsRegular() {
Nan Zhang9067b042017-03-17 14:04:43 -0700451 return fmt.Errorf("%s is not a file, directory, or symlink", src)
Dan Willemsen017d8932016-08-04 15:43:03 -0700452 } else {
453 fileSize = s.Size()
Dan Willemsen10462b32017-03-15 19:02:51 -0700454 executable = s.Mode()&0100 != 0
Colin Cross957cc4e2015-04-24 15:10:32 -0700455 }
456
Colin Crosse19c7932015-04-24 15:08:38 -0700457 if z.directories {
Nan Zhang9067b042017-03-17 14:04:43 -0700458 dir, _ := filepath.Split(dest)
Colin Crosse19c7932015-04-24 15:08:38 -0700459 err := z.writeDirectory(dir)
460 if err != nil {
461 return err
Colin Cross2fe66872015-03-30 17:20:39 -0700462 }
463 }
464
Dan Willemsen017d8932016-08-04 15:43:03 -0700465 compressChan := make(chan *zipEntry, 1)
466 z.writeOps <- compressChan
467
468 // Pre-fill a zipEntry, it will be sent in the compressChan once
469 // we're sure about the Method and CRC.
470 ze := &zipEntry{
471 fh: &zip.FileHeader{
Nan Zhang9067b042017-03-17 14:04:43 -0700472 Name: dest,
Nan Zhangf281bd82017-04-25 16:47:45 -0700473 Method: method,
Dan Willemsen017d8932016-08-04 15:43:03 -0700474
475 UncompressedSize64: uint64(fileSize),
476 },
477 }
478 ze.fh.SetModTime(z.time)
Dan Willemsen10462b32017-03-15 19:02:51 -0700479 if executable {
480 ze.fh.SetMode(0700)
481 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700482
Nan Zhang9067b042017-03-17 14:04:43 -0700483 r, err := os.Open(src)
Dan Willemsen017d8932016-08-04 15:43:03 -0700484 if err != nil {
485 return err
486 }
487
Jeff Gaston175f34c2017-08-17 21:43:21 -0700488 ze.allocatedSize = fileSize
489 z.cpuRateLimiter.Request()
490 z.memoryRateLimiter.Request(ze.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700491
Nan Zhangf281bd82017-04-25 16:47:45 -0700492 if method == zip.Deflate && fileSize >= minParallelFileSize {
Dan Willemsen017d8932016-08-04 15:43:03 -0700493 wg := new(sync.WaitGroup)
494
495 // Allocate enough buffer to hold all readers. We'll limit
496 // this based on actual buffer sizes in RateLimit.
497 ze.futureReaders = make(chan chan io.Reader, (fileSize/parallelBlockSize)+1)
498
499 // Calculate the CRC in the background, since reading the entire
500 // file could take a while.
501 //
502 // We could split this up into chuncks as well, but it's faster
503 // than the compression. Due to the Go Zip API, we also need to
504 // know the result before we can begin writing the compressed
505 // data out to the zipfile.
506 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700507 go z.crcFile(r, ze, compressChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700508
509 for start := int64(0); start < fileSize; start += parallelBlockSize {
510 sr := io.NewSectionReader(r, start, parallelBlockSize)
511 resultChan := make(chan io.Reader, 1)
512 ze.futureReaders <- resultChan
513
Jeff Gaston175f34c2017-08-17 21:43:21 -0700514 z.cpuRateLimiter.Request()
Dan Willemsen017d8932016-08-04 15:43:03 -0700515
516 last := !(start+parallelBlockSize < fileSize)
517 var dict []byte
518 if start >= windowSize {
519 dict, err = ioutil.ReadAll(io.NewSectionReader(r, start-windowSize, windowSize))
520 }
521
522 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700523 go z.compressPartialFile(sr, dict, last, resultChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700524 }
525
526 close(ze.futureReaders)
527
528 // Close the file handle after all readers are done
529 go func(wg *sync.WaitGroup, f *os.File) {
530 wg.Wait()
531 f.Close()
532 }(wg, r)
533 } else {
Jeff Gaston175f34c2017-08-17 21:43:21 -0700534 go z.compressWholeFile(ze, r, compressChan)
Dan Willemsen017d8932016-08-04 15:43:03 -0700535 }
536
537 return nil
538}
539
Jeff Gaston175f34c2017-08-17 21:43:21 -0700540func (z *zipWriter) crcFile(r io.Reader, ze *zipEntry, resultChan chan *zipEntry, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700541 defer wg.Done()
Jeff Gaston175f34c2017-08-17 21:43:21 -0700542 defer z.cpuRateLimiter.Finish()
Dan Willemsen017d8932016-08-04 15:43:03 -0700543
544 crc := crc32.NewIEEE()
545 _, err := io.Copy(crc, r)
546 if err != nil {
547 z.errors <- err
548 return
549 }
550
551 ze.fh.CRC32 = crc.Sum32()
552 resultChan <- ze
553 close(resultChan)
554}
555
Jeff Gaston175f34c2017-08-17 21:43:21 -0700556func (z *zipWriter) compressPartialFile(r io.Reader, dict []byte, last bool, resultChan chan io.Reader, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700557 defer wg.Done()
558
559 result, err := z.compressBlock(r, dict, last)
560 if err != nil {
561 z.errors <- err
562 return
563 }
564
Jeff Gaston175f34c2017-08-17 21:43:21 -0700565 z.cpuRateLimiter.Finish()
566
Dan Willemsen017d8932016-08-04 15:43:03 -0700567 resultChan <- result
568}
569
570func (z *zipWriter) compressBlock(r io.Reader, dict []byte, last bool) (*bytes.Buffer, error) {
571 buf := new(bytes.Buffer)
572 var fw *flate.Writer
573 var err error
574 if len(dict) > 0 {
575 // There's no way to Reset a Writer with a new dictionary, so
576 // don't use the Pool
577 fw, err = flate.NewWriterDict(buf, z.compLevel, dict)
578 } else {
579 var ok bool
580 if fw, ok = z.compressorPool.Get().(*flate.Writer); ok {
581 fw.Reset(buf)
582 } else {
583 fw, err = flate.NewWriter(buf, z.compLevel)
584 }
585 defer z.compressorPool.Put(fw)
586 }
587 if err != nil {
588 return nil, err
589 }
590
591 _, err = io.Copy(fw, r)
592 if err != nil {
593 return nil, err
594 }
595 if last {
596 fw.Close()
597 } else {
598 fw.Flush()
599 }
600
601 return buf, nil
602}
603
Jeff Gaston175f34c2017-08-17 21:43:21 -0700604func (z *zipWriter) compressWholeFile(ze *zipEntry, r *os.File, compressChan chan *zipEntry) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700605 defer r.Close()
606
Dan Willemsen017d8932016-08-04 15:43:03 -0700607 crc := crc32.NewIEEE()
Dan Willemsena8b55022017-03-15 21:49:26 -0700608 _, err := io.Copy(crc, r)
Colin Cross2fe66872015-03-30 17:20:39 -0700609 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700610 z.errors <- err
611 return
Colin Cross2fe66872015-03-30 17:20:39 -0700612 }
613
Dan Willemsena8b55022017-03-15 21:49:26 -0700614 ze.fh.CRC32 = crc.Sum32()
Colin Cross2fe66872015-03-30 17:20:39 -0700615
Dan Willemsen017d8932016-08-04 15:43:03 -0700616 _, err = r.Seek(0, 0)
Colin Cross2fe66872015-03-30 17:20:39 -0700617 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700618 z.errors <- err
619 return
Colin Cross2fe66872015-03-30 17:20:39 -0700620 }
621
Nan Zhangf281bd82017-04-25 16:47:45 -0700622 readFile := func(r *os.File) ([]byte, error) {
623 _, err = r.Seek(0, 0)
624 if err != nil {
625 return nil, err
626 }
627
628 buf, err := ioutil.ReadAll(r)
629 if err != nil {
630 return nil, err
631 }
632
633 return buf, nil
634 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700635
Dan Willemsena8b55022017-03-15 21:49:26 -0700636 ze.futureReaders = make(chan chan io.Reader, 1)
Dan Willemsen017d8932016-08-04 15:43:03 -0700637 futureReader := make(chan io.Reader, 1)
638 ze.futureReaders <- futureReader
639 close(ze.futureReaders)
640
Nan Zhangf281bd82017-04-25 16:47:45 -0700641 if ze.fh.Method == zip.Deflate {
642 compressed, err := z.compressBlock(r, nil, true)
643 if err != nil {
644 z.errors <- err
645 return
646 }
647 if uint64(compressed.Len()) < ze.fh.UncompressedSize64 {
648 futureReader <- compressed
Nan Zhangf281bd82017-04-25 16:47:45 -0700649 } else {
650 buf, err := readFile(r)
651 if err != nil {
652 z.errors <- err
653 return
654 }
655 ze.fh.Method = zip.Store
656 futureReader <- bytes.NewReader(buf)
Nan Zhangf281bd82017-04-25 16:47:45 -0700657 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700658 } else {
Nan Zhangf281bd82017-04-25 16:47:45 -0700659 buf, err := readFile(r)
Dan Willemsen017d8932016-08-04 15:43:03 -0700660 if err != nil {
661 z.errors <- err
662 return
663 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700664 ze.fh.Method = zip.Store
665 futureReader <- bytes.NewReader(buf)
Dan Willemsen017d8932016-08-04 15:43:03 -0700666 }
Nan Zhangf281bd82017-04-25 16:47:45 -0700667
Jeff Gaston175f34c2017-08-17 21:43:21 -0700668 z.cpuRateLimiter.Finish()
669
Dan Willemsen017d8932016-08-04 15:43:03 -0700670 close(futureReader)
671
672 compressChan <- ze
673 close(compressChan)
Colin Cross2fe66872015-03-30 17:20:39 -0700674}
Colin Crosse19c7932015-04-24 15:08:38 -0700675
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700676func (z *zipWriter) addExtraField(zipHeader *zip.FileHeader, fieldHeader [2]byte, data []byte) {
677 // add the field header in little-endian order
678 zipHeader.Extra = append(zipHeader.Extra, fieldHeader[1], fieldHeader[0])
679
680 // specify the length of the data (in little-endian order)
681 dataLength := len(data)
682 lengthBytes := []byte{byte(dataLength % 256), byte(dataLength / 256)}
683 zipHeader.Extra = append(zipHeader.Extra, lengthBytes...)
684
685 // add the contents of the extra field
686 zipHeader.Extra = append(zipHeader.Extra, data...)
687}
688
Colin Crosse19c7932015-04-24 15:08:38 -0700689func (z *zipWriter) writeDirectory(dir string) error {
Jeff Gaston2d174132017-08-15 18:05:56 -0700690 // clean the input
691 cleanDir := filepath.Clean(dir)
692
693 // discover any uncreated directories in the path
694 zipDirs := []string{}
695 for cleanDir != "" && cleanDir != "." && !z.createdDirs[cleanDir] {
696
697 z.createdDirs[cleanDir] = true
698 // parent directories precede their children
699 zipDirs = append([]string{cleanDir}, zipDirs...)
700
701 cleanDir = filepath.Dir(cleanDir)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700702 }
703
Jeff Gaston2d174132017-08-15 18:05:56 -0700704 // make a directory entry for each uncreated directory
705 for _, cleanDir := range zipDirs {
Colin Crosse19c7932015-04-24 15:08:38 -0700706 dirHeader := &zip.FileHeader{
Jeff Gaston2d174132017-08-15 18:05:56 -0700707 Name: cleanDir + "/",
Colin Crosse19c7932015-04-24 15:08:38 -0700708 }
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700709 dirHeader.SetMode(0700 | os.ModeDir)
Colin Crosse19c7932015-04-24 15:08:38 -0700710 dirHeader.SetModTime(z.time)
711
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700712 if *emulateJar && dir == "META-INF/" {
713 // Jar files have a 0-length extra field with header "CAFE"
714 z.addExtraField(dirHeader, [2]byte{0xca, 0xfe}, []byte{})
715 }
716
Dan Willemsen017d8932016-08-04 15:43:03 -0700717 ze := make(chan *zipEntry, 1)
718 ze <- &zipEntry{
719 fh: dirHeader,
Colin Crosse19c7932015-04-24 15:08:38 -0700720 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700721 close(ze)
722 z.writeOps <- ze
Colin Crosse19c7932015-04-24 15:08:38 -0700723 }
724
725 return nil
726}
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700727
728func (z *zipWriter) writeSymlink(rel, file string) error {
729 if z.directories {
730 dir, _ := filepath.Split(rel)
731 if err := z.writeDirectory(dir); err != nil {
732 return err
733 }
734 }
735
736 fileHeader := &zip.FileHeader{
737 Name: rel,
738 }
739 fileHeader.SetModTime(z.time)
740 fileHeader.SetMode(0700 | os.ModeSymlink)
741
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700742 dest, err := os.Readlink(file)
743 if err != nil {
744 return err
745 }
746
Dan Willemsen017d8932016-08-04 15:43:03 -0700747 ze := make(chan *zipEntry, 1)
748 futureReaders := make(chan chan io.Reader, 1)
749 futureReader := make(chan io.Reader, 1)
750 futureReaders <- futureReader
751 close(futureReaders)
752 futureReader <- bytes.NewBufferString(dest)
753 close(futureReader)
754
Dan Willemsen017d8932016-08-04 15:43:03 -0700755 ze <- &zipEntry{
756 fh: fileHeader,
757 futureReaders: futureReaders,
758 }
759 close(ze)
760 z.writeOps <- ze
761
762 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700763}