// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed 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.

//go:build !windows

package main

import (
	"runtime"
	"syscall"
)

func setUlimit() error {
	var lim syscall.Rlimit

	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim)
	if err != nil {
		return err
	}

	// set the "soft" file descriptor to the maximum
	// allowed by a userspace program.
	// http://man7.org/linux/man-pages/man2/getrlimit.2.html
	lim.Cur = lim.Max

	// If we're on darwin, work around the fact that Getrlimit reports
	// the wrong value. See https://github.com/golang/go/issues/30401
	if runtime.GOOS == "darwin" && lim.Cur > 10240 {
		// The max file limit is 10240, even though
		// the max returned by Getrlimit is 1<<63-1.
		// This is OPEN_MAX in sys/syslimits.h.
		lim.Cur = 10240
	}

	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &lim)
	if err != nil {
		return err
	}

	return nil
}
