1// Copyright 2011 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package os
6
7import (
8	"syscall"
9	"time"
10)
11
12const _BIT16SZ = 2
13
14func sameFile(fs1, fs2 *fileStat) bool {
15	a := fs1.sys.(*syscall.Dir)
16	b := fs2.sys.(*syscall.Dir)
17	return a.Qid.Path == b.Qid.Path && a.Type == b.Type && a.Dev == b.Dev
18}
19
20func fileInfoFromStat(d *syscall.Dir) FileInfo {
21	fs := &fileStat{
22		name:    d.Name,
23		size:    int64(d.Length),
24		modTime: time.Unix(int64(d.Mtime), 0),
25		sys:     d,
26	}
27	fs.mode = FileMode(d.Mode & 0777)
28	if d.Mode&syscall.DMDIR != 0 {
29		fs.mode |= ModeDir
30	}
31	if d.Mode&syscall.DMAPPEND != 0 {
32		fs.mode |= ModeAppend
33	}
34	if d.Mode&syscall.DMEXCL != 0 {
35		fs.mode |= ModeExclusive
36	}
37	if d.Mode&syscall.DMTMP != 0 {
38		fs.mode |= ModeTemporary
39	}
40	return fs
41}
42
43// arg is an open *File or a path string.
44func dirstat(arg interface{}) (*syscall.Dir, error) {
45	var name string
46	var err error
47
48	size := syscall.STATFIXLEN + 16*4
49
50	for i := 0; i < 2; i++ {
51		buf := make([]byte, _BIT16SZ+size)
52
53		var n int
54		switch a := arg.(type) {
55		case *File:
56			name = a.name
57			n, err = syscall.Fstat(a.fd, buf)
58		case string:
59			name = a
60			n, err = syscall.Stat(a, buf)
61		default:
62			panic("phase error in dirstat")
63		}
64
65		if n < _BIT16SZ {
66			return nil, &PathError{"stat", name, err}
67		}
68
69		// Pull the real size out of the stat message.
70		size = int(uint16(buf[0]) | uint16(buf[1])<<8)
71
72		// If the stat message is larger than our buffer we will
73		// go around the loop and allocate one that is big enough.
74		if size <= n {
75			d, err := syscall.UnmarshalDir(buf[:n])
76			if err != nil {
77				return nil, &PathError{"stat", name, err}
78			}
79			return d, nil
80		}
81
82	}
83
84	if err == nil {
85		err = syscall.ErrBadStat
86	}
87
88	return nil, &PathError{"stat", name, err}
89}
90
91// Stat returns a FileInfo describing the named file.
92// If there is an error, it will be of type *PathError.
93func Stat(name string) (FileInfo, error) {
94	d, err := dirstat(name)
95	if err != nil {
96		return nil, err
97	}
98	return fileInfoFromStat(d), nil
99}
100
101// Lstat returns a FileInfo describing the named file.
102// If the file is a symbolic link, the returned FileInfo
103// describes the symbolic link.  Lstat makes no attempt to follow the link.
104// If there is an error, it will be of type *PathError.
105func Lstat(name string) (FileInfo, error) {
106	return Stat(name)
107}
108
109// For testing.
110func atime(fi FileInfo) time.Time {
111	return time.Unix(int64(fi.Sys().(*syscall.Dir).Atime), 0)
112}
113